"use strict"; /* ===================== constants ===================== */ const SPORTS = { basketball:{label:"Basketball", A:1.0, M:0.35, B:0.6, C:0.25, pre:6, post:3, gap:7, titles:["Crowd erupts","Big reaction","Fast break","Ball in the air"]}, soccer:{label:"Soccer", A:1.0, M:0.3, B:0.5, C:0.4, pre:10, post:4, gap:15, titles:["Goal-mouth chance","Big reaction","Counterattack","Shot on goal"]}, volleyball:{label:"Volleyball", A:0.9, M:0.4, B:0.8, C:0.1, pre:5, post:3, gap:6, titles:["Point won","Big reaction","Long rally","Kill attempt"]}, football:{label:"Football", A:1.0, M:0.5, B:0.3, C:0.3, pre:7, post:4, gap:12, titles:["Big play","Big reaction","Breakaway run","Pass in the air"]}, baseball:{label:"Baseball / Softball", A:1.0, M:0.6, B:0.5, C:0.1, pre:5, post:6, gap:10, titles:["Big hit","Big reaction","Play on the bases","Ball in play"]}, hockey:{label:"Hockey", A:1.0, M:0.5, B:0.2, C:0.4, pre:8, post:4, gap:10, titles:["Scoring chance","Big reaction","Rush up the ice","Shot on net"]}, tennis:{label:"Tennis / Pickleball", A:0.9, M:0.5, B:0.7, C:0.0, pre:6, post:3, gap:8, titles:["Winner","Big reaction","Long rally","Big serve"]}, other:{label:"Other sport", A:1.0, M:0.5, B:0.4, C:0.2, pre:6, post:4, gap:8, titles:["Highlight","Big reaction","Fast action","Ball in the air"]} }; const SIZES = {tight:{k:1.1, per:0.35, min:4}, standard:{k:0.35, per:0.7, min:7}, generous:{k:0.25, per:1.2, min:10}}; const GRID = 0.25; // seconds per score sample const $ = s => document.querySelector(s); const fmt = s => { s = Math.max(0, s||0); const m = Math.floor(s/60), r = Math.floor(s%60); return m + ":" + String(r).padStart(2,"0"); }; const clamp = (v,a,b) => Math.max(a, Math.min(b, v)); /* ===================== state ===================== */ const S = { source:{name:"Sample game · Suns vs Rockets", sub:"Synthetic demo footage · free to use", url:"", sample:true, file:null}, sport:"basketball", size:"standard", mineFirst:false, follow:null, // {anchors:[{t,box,sig}], number, name, team, color} an:null, // analysis track:null, // [{t,cx,cy,w,h,ok}] clips:[], active:-1, engine:"loading", worker:null, playerCam:false, aiView:true, slow:false, picking:false, pickMode:null, hoops:[], shots:null, hoopDraft:null, reel:null, busy:false, lastAnalyzeSec:null }; const vid = $("#vid"), scanVid = $("#scanVid"), view = $("#view"), vctx = view.getContext("2d"); [vid, scanVid].forEach(v => v.addEventListener("error", () => { if (v.hasAttribute("crossorigin") && v.src) { const u = v.src; v.removeAttribute("crossorigin"); v.src = u; S.tainted = true; } })); let cam = {x:.5, y:.5, z:1}; /* ===================== capabilities ===================== */ const caps = {}; function cap(name){ // sghadimi.com: no claude.ai capabilities. Saving is a plain browser download; Claude features are hidden. if (name !== "downloads") return Promise.resolve(null); return Promise.resolve({ save: async ({filename, data}) => { const blob = data instanceof Blob ? data : new Blob([data], {type: /\.csv$/.test(filename) ? "text/csv" : /\.html$/.test(filename) ? "text/html" : "application/octet-stream"}); const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = filename; document.body.appendChild(a); a.click(); setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 4000); return {status: "saved"}; } }); } /* ===================== detector worker ===================== */ const WORKER_SRC = ` let session=null; function nms(arr, iouT){ arr.sort((a,b)=>b[4]-a[4]); const keep=[]; for(const b of arr){ let ok=true; for(const k of keep){ const x1=Math.max(b[0]-b[2]/2,k[0]-k[2]/2), y1=Math.max(b[1]-b[3]/2,k[1]-k[3]/2), x2=Math.min(b[0]+b[2]/2,k[0]+k[2]/2), y2=Math.min(b[1]+b[3]/2,k[1]+k[3]/2); const inter=Math.max(0,x2-x1)*Math.max(0,y2-y1); const iou=inter/(b[2]*b[3]+k[2]*k[3]-inter); if(iou>iouT){ok=false;break;} } if(ok) keep.push(b); if(keep.length>40) break; } return keep; } self.onmessage = async (e) => { const m = e.data; if (m.type === "init") { try { importScripts(m.base + "vendor/ort.wasm.min.js"); ort.env.wasm.numThreads = 1; ort.env.wasm.proxy = false; ort.env.wasm.wasmPaths = { mjs: m.base + "vendor/ort-wasm-simd-threaded.mjs", wasm: m.base + "vendor/ort-wasm-simd-threaded.wasm" }; const wb = await fetch(m.base + "vendor/ort-wasm-simd-threaded.wasm"); if(!wb.ok) throw new Error("runtime " + wb.status); ort.env.wasm.wasmBinary = await wb.arrayBuffer(); const mb = await fetch(m.base + "model/yolov8n.json"); if(!mb.ok) throw new Error("model " + mb.status); const mj = await mb.json(); const bin = atob(mj.data); const bytes = new Uint8Array(bin.length); for (let i=0;i 0.28) P.push([o[j],o[N+j],o[2*N+j],o[3*N+j],sp]); if (sb > 0.12) B.push([o[j],o[N+j],o[2*N+j],o[3*N+j],sb]); } self.postMessage({ type: "det", id: m.id, persons: nms(P,0.5), balls: nms(B,0.4).slice(0,3) }); } catch (err) { self.postMessage({ type: "det", id: m.id, persons: [], balls: [], error: String(err) }); } } };`; const pending = new Map(); let detId = 0; function initEngine(){ try { const base = new URL(".", location.href).href; const w = new Worker(URL.createObjectURL(new Blob([WORKER_SRC], {type:"text/javascript"}))); w.onmessage = (e) => { const m = e.data; if (m.type === "ready") { S.engine = "ready"; S.worker = w; setEngine(); } else if (m.type === "error") { S.engine = "off"; S.engineErr = m.message; setEngine(); } else if (m.type === "det") { const r = pending.get(m.id); if (r) { pending.delete(m.id); r(m); } } }; w.onerror = () => { S.engine = "off"; setEngine(); }; w.postMessage({type:"init", base}); } catch(e) { S.engine = "off"; setEngine(); } } function setEngine(){ const d = $("#engineDot"), t = $("#engineTxt"); if (S.engine === "ready") { d.className = "dot"; t.textContent = "On-device AI ready · nothing uploaded"; } else if (S.engine === "off") { d.className = "dot warn"; t.textContent = "Vision model unavailable · using sound + motion"; } else { d.className = "dot warn"; t.textContent = "Loading on-device AI…"; } } function detect(imageData){ if (S.engine !== "ready") return Promise.resolve({persons:[], balls:[]}); return new Promise(res => { const id = ++detId; pending.set(id, res); S.worker.postMessage({type:"detect", id, data:imageData.data}, [imageData.data.buffer]); }); } /* ===================== media helpers ===================== */ function seek(v, t){ return new Promise(res => { let fin = false; const finish = () => { if (!fin) { fin = true; res(); } }; const done = () => { v.removeEventListener("seeked", done); if (v.requestVideoFrameCallback) { v.requestVideoFrameCallback(() => finish()); setTimeout(finish, 250); } else setTimeout(finish, 30); }; v.addEventListener("seeked", done); v.currentTime = clamp(t, 0, Math.max(0, (v.duration||0) - 0.05)); setTimeout(finish, 3000); }); } function loaded(v){ return new Promise(res => { if (v.readyState >= 2 && v.duration) return res(); const f = () => { v.removeEventListener("loadeddata", f); res(); }; v.addEventListener("loadeddata", f); }); } const C640 = document.createElement("canvas"); C640.width = C640.height = 640; const c640 = C640.getContext("2d", {willReadFrequently:true}); const CSM = document.createElement("canvas"); CSM.width = 96; CSM.height = 54; const csm = CSM.getContext("2d", {willReadFrequently:true}); function letterbox(v){ const vw = v.videoWidth, vh = v.videoHeight, r = 640 / Math.max(vw, vh); c640.fillStyle = "#727272"; c640.fillRect(0,0,640,640); c640.drawImage(v, 0, 0, vw*r, vh*r); return {r, w:vw*r, h:vh*r}; } // appearance signature of the torso region: 12 hue bins weighted by saturation + 3 neutral bins function signature(box, lb, img){ const sig = new Float32Array(15); const x0 = Math.round((box[0]-box[2]*0.28)*lb.w), x1 = Math.round((box[0]+box[2]*0.28)*lb.w); const y0 = Math.round((box[1]-box[3]*0.30)*lb.h), y1 = Math.round((box[1]+box[3]*0.02)*lb.h); let n = 0; for (let y = Math.max(0,y0); y < Math.min(640,y1); y += 2) for (let x = Math.max(0,x0); x < Math.min(640,x1); x += 2) { const p = (y*640 + x)*4, r = img[p]/255, g = img[p+1]/255, b = img[p+2]/255; const mx = Math.max(r,g,b), mn = Math.min(r,g,b), dl = mx - mn, sat = mx ? dl/mx : 0; if (sat > 0.28 && mx > 0.18) { let h = mx === r ? ((g-b)/dl)%6 : mx === g ? (b-r)/dl + 2 : (r-g)/dl + 4; h = (h*60 + 360) % 360; sig[Math.floor(h/30)] += sat; } else sig[mx > 0.72 ? 12 : mx > 0.3 ? 13 : 14] += 0.8; n++; } let s = 0; for (let i=0;i<15;i++) s += sig[i]; if (s > 0) for (let i=0;i<15;i++) sig[i] = +(sig[i]/s).toFixed(3); return Array.from(sig); } const bhat = (a,b) => { let s = 0; for (let i=0;i document.querySelector(`#steps li[data-s="${s}"]`); const setStep = (s, st) => { const el = stepEl(s); el.classList.remove("on","done"); if (st) el.classList.add(st); }; ["vision","track","shots","score"].forEach(s => setStep(s, null)); stepEl("track").style.display = S.follow ? "" : "none"; stepEl("shots").style.display = S.hoops.length ? "" : "none"; const bar = $("#scanBar"); bar.style.width = "2%"; $("#analyzeBtn").disabled = true; setHud(); try { scanVid.src = S.source.url; await loaded(scanVid); const dur = scanVid.duration, vw = scanVid.videoWidth, vh = scanVid.videoHeight; // sound is not used: plays are found from what the camera sees const audio = null; bar.style.width = "4%"; // 2. vision setStep("vision","on"); const step = Math.max(S.follow ? 0.25 : 0.5, dur / 900); const frames = []; let prevSmall = null, prevHist = null, people = 0; const tStart = performance.now(); for (let t = 0.05; t < dur - 0.05; t += step) { await seek(scanVid, t); // motion + cut on small frame csm.drawImage(scanVid, 0, 0, 96, 54); const sm = csm.getImageData(0,0,96,54).data, gray = new Float32Array(96*54), hist = new Float32Array(16); for (let i=0,p=0;i>4)]++; } let motion = 0, mx = 0, my = 0, mw = 0, cut = 0; if (prevSmall) { for (let i=0;i 22){ mx += (i%96)*d; my += Math.floor(i/96)*d; mw += d; } } motion /= gray.length; let hd = 0; for (let i=0;i<16;i++) hd += Math.abs(hist[i]-prevHist[i]); cut = hd/gray.length > 0.6 ? 1 : 0; } prevSmall = gray; prevHist = hist; const fr = {t:+t.toFixed(2), m:+motion.toFixed(2), cut, ax: mw ? +(mx/mw/96).toFixed(3) : null, ay: mw ? +(my/mw/54).toFixed(3) : null, p:[], b:[]}; if (S.engine === "ready") { const lb = letterbox(scanVid); const img = c640.getImageData(0,0,640,640); const pix = new Uint8ClampedArray(img.data); const det = await detect(img); for (const d of det.persons) { const box = [d[0]/lb.w, d[1]/lb.h, d[2]/lb.w, d[3]/lb.h]; if (box[3] < 0.05 || box[1] > 1.02) continue; fr.p.push([+box[0].toFixed(4), +box[1].toFixed(4), +box[2].toFixed(4), +box[3].toFixed(4), +d[4].toFixed(2), signature(box, lb, pix)]); } for (const d of det.balls) fr.b.push([+(d[0]/lb.w).toFixed(4), +(d[1]/lb.h).toFixed(4), +d[4].toFixed(2)]); people = Math.max(people, fr.p.length); S.scanPreview = {t, persons:fr.p, balls:fr.b}; vctx.save(); drawFrameTo(vctx, view.width, view.height, scanVid, {scan:true}); vctx.restore(); } frames.push(fr); const k = frames.length, total = Math.ceil(dur/step); bar.style.width = (10 + 78*k/total) + "%"; $("#scanFrames").textContent = k + " / " + total + " frames"; $("#scanPeople").textContent = people + " players in view"; const el = (performance.now() - tStart)/1000, eta = el/k*(total-k); $("#scanEta").textContent = k > 3 ? "about " + Math.ceil(eta) + "s left" : ""; if (k % 4 === 0) await new Promise(r => setTimeout(r, 0)); } setStep("vision","done"); S.an = {v:1, duration:dur, vw, vh, step, audio, frames, vision: S.engine === "ready"}; // 3. track if (S.follow) { setStep("track","on"); S.track = buildTrack(); setStep("track","done"); } else S.track = null; if (S.hoops.length) { setStep("shots","on"); await analyzeShots(p => bar.style.width = (88 + p*6) + "%"); setStep("shots","done"); } bar.style.width = "94%"; setStep("score","on"); S.lastAnalyzeSec = (performance.now() - t0)/1000; attributeShots(); rescore(true); renderReport(); await makeThumbs(); setStep("score","done"); bar.style.width = "100%"; toast(S.shots ? `Report ready: ${S.shots.filter(x => x.mine === true).length} shots for your player (${Math.round(S.lastAnalyzeSec)}s)` : `Report ready (${Math.round(S.lastAnalyzeSec)}s). Mark the hoop to count shots.`); renderHow(); } catch(e) { console.error(e); toast("Analysis stopped: " + (e.message || e) + ". Try a shorter MP4 or MOV file."); } finally { S.busy = false; S.scanPreview = null; $("#analyzeBtn").disabled = false; setTimeout(() => { scan.hidden = true; }, 500); $("#analyzeTxt").textContent = "Re-run analysis"; setHud(); drawStage(); } } /* ===================== made-basket detector ===================== */ // Training-free: the parent marks the rim once. Each frame we (1) re-find the hoop by template // matching (multi-scale search if the camera jumps), (2) find the moving ball near it by background // difference, and (3) call a make when the ball goes from above the rim to inside the net. function grayOf(img){ const d = img.data, n = img.width*img.height, g = new Float32Array(n); for (let i=0,p=0;i 1 ? 2 : 1); if (v > best){ best = v; bx = x; by = y; } } return {v:best, x:bx, y:by}; } function components(mask, w, h){ const lab = new Int32Array(w*h), out = []; let id = 0; const st = []; for (let i=0;imaxx) maxx=x; if (ymaxy) maxy=y; if (x>0 && mask[p-1] && !lab[p-1]){ lab[p-1]=id; st.push(p-1); } if (x0 && mask[p-w] && !lab[p-w]){ lab[p-w]=id; st.push(p-w); } if (y=1; k--) { if (ring[n-1].t - ring[k].t > 2.2) break; const A = ring[k].g, P = ring[k-1].g, N = ring[k+1].g; const qx = px - vx, qy = py - vy, R = Math.round(Math.max(10, 2.2*Math.hypot(vx, vy)) + ballD*1.5); const x0 = Math.max(1, Math.round(qx - R)), x1 = Math.min(W-2, Math.round(qx + R)), y0 = Math.max(1, Math.round(qy - R)), y1 = Math.min(H-2, Math.round(qy + R)); const ww = x1 - x0 + 1, hh = y1 - y0 + 1; if (ww < 4 || hh < 4) break; const m = new Uint8Array(ww*hh); for (let yy=0; yy 14 && Math.abs(a - N[i]) > 14 ? 1 : 0; } let best = null, bd = 1e9; for (const c of components(m, ww, hh)) { const cw = c.maxx - c.minx + 1, ch = c.maxy - c.miny + 1, d = Math.max(cw, ch); if (d < 0.45*ballD || d > 2.4*ballD || cw/ch < 0.4 || cw/ch > 2.5 || c.area/(cw*ch) < 0.35) continue; const cx = x0 + c.minx + cw/2, cy = y0 + c.miny + ch/2, dd = Math.hypot(cx - qx, cy - qy); if (dd < bd) { bd = dd; best = {x:cx, y:cy}; } } if (best) { const nvx = px - best.x, nvy = py - best.y; vx = pts.length > 1 ? vx*0.5 + nvx*0.5 : nvx; vy = pts.length > 1 ? vy*0.5 + nvy*0.5 : nvy; px = best.x; py = best.y; miss = 0; pts.push({t:ring[k].t, x:px, y:py}); } else { miss++; px = qx; py = qy; if (miss >= 3) break; } } return pts; } let SHOT_MODE = "diff3"; let MADE_RULE = (made, above, net, deep) => deep >= 2 || (above && net > 0.35); async function analyzeShots(onProgress){ if (!S.hoops || !S.hoops.length) { S.shots = null; return null; } const v = scanVid; if (v.src !== S.source.url) v.src = S.source.url; await loaded(v); const vw = v.videoWidth, vh = v.videoHeight, PW = Math.min(960, vw), PH = Math.round(PW*vh/vw); const cv = document.createElement("canvas"); cv.width = PW; cv.height = PH; const cx = cv.getContext("2d", {willReadFrequently:true}); const frame = async (t) => { await seek(v, t); cx.drawImage(v, 0, 0, PW, PH); return grayOf(cx.getImageData(0, 0, PW, PH)); }; // templates from each hoop's marking frame const H = []; for (const hp of S.hoops) { const g = await frame(hp.t); const w0 = hp.w*PW, rcx = hp.cx*PW, rcy = hp.cy*PH; const tx0 = Math.max(0, Math.round(rcx - 1.1*w0)), ty0 = Math.max(0, Math.round(rcy - 1.6*w0)); const tx1 = Math.min(PW, Math.round(rcx + 1.1*w0)), ty1 = Math.min(PH, Math.round(rcy + 1.0*w0)); const tw = tx1 - tx0, th = ty1 - ty0, tg = new Float32Array(tw*th); for (let j=0;j { const w2 = Math.max(8, Math.round(tw*s)), h2 = Math.max(8, Math.round(th*s)); return {s, T:makeTmpl(resizeGray(tg, tw, th, w2, h2), w2, h2)}; }); H.push({w0, rel:{x:rcx - tx0, y:rcy - ty0}, T:makeTmpl(tg, tw, th), tg, tw, th, scales, mx:tx0, my:ty0, s:1, lost:0, bg:null, bgKey:"", traj:[], net:[], lastGlobal:-9, poses:[], releases:[], lastNear:null}); } const dur = v.duration; const gFull = new Float32Array(PW*PH); const fillGray = (x0, y0, x1, y1) => { x0 = Math.max(0, x0|0); y0 = Math.max(0, y0|0); x1 = Math.min(PW, Math.ceil(x1)); y1 = Math.min(PH, Math.ceil(y1)); if (x1 <= x0 || y1 <= y0) return; const d = cx.getImageData(x0, y0, x1 - x0, y1 - y0).data, rw = x1 - x0; for (let y=y0, p=0; y { cx.drawImage(v, 0, 0, PW, PH); // only read the pixels around each hoop; the whole frame only when a hoop is lost let x0 = PW, y0 = PH, x1 = 0, y1 = 0, full = false; for (const h of H) { if (h.lost >= 2) full = true; const w = h.w0*h.s, pad = 0.8*h.w0*h.s + 2, tw = h.tw*h.s, th = h.th*h.s, rcx = h.mx + h.rel.x*h.s, ry = h.my + h.rel.y*h.s; x0 = Math.min(x0, h.mx - pad, rcx - 3.6*w); y0 = Math.min(y0, h.my - pad, ry - 4.6*w); x1 = Math.max(x1, h.mx + tw + pad, rcx + 3.6*w); y1 = Math.max(y1, h.my + th + pad, ry + 2.1*w); } if (full) fillGray(0, 0, PW, PH); else fillGray(x0, y0, x1, y1); return gFull; }; // a half-size grayscale copy of every recent frame, for tracing the ball back to the shooter's hands const BW = Math.round(PW/2), BH = Math.round(PH/2), bcv = document.createElement("canvas"); bcv.width = BW; bcv.height = BH; const bcx = bcv.getContext("2d", {willReadFrequently:true}); const ring = []; const RING = 64; const pushRing = (t) => { bcx.drawImage(v, 0, 0, BW, BH); const d = bcx.getImageData(0, 0, BW, BH).data, g8 = new Uint8Array(BW*BH); for (let i=0,p=0;i> 8; ring.push({t, g:g8}); if (ring.length > RING) ring.shift(); }; const processFrame = (t) => { const g = grab(); pushRing(t); for (const h of H) { // 1. hoop const sc = h.s, cur = sc === 1 ? h.T : h.scales.find(q => q.s === sc).T, pad = Math.round(0.8*h.w0*sc); let r = searchTmpl(g, PW, PH, cur, h.mx - pad, h.my - pad, h.mx + pad, h.my + pad, 2); if (r.v > 0.3) r = searchTmpl(g, PW, PH, cur, r.x - 2, r.y - 2, r.x + 2, r.y + 2, 1); if (r.v > 0.5) { h.mx = r.x; h.my = r.y; h.lost = 0; } else if (++h.lost >= 3 && t - h.lastGlobal > 0.5) { h.lastGlobal = t; // coarse global search on a half-size frame at several scales const QW = PW >> 1, QH = PH >> 1, q = resizeGray(g, PW, PH, QW, QH); let best = {v:-2}; for (const S_ of h.scales) { const tq = makeTmpl(resizeGray(S_.T.g, S_.T.tw, S_.T.th, Math.max(6, S_.T.tw>>1), Math.max(6, S_.T.th>>1)), Math.max(6, S_.T.tw>>1), Math.max(6, S_.T.th>>1)); const rr = searchTmpl(q, QW, QH, tq, 0, 0, QW, QH, 2); if (rr.v > best.v) best = {...rr, s:S_.s}; } if (best.v > 0.5) { const T2 = h.scales.find(q2 => q2.s === best.s).T; const rf = searchTmpl(g, PW, PH, T2, best.x*2 - 4, best.y*2 - 4, best.x*2 + 4, best.y*2 + 4, 1); if (rf.v > 0.55) { h.mx = rf.x; h.my = rf.y; h.s = best.s; h.lost = 0; h.bg = null; } } } const w = h.w0*h.s, rcx = h.mx + h.rel.x*h.s, ry = h.my + h.rel.y*h.s; // 2. ball near the rim const R0x = Math.max(0, Math.round(rcx - 3.6*w)), R0y = Math.max(0, Math.round(ry - 4.5*w)), R1x = Math.min(PW, Math.round(rcx + 3.5*w)), R1y = Math.min(PH, Math.round(ry + 2*w)); const rw = R1x - R0x, rh = R1y - R0y; if (rw < 8 || rh < 8) continue; const key = rw + "x" + rh; const roi = new Float32Array(rw*rh); for (let j=0;j 0) { h.p2 = h.p1; h.p1 = roi; continue; } // hoop not found this frame: don't guess if (SHOT_MODE === "bg") { for (let i=0;i 22 ? 1 : 0; cnt += m[i]; h.bg[i] = h.bg[i]*0.9 + roi[i]*0.1; } } else { // three-frame difference in hoop-aligned coordinates: survives a panning camera if (!h.p1 || !h.p2) { h.p2 = h.p1; h.p1 = roi; continue; } for (let i=0;i 18 && Math.abs(roi[i] - h.p2[i]) > 18 ? 1 : 0; cnt += m[i]; } h.p2 = h.p1; h.p1 = roi; } if (cnt > 0.2*rw*rh) { h.bg = roi.slice(); continue; } // whole view moved: skip const fg = openMask(m, rw, rh); const prev = h.traj.length && t - h.traj[h.traj.length-1].t < 0.3 ? h.traj[h.traj.length-1] : null; let best = null; for (const c of components(fg, rw, rh)) { const ww = c.maxx - c.minx + 1, hh = c.maxy - c.miny + 1, d = Math.max(ww, hh); if (d < 0.25*w || d > 1.1*w) continue; if (ww/hh < 0.45 || ww/hh > 2.2) continue; const fill = c.area/(ww*hh); if (fill < 0.45) continue; const bx = R0x + c.minx + ww/2, by = R0y + c.miny + hh/2; let sc2 = fill; if (prev) sc2 -= Math.hypot(bx - prev.x, by - prev.y)/(3*w); if (!best || sc2 > best.s) best = {s:sc2, x:bx, y:by, c}; } // the ball itself must not count as net movement if (best) { const c = best.c; for (let y=Math.max(0,c.miny-2); y<=Math.min(rh-1,c.maxy+2); y++) for (let x=Math.max(0,c.minx-2); x<=Math.min(rw-1,c.maxx+2); x++) fg[y*rw+x] = 0; } // net motion under the rim const nx0 = Math.round(rcx - 0.35*w - R0x), nx1 = Math.round(rcx + 0.35*w - R0x), ny0 = Math.round(ry + 0.2*w - R0y), ny1 = Math.round(ry + 0.9*w - R0y); let nm = 0, nc = 0; for (let y=Math.max(0,ny0); y ry - 4.2*w; if (aboveRim) { if (h.lastNear == null || t - h.lastNear > 0.8) h.releases.push({t, path: backtrackBall(ring, BW, BH, best.x/2, best.y/2, 0.5*w/2)}); h.lastNear = t; } } if (!h.poses.length || t - h.poses[h.poses.length-1][0] >= 0.1) h.poses.push([+t.toFixed(2), rcx/PW, ry/PH, w/PW]); } }; let lastT = -1; if (v.requestVideoFrameCallback) { // decode by playing (every frame, much faster than seeking); muted, double speed await seek(v, 0); v.muted = true; v.playbackRate = 1; await new Promise((res) => { let done = false; const fin = () => { if (!done) { done = true; v.pause(); res(); } }; const step = (now, meta) => { if (done) return; const t = meta.mediaTime; if (t > lastT + 0.02) { processFrame(t); lastT = t; onProgress && onProgress(t/dur); } if (v.ended || t >= dur - 0.05) return fin(); v.requestVideoFrameCallback(step); }; v.requestVideoFrameCallback(step); v.addEventListener("ended", fin, {once:true}); const guard = setInterval(() => { if (done) return clearInterval(guard); if (v.paused && !v.ended) v.play().catch(()=>{}); }, 1000); v.play().catch(() => fin()); setTimeout(fin, (dur + 30)*1000*2); }); v.playbackRate = 1; } else { for (let t = 0; t < dur; t += 1/15) { await seek(v, t); processFrame(t); onProgress && onProgress(t/dur); if ((t*15|0) % 8 === 0) await new Promise(r => setTimeout(r, 0)); } } // 3. shot events const shots = []; H.forEach((h, hi) => { const ev = []; let cur = null; for (const p of h.traj) { const near = Math.abs(p.x - p.cx) < 1.6*p.w && p.y > p.ry - 3*p.w && p.y < p.ry + 1.2*p.w; if (!near) continue; if (!cur || p.t - cur.last > 0.8) { if (cur) ev.push(cur); cur = {start:p.t, last:p.t, pts:[]}; } cur.last = p.t; cur.pts.push(p); } if (cur) ev.push(cur); for (const e of ev) { let above = false, made = false, top = 9, deep = 0; for (const p of e.pts) { top = Math.min(top, (p.y - p.ry)/p.w); if (p.y < p.ry - 0.05*p.w && Math.abs(p.x - p.cx) < 1.3*p.w) above = true; if (above && p.y > p.ry + 0.2*p.w && Math.abs(p.x - p.cx) < 0.7*p.w) made = true; if (above && p.y > p.ry + 0.2*p.w && p.y < p.ry + 1.2*p.w && Math.abs(p.x - p.cx) < 0.5*p.w) deep++; } if (e.pts.length < 3 || top > -0.3) continue; let net = 0; for (const q of h.net) if (q.t >= e.start - 0.1 && q.t <= e.last + 0.6) net = Math.max(net, q.v); const p0 = e.pts[0]; let rimT = e.start; for (const p of e.pts) if (p.y < p.ry + 0.1*p.w && Math.abs(p.x - p.cx) < 1.3*p.w) rimT = p.t; const rel = h.releases.find(r => r.t >= e.start - 0.1 && r.t <= e.last + 0.05); const path = rel ? rel.path : []; // newest first // release = going back in time past the top of the arc, the point where the ball stops dropping (in the image) let rIdx = -1; if (path.length >= 4) { let apex = 0; for (let i=1;i= path[rIdx].y - 0.5) { rIdx = i; flat = 0; } else if (++flat >= 2) break; if (path[0].t - path[i].t > 1.8) break; } } const first = rIdx >= 0 ? path[rIdx] : null; const release = first && rIdx >= 2 ? {t:+first.t.toFixed(2), x:first.x*2/PW, y:first.y*2/PH, n:rIdx+1} : null; // the flight, release to rim, for arc and drawing const flight = (rIdx >= 0 ? path.slice(0, rIdx+1).reverse().map(p => [+p.t.toFixed(2), +(p.x*2/PW).toFixed(4), +(p.y*2/PH).toFixed(4)]) : []) .concat(e.pts.filter(p => p.t <= rimT + 0.05).map(p => [+p.t.toFixed(2), +(p.x/PW).toFixed(4), +(p.y/PH).toFixed(4)])); shots.push({t:+e.start.toFixed(2), end:+e.last.toFixed(2), made: MADE_RULE(made, above, net, deep), rimT:+rimT.toFixed(2), release, flight, dbg:{made, above, net:+net.toFixed(3), deep}, hoop:hi, net:+net.toFixed(2), rim:[p0.cx/PW, p0.ry/PH, p0.w/PW]}); } }); shots.sort((a,b) => a.t - b.t); S.hoopPoses = H.map(h => h.poses); S.shots = shots; return shots; } /* ===================== coach engine: court, movement, shooting ===================== */ const COURTS = { hs:{label:"High school / youth (US)", lane:12, ft:19, r3:19.75, corner3:null, hoopY:5.25}, college:{label:"College (US)", lane:12, ft:19, r3:22.15, corner3:21.65, hoopY:5.25}, nba:{label:"NBA", lane:16, ft:19, r3:23.75, corner3:22, hoopY:5.25}, fiba:{label:"FIBA / international", lane:16.08, ft:19.03, r3:22.15, corner3:21.65, hoopY:5.17} }; // 4-point homography (image -> court), solved by Gaussian elimination function homography(src, dst){ const A = [], b = []; for (let i=0;i<4;i++){ const [x,y] = src[i], [u,v] = dst[i]; A.push([x,y,1,0,0,0,-u*x,-u*y]); b.push(u); A.push([0,0,0,x,y,1,-v*x,-v*y]); b.push(v); } const n = 8, M = A.map((r,i) => r.concat([b[i]])); for (let c=0;c Math.abs(M[p][c])) p = r; [M[c], M[p]] = [M[p], M[c]]; if (Math.abs(M[c][c]) < 1e-12) return null; for (let r=0;r r[n]/r[i]); return [h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7],1]; } function applyH(H, x, y){ const w = H[6]*x + H[7]*y + H[8]; return [(H[0]*x + H[1]*y + H[2])/w, (H[3]*x + H[4]*y + H[5])/w]; } function invertH(H){ const [a,b,c,d,e,f,g,h,i] = H, A = e*i - f*h, B = -(d*i - f*g), C = d*h - e*g, det = a*A + b*B + c*C; if (Math.abs(det) < 1e-12) return null; return [A/det, -(b*i - c*h)/det, (b*f - c*e)/det, B/det, (a*i - c*g)/det, -(a*f - c*d)/det, C/det, -(a*h - b*g)/det, (a*e - b*d)/det]; } function courtSpec(){ return COURTS[(S.calib && S.calib.std) || "hs"]; } function buildCalib(){ const c = S.calib; if (!c || c.pts.length !== 4) { S.H = null; S.Hinv = null; return; } const K = COURTS[c.std], L = K.lane/2; // aspect-correct the taps (video pixels) so feet come out square const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9; const src = c.pts.map(p => [p[0]*vw, p[1]*vh]); S.H = homography(src, [[-L,0],[L,0],[L,K.ft],[-L,K.ft]]); S.Hinv = S.H && invertH(S.H); } // camera moves: undo pan/zoom with the hoop's tracked position and size function poseAt(t){ const P = S.hoopPoses && S.hoopPoses[S.calib && S.calib.hoop || 0]; if (!P || !P.length) return null; let lo = 0, hi = P.length-1; while (hi - lo > 1){ const m = (lo+hi)>>1; if (P[m][0] <= t) lo = m; else hi = m; } return Math.abs(P[lo][0]-t) < Math.abs(P[hi][0]-t) ? P[lo] : P[hi]; } function toCourt(nx, ny, t){ if (!S.H) return null; const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9; let x = nx*vw, y = ny*vh; const a = poseAt(t), b = S.calib && poseAt(S.calib.t); if (a && b && a[3] > 0) { const k = b[3]/a[3]; x = b[1]*vw + (x - a[1]*vw)*k; y = b[2]*vh + (y - a[2]*vh)*k; } const [X, Y] = applyH(S.H, x, y); return [X, Y]; } function fromCourt(X, Y, t){ if (!S.Hinv) return null; const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9; let [x, y] = applyH(S.Hinv, X, Y); const a = poseAt(t), b = S.calib && poseAt(S.calib.t); if (a && b && b[3] > 0) { const k = a[3]/b[3]; x = a[1]*vw + (x - b[1]*vw)*k; y = a[2]*vh + (y - b[2]*vh)*k; } return [x/vw, y/vh]; } function zoneOf(X, Y){ const K = courtSpec(); if (Y > 47) return "back"; const d = Math.hypot(X, Y - K.hoopY); const corner = K.corner3 ? (Math.abs(X) >= K.corner3 && Y <= 14) : false; if (corner) return "corner3"; if (d >= K.r3) return "three"; if (Math.abs(X) <= K.lane/2 && Y <= K.ft) return "paint"; return "mid"; } const ZONES = {paint:"Paint", mid:"Mid-range", corner3:"Corner 3", three:"Above-the-break 3", back:"Backcourt"}; // who took each shot: the person nearest the point where the ball left the hands function attributeShots(){ // sharpen each release to where the ball starts its free climb (the shot engine's guess can include the gather or the pass) for (const sh of S.shots || []) { if (sh._rel0 === undefined) sh._rel0 = sh.release || null; const r = refineRelease(sh); sh._fit = !!(r && r.fit); sh.release = sh._fit ? Object.assign({}, sh._rel0 || {}, {t:r.t, x:r.x, y:r.y}) : sh._rel0; } if (!S.shots) return; const F = S.an && S.an.frames; for (const sh of S.shots) { const tRel = sh.release ? sh.release.t : (sh.rimT || sh.t) - 1.0; sh.relT = +tRel.toFixed(2); // the people in view at release let people = []; if (F && F.length) { let best = null; for (const f of F) if (!best || Math.abs(f.t - tRel) < Math.abs(best.t - tRel)) best = f; if (best && Math.abs(best.t - tRel) < 0.6) people = best.p; } let shooter = null, how = "guess"; if (sh.release && people.length) { let bd = 1e9; for (const p of people) { const top = p[1] - p[3]/2; const dx = Math.max(0, Math.abs(sh.release.x - p[0]) - p[2]/2), dy = Math.max(0, top - sh.release.y, sh.release.y - (p[1] + p[3]/2)); const d = Math.hypot(dx, dy*0.6)/p[3]; if (d < bd) { bd = d; shooter = p; } } how = bd < 0.35 ? "traced" : "guess"; if (bd > 0.9) shooter = null; } if (!shooter && people.length) { // fallback: the person farthest from the rim (rebounders wait under it) let bd = -1; for (const p of people) { const d = Math.hypot(p[0] - sh.rim[0], (p[1] - sh.rim[1])*0.56); if (d > bd) { bd = d; shooter = p; } } how = "guess"; } // better: follow the ball's shooter back to the set position just before the jump, where the detector sees them standing sh._local = sh.release && sh._fit ? localTrack(sh, sh.release) : null; const setBox = sh._local && localAt(sh._local, tRel - 0.45); if (setBox) { shooter = [setBox.cx, setBox.cy, setBox.w, setBox.h]; how = "traced"; } sh.shooterBox = shooter ? shooter.slice(0,4) : null; sh.how = how; // is it our player? let mine = null, sure = false; const relDist = (b) => { const dx = Math.max(0, Math.abs(sh.release.x - b[0]) - b[2]/2), dy = Math.max(0, (b[1] - b[3]/2) - sh.release.y, sh.release.y - (b[1] + b[3]/2)); return Math.hypot(dx, dy*0.6)/b[3]; }; if (S.track && shooter) { const tk = trackAt(setBox ? tRel - 0.45 : tRel); if (tk && tk.ok) { const same = Math.hypot(tk.cx - shooter[0], tk.cy - shooter[1]) < 0.5*shooter[3]; if (same) { mine = true; sure = how === "traced"; } else if (how === "traced" && sh.release && relDist([tk.cx, tk.cy, tk.w, tk.h]) > 0.8) { mine = false; sure = true; } else mine = null; // close call: ask the coach } } if (!S.follow) { mine = true; sure = true; } // no one picked: every shot at this hoop counts (one-player workout) if (sh.coach != null) { mine = sh.coach; sure = true; } // the coach's answer always wins sh.mine = mine; sh.sure = sure; // where it was taken from: the traced shooter, or our tracked player when the coach says it was theirs let src = shooter; if (((sh.coach === true && !setBox) || (how !== "traced" && mine === true)) && S.track) { const tk = trackAt(tRel); if (tk && tk.ok) src = [tk.cx, tk.cy, tk.w, tk.h]; } const pre = setBox && localMedian(sh._local, tRel - 0.6, tRel - 0.28); const feet = src ? [src[0], src[1] + src[3]/2] : null; const cxy = pre && pre.court && src === shooter ? pre.court : feet ? toCourt(feet[0], feet[1], tRel) : null; sh.court = cxy && cxy[1] > -4 && cxy[1] < 60 && Math.abs(cxy[0]) < 32 ? cxy.map(v => +v.toFixed(1)) : null; if (sh.court) { const K = courtSpec(); sh.dist = +Math.hypot(sh.court[0], sh.court[1] - K.hoopY).toFixed(1); sh.zone = zoneOf(sh.court[0], sh.court[1]); sh.pts = (sh.zone === "three" || sh.zone === "corner3") ? 3 : 2; } else { sh.dist = null; sh.zone = null; sh.pts = null; } } } function movementStats(){ const tr = S.track; if (!tr || !S.H) return null; const pts = []; for (const q of tr) { if (!q.ok) continue; const c = toCourt(q.cx, q.cy + q.h/2, q.t); if (!c || c[1] < -4 || c[1] > 60 || Math.abs(c[0]) > 32) continue; pts.push({t:q.t, x:c[0], y:c[1]}); } if (pts.length < 4) return null; // smooth: median of 3, then a short moving average const med = pts.map((p, i) => { if (i === 0 || i === pts.length-1) return {...p}; const xs = [pts[i-1].x, p.x, pts[i+1].x].sort((a,b)=>a-b), ys = [pts[i-1].y, p.y, pts[i+1].y].sort((a,b)=>a-b); return {t:p.t, x:xs[1], y:ys[1]}; }); const sm = med.map((p, i) => { let x = 0, y = 0, n = 0; for (let j=Math.max(0,i-1); j<=Math.min(med.length-1,i+1); j++){ if (Math.abs(med[j].t - p.t) < 0.6){ x += med[j].x; y += med[j].y; n++; } } return {t:p.t, x:x/n, y:y/n}; }); let dist = 0, tracked = 0; const sp = []; for (let i=1;i 0.7) continue; const d = Math.hypot(sm[i].x - sm[i-1].x, sm[i].y - sm[i-1].y); const v = d/dt; if (v > 32) continue; dist += d; tracked += dt; sp.push({t:sm[i].t, v}); } // top speed over 1 s windows; sprints = 1 s or more at 13 ft/s (about 9 mph) or faster let top = 0; for (let i=0;i= 3) top = Math.max(top, s/n); } let sprints = 0, run = 0, last = null; for (const q of sp){ if (q.v >= 13 && (!last || q.t - last < 0.6)) { run += last ? q.t - last : 0; } else if (q.v < 13) { if (run >= 1.0) sprints++; run = 0; } last = q.t; } if (run >= 1.0) sprints++; const zoneT = {paint:0, mid:0, corner3:0, three:0, back:0}; for (let i=1;i 0 && dt <= 0.7) zoneT[zoneOf(sm[i].x, sm[i].y)] += dt; } return {dist, tracked, top, sprints, zoneT, path:sm}; } function shootingStats(){ if (!S.shots) return null; const mine = S.shots.filter(s => s.mine === true); const unsure = S.follow ? S.shots.filter(s => s.mine == null || (!s.sure && s.coach == null)).length : 0; const made = mine.filter(s => s.made).length; const z = {}; for (const k of Object.keys(ZONES)) z[k] = {m:0, a:0}; let pts = 0, threesA = 0, threesM = 0; for (const s of mine) { if (s.zone) { z[s.zone].a++; if (s.made) z[s.zone].m++; } if (s.made && s.pts) pts += s.pts; if (s.pts === 3) { threesA++; if (s.made) threesM++; } } return {att:mine.length, made, pts, threesA, threesM, zones:z, unsure, shots:mine}; } /* ===================== form metrics and coaching moments ===================== */ const FORM = { arc:{label:"Entry angle", unit:"°", good:v => v >= 40, target:"40°+ (45° ideal)"}, rel:{label:"Release height", unit:"× height", good:v => v >= 0.8, target:"0.8×+ (above the shoulders)"}, drift:{label:"Landing drift", unit:"ft", good:v => v <= 2, target:"≤ 2 ft"}, trigger:{label:"Catch to release", unit:"s", good:v => v <= 1.25, target:"≤ 1.2 s"} }; const RULES = { arc:{title:"Flat arc", fix:"The ball comes in too flat, so the rim looks smaller. Shoot up through the ball with the elbow under it, and aim to drop it in at about 45 degrees.", drill:"Arc ladder: 5 spots 3 ft from the rim, make 10 that clear an imaginary ball on the front rim", reps:"5 × 10 makes"}, rel:{title:"Low release", fix:"Finish with the ball above the forehead and the wrist over the eyebrow, so defenders can't get to it.", drill:"Wall line: tape a line 2 ft above head height, 25 one-hand shots that cross it", reps:"2 × 25"}, drift:{title:"Drifting on the shot", fix:"Set both feet before the catch, jump straight up and land on the same spot, chest still facing the rim.", drill:"Spot landing: tape an X, catch, shoot and land on it with both feet", reps:"3 × 10 from 15 ft"}, set:{title:"Shooting on the move", fix:"Hop into the catch so both feet are set before the ball arrives.", drill:"1-2 step catch-and-shoot from both wings", reps:"4 × 8"}, trigger:{title:"Slow trigger", fix:"Catch in the shot pocket and go. Aim for about 0.7 s from catch to release.", drill:"Partner passes; shoot before the partner finishes saying 'one'", reps:"3 × 10"}, walk:{title:"Walking between reps", fix:"Move to the next spot at game speed. Walking reps don't build game legs.", drill:"Every rep ends with a sprint to the next spot", reps:"Whole workout"} }; function flightFit(sh){ // one parabola through the ball's free flight: x linear and y quadratic in time, outliers trimmed const seen = new Set(); let F = (sh.flight || []).filter(p => p[0] <= (sh.rimT || 1e9) + 0.05).sort((a, b) => a[0] - b[0]).filter(p => { const k = p[0].toFixed(2); if (seen.has(k)) return false; seen.add(k); return true; }); if (F.length < 8) return null; // stop at the first time the ball comes back down to the rim; drop samples clipped by the frame edge or tangled in the rim and net let ai = 0; for (let i=0;i F[ai][2] + 0.08 && F[i][2] >= sh.rim[1]) break; } let end = F.length; for (let k=ai;k= sh.rim[1]) { end = k + 1; break; } const rw = sh.rim[2]; F = F.slice(0, end).filter(p => p[2] > 0.035 && p[1] > 0.01 && p[1] < 0.99 && Math.hypot((p[1] - sh.rim[0])*16/9, p[2] - sh.rim[1]) > rw*16/9*1.3); if (F.length < 8) return null; ai = 0; for (let i=0;i { const n = b.length, M = A.map((r, i) => r.concat(b[i])); for (let c=0;c Math.abs(M[pv][c])) pv = r; [M[c], M[pv]] = [M[pv], M[c]]; if (!M[c][c]) return null; for (let r=0;r r[n]/r[i]); }; // gravity sets the curve: 16.1 ft/s^2 times the pixels per foot at the rim (rim = 18 in). The free fit may scale it by up to 25% for depth. const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9, g2 = 16.1 * (rw*vw/1.5) / vh; const fit = (pts) => { const A = [[0,0,0],[0,0,0],[0,0,0]], by = [0,0,0], A2 = [[0,0],[0,0]], bx = [0,0], A3 = [[0,0],[0,0]], b3 = [0,0]; for (const p of pts) { const u = p[0] - ta, r = [1, u, u*u]; for (let i=0;i<3;i++){ for (let j=0;j<3;j++) A[i][j] += r[i]*r[j]; by[i] += r[i]*p[2]; } for (let i=0;i<2;i++){ for (let j=0;j<2;j++) A2[i][j] += r[i]*r[j]; bx[i] += r[i]*p[1]; } } const free = solve(A, by), cx = solve(A2, bx); if (!free || !cx) return null; const c2 = clamp(free[2], g2*0.75, g2*1.25); for (const p of pts) { const u = p[0] - ta, r = [1, u]; for (let i=0;i<2;i++){ for (let j=0;j<2;j++) A3[i][j] += r[i]*r[j]; b3[i] += r[i]*(p[2] - c2*u*u); } } const c01 = solve(A3, b3); if (!c01) return null; return {cx, cy:[c01[0], c01[1], c2], g:free[2]/g2}; }; const err = (m, p) => { const u = p[0] - ta; return Math.hypot((p[1] - (m.cx[0] + m.cx[1]*u))*AR, p[2] - (m.cy[0] + m.cy[1]*u + m.cy[2]*u*u)); }; // seed on the clean middle of the flight, then grow backward toward the hand let use = F.filter(p => p[0] >= ta - 0.45 && p[0] <= ta + 0.2); if (use.length < 6) use = F.slice(); let m = fit(use); if (!m) return null; for (let it = 0; it < 2; it++) { const e = use.map(p => err(m, p)).sort((a, b) => a - b), cut = Math.max(0.006, e[e.length >> 1]*3); use = use.filter(p => err(m, p) <= cut); if (use.length < 5) return null; m = fit(use) || m; } const tol = Math.max(0.007, sh.rim[2]*AR*0.3); // a jump shot leaves the hands above the shoulders: below that line the ball is still being dribbled or carried const shoulder = (p) => { const Fr = S.an && S.an.frames; if (!Fr || !Fr.length) return 1; let fr = Fr[0]; for (const q of Fr) if (Math.abs(q.t - p[0]) < Math.abs(fr.t - p[0])) fr = q; let best = null, bd = 1e9; for (const b of fr.p) { const d = Math.abs(b[0] - p[1]); if (d < b[2]*0.9 && d < bd) { bd = d; best = b; } } return best ? best[1] - best[3]/2 + best[3]*0.22 : 1; }; let rel = use[0], miss = 0; for (let i = F.indexOf(use[0]) - 1; i >= 0; i--) { if (F[i][2] > shoulder(F[i])) break; if (err(m, F[i]) <= tol) { rel = F[i]; miss = 0; use = [F[i]].concat(use); m = fit(use) || m; } else if (++miss >= 2) break; } if (rel[2] > shoulder(rel)) return null; const pts = F.filter(p => p[0] >= rel[0] && err(m, p) <= tol*1.5); const res = pts.reduce((s, p) => s + err(m, p), 0) / Math.max(1, pts.length); if (m.cy[2] <= 0) return null; const tApex = ta - m.cy[1]/(2*m.cy[2]), yApex = m.cy[0] + m.cy[1]*(tApex - ta) + m.cy[2]*(tApex - ta)**2; const disc = m.cy[1]**2 - 4*m.cy[2]*(m.cy[0] - sh.rim[1]), tRim = ta + (-m.cy[1] + Math.sqrt(Math.max(0, disc)))/(2*m.cy[2]); return {m, ta, rel, res, tol, n:pts.length, tApex, yApex, tRim, at:(t) => { const u = t - ta; return [m.cx[0] + m.cx[1]*u, m.cy[0] + m.cy[1]*u + m.cy[2]*u*u]; }}; } function refineRelease(sh){ const r0 = sh._rel0 !== undefined ? sh._rel0 : sh.release; const ff = flightFit(sh); sh._ff = ff; // a real shot climbs at least two rim-widths to the top of its arc, and its flight fits one parabola if (!ff || ff.res > ff.tol || ff.rel[2] - ff.yApex < sh.rim[2]*1.78*2) return r0 ? {t:r0.t, x:r0.x, y:r0.y, fit:false} : null; return {t:ff.rel[0], x:ff.rel[1], y:ff.rel[2], fit:true}; } function courtMedian(a, b){ const xs = [], ys = []; for (const q of S.track || []) { if (!q.ok || q.t < a || q.t > b) continue; const c = toCourt(q.cx, q.cy + q.h/2, q.t); if (c) { xs.push(c[0]); ys.push(c[1]); } } if (!xs.length) return null; xs.sort((u,v) => u-v); ys.sort((u,v) => u-v); return [xs[xs.length>>1], ys[ys.length>>1]]; } function localTrack(sh, r){ // follow the shooter for ~2.5 s around the release from the detections alone: nearest box each frame, same look const F = S.an && S.an.frames; if (!F || !F.length || !r) return null; let f0 = 0; for (let i=0;i p[1] + p[3]/2 ? 9 : 0; const d = dx/p[3] + dy; if (d < bd) { bd = d; seed = p; } } if (!seed || bd > 1.2) return null; const out = [{t:F[f0].t, cx:seed[0], cy:seed[1], w:seed[2], h:seed[3]}]; for (const dir of [-1, 1]) { let cur = seed, miss = 0; for (let i = f0 + dir; i >= 0 && i < F.length && Math.abs(F[i].t - r.t) < 3.2; i += dir) { let best = null, bc = 1e9; for (const p of F[i].p) { const d = Math.hypot(p[0] - cur[0], (p[1] + p[3]/2) - (cur[1] + cur[3]/2)), sim = bhat(p[5], cur[5]); if (d < 0.07 + miss*0.03 && sim > 0.6) { const c = d - sim*0.05; if (c < bc) { bc = c; best = p; } } } if (!best) { if (++miss > 2) break; continue; } miss = 0; cur = best; out.push({t:F[i].t, cx:best[0], cy:best[1], w:best[2], h:best[3]}); } } return out.sort((a, b) => a.t - b.t); } function localAt(L, t){ if (!L || !L.length) return null; let a = null, b = null; for (const q of L) { if (q.t <= t) a = q; if (q.t >= t && !b) b = q; } if (!a || !b) return null; if (b.t - a.t > 0.6) return null; const u = b.t > a.t ? (t - a.t)/(b.t - a.t) : 0; return {cx:a.cx + (b.cx-a.cx)*u, cy:a.cy + (b.cy-a.cy)*u, w:a.w + (b.w-a.w)*u, h:a.h + (b.h-a.h)*u}; } function localCourt(L, t){ const k = localAt(L, t); return k ? toCourt(k.cx, k.cy + k.h/2, t) : null; } function localMedian(L, a, b){ const xs = [], ys = [], hs = [], fy = []; for (const q of L || []) { if (q.t < a || q.t > b) continue; const c = toCourt(q.cx, q.cy + q.h/2, q.t); if (c) { xs.push(c[0]); ys.push(c[1]); } hs.push(q.h); fy.push(q.cy + q.h/2); } if (!hs.length) return null; const md = v => { v.sort((u,w) => u-w); return v[v.length>>1]; }; return {court: xs.length ? [md(xs), md(ys)] : null, h:md(hs), feet:md(fy)}; } function standingAt(t){ // set position: feet and standing height in the half second before the jump if (!S.track) return null; const hs = [], fy = []; for (const q of S.track) if (q.ok && q.t >= t - 0.95 && q.t <= t - 0.3) { hs.push(q.h); fy.push(q.cy + q.h/2); } if (!hs.length) return null; hs.sort((a,b) => a-b); fy.sort((a,b) => a-b); return {h: hs[hs.length>>1], feet: fy[fy.length>>1]}; } function courtAt(t){ const tk = trackAt(t); if (!tk || !tk.ok) return null; return toCourt(tk.cx, tk.cy + tk.h/2, t); } function shotForm(sh){ const f = {}; if (sh.mine !== true) return f; const r = sh._fit && sh.release ? {t:sh.release.t, x:sh.release.x, y:sh.release.y, fit:true} : null; if (!r) { f.unmeasured = "release not seen"; f.flags = []; return f; } const t = r.t, layup = sh.dist != null && sh.dist < 8; f.relPt = r; f.layup = layup; const L = sh._local || localTrack(sh, r); f.local = L; // arc: the angle the ball comes down into the rim (45 degrees is ideal), and how high it peaked over the rim const ff = sh._ff || flightFit(sh), vw = vid.videoWidth || 16, vh = vid.videoHeight || 9; if (ff && ff.res <= ff.tol) { f.arcFt = +Math.max(0, (sh.rim[1] - ff.yApex) * vh / (sh.rim[2]*vw/1.5)).toFixed(1); const tf = ff.tRim - ff.tApex, T = ff.tRim - t; const vyPx = 2*ff.m.cy[2]*tf*vh, vxPx = Math.abs(ff.m.cx[1])*vw; // with the court marked: gravity and the shot's distance give the true angle from the flight times alone. // without it: read the angle off the picture, but only for a side-on camera (a ball flying toward or away from the lens looks steeper than it is) // ballistics: tan(entry) = (g T^2 / 2 - rise) / D, with T the time from release to the rim, D the distance and rise = rim minus release height (about 3 ft) if (sh.dist && sh.dist >= 8 && T > 0.3) { f.arc = Math.round(Math.atan2(16.1*T*T - 3, Math.max(1, sh.dist - 1.5))*180/Math.PI); f.arcHow = "court"; } // side-on check: the ball's fall must match gravity at the rim's scale (within 20%), or the flight runs toward or away from the lens // and the sideways travel in the picture must cover most of the distance that flight time implies (a shot at 45 degrees covers about 16 T^2 - 3 ft) else if (!S.H && ff.m.g >= 0.8 && ff.m.g <= 1.25 && Math.abs(ff.at(ff.tRim)[0] - r.x)*vw/(sh.rim[2]*vw/1.5) >= 0.75*(16.1*T*T - 3)) { f.arc = Math.round(Math.atan2(vyPx, vxPx)*180/Math.PI); f.arcHow = "picture"; } f.ff = ff; } const pre = localMedian(L, t - 0.6, t - 0.28), stand = localMedian(L, t - 1.0, t - 0.5) || pre; if (pre) { f.st = {h:stand.h, feet:pre.feet}; f.rel = +((pre.feet - r.y) / stand.h).toFixed(2); // floor positions in feet: the court map when it's marked, otherwise the player's own height (about 5.75 ft) as the ruler const k = 5.75 / (stand.h * vh), approx = !S.H; const floorAt = (q) => { if (S.H) return toCourt(q.cx, q.cy + q.h/2, q.t); const a = poseAt(q.t), b = poseAt(t), z = a && b && a[3] > 0 ? b[3]/a[3] : 1, ox = a ? a[1] : 0, oy = a ? a[2] : 0; return [(q.cx - ox)*z*vw*k, (q.cy + q.h/2 - oy)*z*vh*k]; }; const medFloor = (a, b) => { const P = (L || []).filter(q => q.t >= a && q.t <= b).map(floorAt).filter(Boolean); if (!P.length) return null; const md = v => v.sort((x, y) => x - y)[v.length >> 1]; return [md(P.map(c => c[0])), md(P.map(c => c[1]))]; }; const p0 = medFloor(t - 0.6, t - 0.28), p1 = medFloor(t + 0.6, t + 1.25); // more than 6 ft is a tracking slip, not a jump shot if (p0 && p1) { const d = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]); if (d <= 6) { f.drift = +d.toFixed(1); if (S.H) { f.p0 = p0; f.p1 = p1; } f.approx = approx; } } // catch to release: time since the run into the spot ended (two quick steps in a row) if (L) { const C = L.filter(q => q.t <= t - 0.45).map(q => ({t:q.t, c:floorAt(q)})).filter(q => q.c); const v = i => Math.hypot(C[i].c[0] - C[i-1].c[0], C[i].c[1] - C[i-1].c[1]) / Math.max(0.1, C[i].t - C[i-1].t); for (let i = C.length - 1; i >= 2; i--) if (v(i) > 3.5 && v(i-1) > 3.5) { f.trigger = +(t - C[i].t).toFixed(1); break; } } } else f.unmeasured = "shooter not found at the release"; if (layup) { delete f.arc; delete f.rel; delete f.trigger; delete f.set; delete f.drift; } f.flags = Object.keys(FORM).filter(k => f[k] != null && !FORM[k].good(f[k]) && !(k === "drift" && f.approx && f[k] <= 2.5)); if (ff) f.g = +ff.m.g.toFixed(2); f.score = Math.max(0, 100 - f.flags.length * 22); return f; } function speedSeries(){ const mv = movementStats(); if (!mv) return null; const P = mv.path, out = []; for (let i=1;i 0.7) continue; out.push({t:P[i].t, v:Math.hypot(P[i].x - P[i-1].x, P[i].y - P[i-1].y)/dt}); } // smooth over about a second return out.map((q, i) => { let s = 0, n = 0; for (let j=Math.max(0,i-2); j<=Math.min(out.length-1,i+2); j++){ s += out[j].v; n++; } return {t:q.t, v:s/n}; }); } const INTENSITY = [{max:5.5, name:"Walk", col:"#56627c"}, {max:9, name:"Jog", col:"#2EE6C5"}, {max:14, name:"Run", col:"#FFC24B"}, {max:99, name:"Sprint", col:"#FF5A1F"}]; const intensityOf = v => INTENSITY.find(z => v < z.max); function coachMoments(){ const M = []; if (S.shots) for (const sh of S.shots) { if (sh.mine !== true) continue; sh.form = shotForm(sh); const f = sh.form, t = f.relPt ? f.relPt.t : (sh.relT || sh.t); if (f.flags && f.flags.length) { for (const k of f.flags) M.push({t, kind:"fix", key:k, shot:sh, title:RULES[k].title, metric:`${FORM[k].label}: ${k === "drift" && f.approx ? "about " : ""}${fmtV(k, f[k])}${k === "arc" && f.arcFt != null ? `, ${f.arcFt} ft over the rim` : ""} (target ${FORM[k].target})`, fix:RULES[k].fix, drill:RULES[k].drill, reps:RULES[k].reps}); } else if (f.arc != null || f.drift != null) { const bits = []; if (f.arc != null) bits.push(`${f.arc}° into the rim${f.arcFt != null ? `, ${f.arcFt} ft over it` : ""}`); if (f.drift != null) bits.push(`landed ${f.drift} ft from takeoff`); if (f.trigger != null) bits.push(`${f.trigger} s catch to release`); M.push({t, kind:"good", shot:sh, title: f.layup ? "Clean finish" : "Good rep", metric: bits.join(" · "), fix:"Repeat this one: feet set, straight up, high finish."}); } } const sp = speedSeries(); S.speed = sp; if (sp && sp.length > 4) { // walking with somewhere to go: a move between spots of 9+ ft that never got past a jog let a = null, dist = 0, peak = 0; for (let i=1;i 1.5; if (moving) { if (a == null) { a = sp[i-1].t; dist = 0; peak = 0; } dist += sp[i].v*(sp[i].t - sp[i-1].t); peak = Math.max(peak, sp[i].v); } if ((!moving || i === sp.length-1) && a != null) { const b = sp[i-1].t; if (b - a >= 2.5 && dist >= 9 && peak < 7.5) M.push({t:a, end:b, kind:"fix", key:"walk", title:RULES.walk.title, metric:`${Math.round(dist)} ft in ${(b-a).toFixed(1)} s, top ${(peak*0.6818).toFixed(1)} mph (game speed 8+ mph)`, fix:RULES.walk.fix, drill:RULES.walk.drill, reps:RULES.walk.reps}); a = null; } } // best burst let best = null; for (const q of sp) if (!best || q.v > best.v) best = q; if (best && best.v >= 13) M.push({t:best.t - 0.5, kind:"good", title:"Top-speed burst", metric:`${(best.v*0.6818).toFixed(1)} mph`, fix:"This is game speed. Ask for it on every transition rep."}); } M.sort((a,b) => a.t - b.t); S.moments = M; return M; } function formSummary(){ const shots = (S.shots || []).filter(s => s.mine === true && s.form && !s.form.layup); const out = {}; for (const k of Object.keys(FORM)) { const v = shots.map(s => s.form[k]).filter(x => x != null); if (!v.length) continue; v.sort((a,b) => a-b); out[k] = {median: v[v.length>>1], n: v.length, flagged: v.filter(x => !FORM[k].good(x)).length}; } const sc = shots.map(s => s.form.score).filter(x => x != null); out.score = sc.length ? Math.round(sc.reduce((a,b) => a+b, 0)/sc.length) : null; return out; } /* ===================== coaching UI: hero, scorecard, moments, timeline lanes, overlays ===================== */ const fmtV = (k, v) => /^[°×]/.test(FORM[k].unit) ? `${v}${FORM[k].unit.split(" ")[0]}` : `${v} ${FORM[k].unit.split(" ")[0]}`; const GAUGE = {arc:{lo:25,hi:60,t:40,dir:1}, rel:{lo:0.5,hi:1.7,t:0.8,dir:1}, drift:{lo:0,hi:5,t:2,dir:-1}, set:{lo:0,hi:10,t:3,dir:-1}, trigger:{lo:0,hi:2.5,t:1.25,dir:-1}}; const SHORT = {arc:"ARC", rel:"LOW", drift:"DRIFT", trigger:"SLOW", walk:"WALK"}; function gaugeHTML(k, v){ const g = GAUGE[k]; if (!g || v == null) return ""; const P = x => clamp((x - g.lo)/(g.hi - g.lo), 0, 1)*100, okA = g.dir > 0 ? P(g.t) : 0, okB = g.dir > 0 ? 100 : P(g.t); return ``; } const who = () => S.follow && S.follow.number ? "#" + S.follow.number : "Player"; function fixCounts(){ const c = {}; for (const m of S.moments || []) if (m.kind === "fix") (c[m.key] = c[m.key] || []).push(m); return Object.entries(c).sort((a, b) => b[1].length - a[1].length || a[1][0].t - b[1][0].t); } function ringSVG(score){ const r = 40, C = 2*Math.PI*r, f = score == null ? 0 : score/100, col = score == null ? "#5D6679" : score >= 75 ? "#3DDC84" : score >= 55 ? "#FFC24B" : "#FF5A1F"; return `
${score == null ? "–" : score}FORM
`; } function renderHero(){ const H = $("#hero"); if (!H) return; const sh = shootingStats(), mv = movementStats(), fs = formSummary(); if (!(sh && sh.att) && !mv) { H.hidden = true; return; } H.hidden = false; const fc = fixCounts(); const prio = fc.slice(0, 3).map(([k, L]) => ``).join("") || ``; const dur = vid.duration || (S.an && S.an.duration) || 0, cov = mv && dur ? Math.round(mv.tracked/dur*100) : null; const kpi = (v, lab, note, ok) => `
${v}${lab}${note ? `${note}` : ""}
`; H.innerHTML = `${ringSVG(fs.score)}
Session report

${esc(S.follow && S.follow.name ? S.follow.name : (S.follow && S.follow.number ? "Player #" + S.follow.number : "Shooting workout"))}

${esc(S.source.sample ? "Spot-shooting workout" : "Workout")} · ${fmt(dur)} · ${sh ? sh.att + " shots" : ""}${cov != null ? ` · on camera ${cov}%` : ""}
${prio}
${sh && sh.att ? kpi(`${sh.made}/${sh.att}`, "field goals", pct(sh.made, sh.att), sh.made/sh.att >= 0.5) : ""} ${fs.arc ? kpi(fs.arc.median + "°", "entry angle", fs.arc.flagged ? `${fs.arc.flagged} flat · target 40°+` : "on target", !fs.arc.flagged) : ""} ${fs.drift ? kpi(fs.drift.median.toFixed(1), "drift, ft", fs.drift.flagged ? `${fs.drift.flagged} drifted` : "lands square", !fs.drift.flagged) : ""} ${mv ? kpi((mv.top*0.6818).toFixed(1), "top mph", `${Math.round(mv.dist)} ft run`, true) : ""}
`; } $("#hero").addEventListener("click", e => { const b = e.target.closest("[data-goto]"); if (!b) return; const m = (S.moments || []).find(q => Math.abs(q.t - +b.dataset.goto) < 0.01); if (m) playMoment(m); }); function scorecardHTML(){ const fs = formSummary(), keys = Object.keys(FORM).filter(k => fs[k]); if (!keys.length) return ""; let h = `

Form scorecard median of ${fs[keys[0]].n} jump shots

`; for (const k of keys) { const z = fs[k]; h += `
${FORM[k].label}${fmtV(k, z.median)}${gaugeHTML(k, z.median)}Target ${FORM[k].target} · ${z.flagged ? `${z.flagged} of ${z.n} off target` : "every rep on target"}
`; } h += `
`; const fc = fixCounts(); if (fc.length) { h += `

Priorities this week most frequent first

    `; for (const [k, L] of fc.slice(0, 4)) h += `
  1. ${esc(RULES[k].title)} ×${L.length}

    ${esc(RULES[k].fix)}

    Drill ${esc(RULES[k].drill)} · ${esc(RULES[k].reps)}

    ${L.slice(0, 4).map(m => ``).join("")}
  2. `; h += `
`; } return h; } function renderMoments(){ const card = $("#momentsCard"), L = $("#moments"); if (!card) return; const M = S.moments || []; if (!M.length) { card.hidden = true; L.innerHTML = ""; return; } card.hidden = false; const f = S.mFilter || "all", show = M.map((m, i) => [m, i]).filter(([m]) => f === "all" || m.kind === f); const nf = M.filter(m => m.kind === "fix").length, ng = M.length - nf; $("#momentsSub").textContent = `${nf} to fix, ${ng} to repeat. Tap one to watch it with the correction drawn on the video.`; L.innerHTML = show.map(([m, i]) => { const sh = m.shot, n = sh ? S.shots.indexOf(sh) + 1 : 0, v = m.key && sh && sh.form ? sh.form[m.key] : null; const gauge = m.key && GAUGE[m.key] && v != null ? `
${FORM[m.key].label}${fmtV(m.key, v)} · target ${FORM[m.key].target}
${gaugeHTML(m.key, v)}
` : `
${esc(m.metric)}
`; const kind = m.kind === "fix" ? (sh ? `Fix · shot ${n}` : "Fix · movement") : (sh ? `Good · shot ${n}` : "Good · movement"); return ``; }).join(""); } document.querySelectorAll("[data-mf]").forEach(b => b.onclick = () => { S.mFilter = b.dataset.mf; document.querySelectorAll("[data-mf]").forEach(c => c.setAttribute("aria-pressed", c === b)); renderMoments(); }); $("#moments").addEventListener("click", e => { const b = e.target.closest("[data-m]"); if (b) playMoment(S.moments[+b.dataset.m]); }); $("#report").addEventListener("click", e => { const b = e.target.closest("[data-mt]"); if (!b) return; const m = (S.moments || []).find(q => Math.abs(q.t - +b.dataset.mt) < 0.01); if (m) playMoment(m); }); function playMoment(m){ S.focusM = m; const sh = m.shot; if (m.end) playRange(Math.max(0, m.t - 0.6), m.end + 0.6); else if (sh) playRange(Math.max(0, (sh.relT || sh.t) - 1.8), (sh.rimT || sh.end) + 1.9); else playRange(Math.max(0, m.t - 1), m.t + 3); $("#stage").scrollIntoView({behavior:"smooth", block:"nearest"}); } function momentsAt(now){ const M = S.moments || []; const hit = M.filter(m => m.end ? now >= m.t - 0.3 && now <= m.end + 0.4 : m.shot ? now >= (m.shot.relT || m.t) - 1.4 && now <= (m.shot.rimT || m.t + 1) + 1.9 : now >= m.t - 0.8 && now <= m.t + 2.4); if (!hit.length) return []; const fx = hit.filter(m => m.kind === "fix"); return fx.length ? fx : hit.slice(0, 1); } let coachKey = ""; function updateCoachCard(){ const C = $("#coachCard"), now = vid.currentTime || 0; const ms = (S.aiView && !S.reel && !S.picking && !S.busy) ? momentsAt(now) : []; const key = ms.map(m => m.t + m.title).join("|"); if (key !== coachKey) { coachKey = key; if (!ms.length) C.hidden = true; else { const m = ms[0], sh = m.shot, n = sh ? S.shots.indexOf(sh) + 1 : 0; C.className = "coachcard " + m.kind; C.hidden = false; C.innerHTML = `
${m.kind === "fix" ? "Coach's fix" : "Keep this"}${sh ? " · shot " + n : ""}${fmt(m.t)}

${esc(ms.map(q => q.title).join(" + "))}

${ms.map(q => `
${esc(q.metric)}
`).join("")}

${esc(m.fix)}

`; } } document.querySelectorAll(".mcard").forEach(el => { const m = (S.moments || [])[+el.dataset.m]; el.classList.toggle("now", !!m && ms.includes(m)); }); } function speedNow(t){ const sp = S.speed; if (!sp || !sp.length) return null; let lo = 0, hi = sp.length - 1; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (sp[mid].t < t) lo = mid; else hi = mid; } const q = Math.abs(sp[lo].t - t) < Math.abs(sp[hi].t - t) ? sp[lo] : sp[hi]; return Math.abs(q.t - t) < 0.8 ? q.v : null; } function updateLiveHud(){ const L = $("#liveHud"); if (!S.aiView || S.reel || S.picking || S.busy || !(S.moments || S.speed)) { L.hidden = true; return; } const now = vid.currentTime || 0, v = speedNow(now), z = v != null ? intensityOf(v) : null; const mine = (S.shots || []).filter(s => s.mine === true && (s.rimT || s.end) <= now + 0.05), mk = mine.filter(s => s.made).length; const last = mine.filter(s => s.form && s.form.arc != null).pop(); const seg = INTENSITY.map((q, i) => ``).join(""); L.hidden = false; L.innerHTML = `
Speed${v != null ? (v*0.6818).toFixed(1) : "–"}MPH
${seg}
Shots${mk}/${mine.length}
${last ? `
Last arc${last.form.arc}°
` : ""}`; } function pill(ctx, x, y, text, bg, fg, px, align){ ctx.font = `700 ${Math.round(13*px*1.35)}px "Barlow Condensed", Arial Narrow, sans-serif`; const w = ctx.measureText(text).width + 14*px, h = 20*px, x0 = align === "right" ? x - w : align === "left" ? x : x - w/2; ctx.fillStyle = bg; roundRect(ctx, x0, y - h/2, w, h, 5*px); ctx.fill(); ctx.fillStyle = fg; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillText(text, x0 + 7*px, y + px); ctx.textBaseline = "alphabetic"; } function arrow(ctx, a, b, col, px){ const ang = Math.atan2(b[1]-a[1], b[0]-a[0]), L = 12*px; ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 3*px; ctx.lineCap = "round"; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke(); ctx.beginPath(); ctx.moveTo(b[0], b[1]); ctx.lineTo(b[0] - L*Math.cos(ang - 0.45), b[1] - L*Math.sin(ang - 0.45)); ctx.lineTo(b[0] - L*Math.cos(ang + 0.45), b[1] - L*Math.sin(ang + 0.45)); ctx.closePath(); ctx.fill(); } function drawCoachOverlay(ctx, map, vw, vh, s, px, now){ if (!S.shots) return; const sh = S.shots.find(q => q.mine === true && q.release && now >= (q.relT || q.t) - 1.4 && now <= (q.rimT || q.end) + 1.9); if (!sh || !sh.form) return; const f = sh.form; if (!f.relPt) return; const rt = f.relPt.t, bad = k => f.flags && f.flags.includes(k); const ftPx = sh.rim[2]*vw*s/1.5; // screen px per foot at the rim const R = map(f.relPt.x, f.relPt.y), rim = map(sh.rim[0], sh.rim[1]); ctx.save(); // moving into the shot: feet direction before release if (bad("set") && now < rt + 0.4 && f.p0m && f.p1m) { const a = fromCourt(f.p0m[0], f.p0m[1], now), b = fromCourt(f.p1m[0], f.p1m[1], now); if (a && b) { const A = map(a[0], a[1]), B = map(b[0], b[1]); arrow(ctx, A, B, "#FF8A5C", px); pill(ctx, (A[0]+B[0])/2, Math.max(A[1], B[1]) + 22*px, `MOVING ${f.set} FT/S · SET FEET FIRST`, "#FF8A5C", "#1A0B03", px); } } if (now >= rt - 0.05) { // release point and height if (f.st && bad("rel")) { const ty = f.st.feet - 1.25*f.st.h, T = map(f.relPt.x, ty); ctx.setLineDash([6*px, 5*px]); ctx.strokeStyle = "#3DDC84"; ctx.lineWidth = 2.2*px; ctx.beginPath(); ctx.moveTo(T[0] - 46*px, T[1]); ctx.lineTo(T[0] + 46*px, T[1]); ctx.stroke(); ctx.setLineDash([]); pill(ctx, T[0] + 50*px, T[1], "RELEASE HERE", "#3DDC84", "#04130a", px, "left"); arrow(ctx, [R[0], R[1] - 4*px], [T[0], T[1] + 8*px], "rgba(61,220,132,.8)", px*0.7); } ctx.fillStyle = "#fff"; ctx.beginPath(); ctx.arc(R[0], R[1], 5*px, 0, 7); ctx.fill(); ctx.strokeStyle = bad("rel") ? "#FF8A5C" : "#3DDC84"; ctx.lineWidth = 2*px; ctx.beginPath(); ctx.arc(R[0], R[1], 9*px, 0, 7); ctx.stroke(); if (now < rt + 0.5) pill(ctx, R[0] - 14*px, R[1] - 2*px, f.rel != null ? `RELEASE ${f.rel}× HEIGHT` : "RELEASE", bad("rel") ? "#FF8A5C" : "rgba(237,241,247,.92)", "#0A0D13", px, "right"); // target arc (ghost), only when the arc is flat if (bad("arc")) { // the arc that drops into the rim at 45 degrees from the same release point const dx = Math.abs(rim[0] - R[0]), dy = R[1] - rim[1]; let hLo = 1, hHi = 5000, H = 0; for (let it=0; it<40; it++){ H = (hLo + hHi)/2; const D = 2*H*(1 + Math.sqrt(Math.max(0, (H + dy)/H))); if (D > dx) hHi = H; else hLo = H; } const apexY = rim[1] - H, y0 = R[1], y1 = rim[1]; let hgt = 0, lo = 0, hi = 4000; for (let it=0; it<40; it++){ hgt = (lo+hi)/2; let mn = 1e9; for (let u=0; u<=1; u+=0.02) mn = Math.min(mn, (1-u)*y0 + u*y1 - 4*hgt*u*(1-u)); if (mn > apexY) lo = hgt; else hi = hgt; } ctx.setLineDash([7*px, 6*px]); ctx.strokeStyle = "rgba(61,220,132,.9)"; ctx.lineWidth = 2.4*px; ctx.beginPath(); let ax = R[0], ay = 1e9; for (let u=0; u<=1.0001; u+=0.02){ const x = R[0] + (rim[0]-R[0])*u, y = (1-u)*y0 + u*y1 - 4*hgt*u*(1-u); u ? ctx.lineTo(x, y) : ctx.moveTo(x, y); if (y < ay) { ay = y; ax = x; } } ctx.stroke(); ctx.setLineDash([]); pill(ctx, ax, ay - 16*px, "TARGET · 45° INTO THE RIM", "#3DDC84", "#04130a", px); } // the real flight, drawn as it happens const pts = (sh.flight || []).filter(p => p[0] <= now + 0.02); if (pts.length > 1) { const col = bad("arc") ? "#FF8A5C" : "#3DDC84"; ctx.shadowColor = col; ctx.shadowBlur = 12*px; ctx.strokeStyle = col; ctx.lineWidth = 3.4*px; ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.beginPath(); pts.forEach((p, i) => { const [x, y] = map(p[1], p[2]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); }); ctx.stroke(); ctx.shadowBlur = 0; let ap = sh.flight[0]; for (const p of sh.flight) if (p[2] < ap[2]) ap = p; if (now >= ap[0] && f.arc != null) { const A = map(ap[1], ap[2]); ctx.fillStyle = col; ctx.beginPath(); ctx.arc(A[0], A[1], 4*px, 0, 7); ctx.fill(); pill(ctx, A[0], A[1] - 18*px, `${f.arcFt != null ? f.arcFt + " FT OVER RIM · " : ""}${f.arc}° IN`, col, "#0A0D13", px); } } // landing: takeoff to landing on the floor if (f.p0 && f.p1 && now >= rt + 0.25) { const a = fromCourt(f.p0[0], f.p0[1], now), b = fromCourt(f.p1[0], f.p1[1], now); if (a && b) { const A = map(a[0], a[1]), B = map(b[0], b[1]), col = bad("drift") ? "#FF8A5C" : "#3DDC84"; ctx.strokeStyle = "rgba(255,255,255,.85)"; ctx.lineWidth = 2*px; ctx.beginPath(); ctx.ellipse(A[0], A[1], 13*px, 4.5*px, 0, 0, 7); ctx.stroke(); if (Math.hypot(B[0]-A[0], B[1]-A[1]) > 6*px) arrow(ctx, A, B, col, px); pill(ctx, (A[0]+B[0])/2, Math.max(A[1], B[1]) + 26*px, bad("drift") ? `DRIFT ${f.drift} FT · LAND WHERE YOU JUMP` : `LANDED ${f.drift} FT`, col, "#0A0D13", px); } } } ctx.restore(); } /* ===================== scoring ===================== */ function robustZ(arr, win){ const n = arr.length, out = new Float32Array(n); if (!n) return out; // moving average baseline const pre = new Float64Array(n+1); for (let i=0;ix-y); const mad = sorted[Math.floor(sorted.length/2)] * 1.4826 || 1; for (let i=0;i a.t ? clamp((t-a.t)/(b.t-a.t), 0, 1) : 0; out[i] = va + (vb-va)*u; } return out; } function gauss(arr, sigma){ const r = Math.ceil(sigma*3), k = []; let s = 0; for (let i=-r;i<=r;i++){ const w = Math.exp(-i*i/(2*sigma*sigma)); k.push(w); s += w; } const out = new Float32Array(arr.length); for (let i=0;i=0 && q { let v = 0; for (const b of f.b) if (b[1] < 0.42) v = Math.max(v, 0.6 + b[2]); return v; }); const spread = interpFrames(an.frames, null, n, f => { if (f.p.length < 3) return 0; let cx = 0, cy = 0; for (const p of f.p){ cx += p[0]; cy += p[1]; } cx /= f.p.length; cy /= f.p.length; let s = 0; for (const p of f.p) s += Math.hypot(p[0]-cx, (p[1]-cy)*0.56); return -s/f.p.length; }); const zc = robustZ(Array.from(spread), 40); let inv = new Float32Array(n), pres = new Float32Array(n); if (S.track) { const tr = S.track; pres = interpFrames(tr, null, n, f => f.ok ? 1 : 0); inv = interpFrames(tr, null, n, (f) => { if (!f.ok) return 0; const fr = an.frames[f.i]; let near = 0; const tx = fr.b.length ? fr.b[0][0] : fr.ax, ty = fr.b.length ? fr.b[0][1] : fr.ay; if (tx != null) near = 1 - clamp(Math.hypot(f.cx - tx, (f.cy - ty)*0.56)/0.3, 0, 1); return 0.35 + 0.65*near; }); } return {n, za, zh, zm, ball, zc, inv, pres}; } function rescore(fresh){ if (!S.an) return; const sp = SPORTS[S.sport], sz = SIZES[S.size], X = series(); S.X = X; const P = S.track ? (S.mineFirst ? 2.2 : 0.8) : 0; const raw = new Float32Array(X.n); const hasAudio = !!S.an.audio; for (let i=0;i= 0 && i < X.n) raw[i] += sh.made ? 5 : 2.2; } } const sc = gauss(raw, 0.75/GRID); S.score = sc; let mean = 0; for (const v of sc) mean += v; mean /= sc.length; let sd = 0; for (const v of sc) sd += (v-mean)**2; sd = Math.sqrt(sd/sc.length) || 1; S.scoreStats = {mean, sd}; const half = Math.round(sp.gap/2/GRID), thr = mean + sz.k*sd, peaks = []; for (let i=1;i sc[i] || (sc[j] === sc[i] && j < i)) { isMax = false; break; } if (isMax) peaks.push(i); } peaks.sort((a,b) => sc[b]-sc[a]); const capN = Math.max(sz.min, Math.round(S.an.duration/60*sz.per)); const chosen = peaks.slice(0, capN).sort((a,b) => a-b); const old = fresh ? [] : S.clips; const clips = []; for (const i of chosen) { const peak = i*GRID; // lock peak to the start of the reaction: walk back while audio is rising let start = Math.max(0, peak - sp.pre), end = Math.min(S.an.duration, peak + sp.post); const prev = clips[clips.length-1]; if (prev && start < prev.end) { if (peak - prev.peak >= 3.5) { const mid = Math.max(prev.peak + 1.5, peak - sp.pre*0.6); prev.end = Math.min(prev.end, mid); start = Math.max(start, prev.end); } else { if (sc[i] > prev.raw) { prev.peak = peak; prev.raw = sc[i]; } prev.end = Math.max(prev.end, Math.min(end, prev.start + 14)); continue; } } clips.push({start, end, peak, raw:sc[i]}); } clips.forEach((c, k) => { const lo = Math.max(0, Math.round((c.peak-1.5)/GRID)), hi = Math.min(X.n-1, Math.round((c.peak+1.5)/GRID)); let a = -9, m = -9, b = 0, iv = 0, pr = 0; for (let i=lo;i<=hi;i++){ a = Math.max(a, X.za[i]); m = Math.max(m, X.zm[i]); b = Math.max(b, X.ball[i]); iv = Math.max(iv, X.inv[i]); } const s0 = Math.round(c.start/GRID), s1 = Math.round(c.end/GRID); let cnt = 0; for (let i=s0;i 2.2) { tags.push(["Crowd roar","hot"]); ti = 0; } else if (hasAudio && a > 1.0) { tags.push(["Crowd reaction",""]); ti = 1; } if (m > 1.4) { tags.push(["Fast action",""]); if (ti > 1) ti = 2; } if (b > 0.5) tags.push(["Ball in the air",""]); c.shot = null; if (useShots) { const inClip = S.shots.filter(sh => sh.t >= c.start - 0.3 && sh.t <= c.end); if (inClip.some(sh => sh.made)) { tags.unshift(["Made basket","hot"]); ti = 0; c.shot = "made"; } else if (inClip.length) { tags.unshift(["Missed shot",""]); if (ti > 1) ti = 3; c.shot = "miss"; } } const mine = !!(S.track && pr > 0.45); if (mine) tags.push([(S.follow.number ? "#" + S.follow.number : "Your player") + " on screen","trk"]); const prevClip = old.find(o => Math.abs(o.peak - c.peak) < 1.5); c.id = "c" + Math.round(c.peak*4); c.title = sp.titles[ti]; if (c.shot === "made") c.title = "Bucket!"; else if (c.shot === "miss") c.title = "Shot attempt"; c.tags = tags; c.mine = !!mine; c.presence = pr; c.pct = clamp(Math.round(50 + 18*(c.raw - mean)/sd), 1, 99); c.keep = prevClip ? prevClip.keep : true; c.thumb = prevClip ? prevClip.thumb : (S.thumbCache && S.thumbCache[c.id]) || null; c.ai = prevClip ? prevClip.ai : null; if (c.ai) { c.title = c.ai.title || c.title; } if (prevClip && prevClip.trimmed) { c.start = prevClip.start; c.end = prevClip.end; c.trimmed = true; } }); if (S.mineFirst && S.track) clips.sort((a,b) => (b.mine - a.mine) || (a.start - b.start)); S.clips = clips; renderRail(); drawTimeline(); if (!fresh) makeThumbs(); } /* ===================== tracking ===================== */ function buildTrack(){ const an = S.an, F = an.frames; if (!S.follow || !F.length || !an.vision) return null; // 1. multi-object tracklets: every detection is claimed by at most one track per frame const tid = F.map(f => new Array(f.p.length).fill(-1)); const T = []; let active = []; for (let i=0;i 0 && F[i-1].p.length && P.length) { const dxs = [], dys = []; for (const p of P) { let bd = 1, bq = null; for (const q of F[i-1].p) { const d = Math.hypot(p[0]-q[0], p[1]-q[1]); if (d < bd && bhat(p[5], q[5]) > 0.7) { bd = d; bq = q; } } if (bq && bd < 0.25) { dxs.push(p[0]-bq[0]); dys.push(p[1]-bq[1]); } } if (dxs.length >= 2) { dxs.sort((x,y)=>x-y); dys.sort((x,y)=>x-y); sx = dxs[dxs.length>>1]; sy = dys[dys.length>>1]; } } const pairs = []; active.forEach((tr, a) => { const px = tr.x + tr.vx + sx, py = tr.y + tr.vy + sy; P.forEach((p, k) => { const d = Math.hypot(p[0]-px, (p[1]-py)*0.8), sim = bhat(p[5], tr.sig), hz = Math.abs(Math.log((p[3]+1e-3)/(tr.h+1e-3))); if (d < 0.16 + 0.05*tr.miss && sim > 0.55) pairs.push([d*2.2 + (1-sim)*1.2 + hz*0.4, a, k]); }); }); pairs.sort((u,v) => u[0]-v[0]); const usedA = new Set(), usedK = new Set(); // a crossing with a look-alike makes the match ambiguous: end the tracklet instead of guessing const firstCost = new Map(), contested = new Set(); for (const [c, a] of pairs) { if (!firstCost.has(a)) firstCost.set(a, c); else if (c - firstCost.get(a) < 0.07 && !contested.has(a)) contested.add(a); } for (const a of contested) { active[a].miss = 99; usedA.add(a); } for (const [, a, k] of pairs) { if (usedA.has(a) || usedK.has(k)) continue; usedA.add(a); usedK.add(k); const tr = active[a], p = P[k]; tr.vx = (p[0]-tr.x-sx)*0.5 + tr.vx*0.5; tr.vy = (p[1]-tr.y-sy)*0.5 + tr.vy*0.5; tr.x = p[0]; tr.y = p[1]; tr.h = p[3]; tr.miss = 0; for (let j=0;j<15;j++) tr.sig[j] = tr.sig[j]*0.85 + p[5][j]*0.15; tr.items.push([i,k]); tid[i][k] = tr.id; } active.forEach((tr, a) => { if (!usedA.has(a) || tr.miss >= 99) { tr.miss++; tr.x += tr.vx*0.5 + sx; tr.y += tr.vy*0.5 + sy; tr.vx *= 0.5; tr.vy *= 0.5; } }); active = active.filter(tr => tr.miss <= 3); P.forEach((p, k) => { if (!usedK.has(k)) { const tr = {id:T.length, x:p[0], y:p[1], h:p[3], vx:0, vy:0, sig:p[5].slice(), miss:0, items:[[i,k]]}; T.push(tr); active.push(tr); tid[i][k] = tr.id; } }); } // 2. chain tracklets outward from each anchor const out = F.map((f,i) => ({t:f.t, i, ok:false, cx:0, cy:0, w:0, h:0, dist:1e9})); const det = (it) => F[it[0]].p[it[1]]; for (const anc of S.follow.anchors) { let fi = 0; for (let i=0;i { const s = bhat(p[5], anc.sig) - Math.hypot(p[0]-anc.box[0], p[1]-anc.box[1])*4; if (s > bs) { bs = s; best = k; } }); if (best < 0) continue; const chain = new Set([tid[fi][best]]); for (const dir of [1, -1]) { let cur = T[tid[fi][best]]; for (let guard = 0; guard < 400; guard++) { const edge = dir > 0 ? cur.items[cur.items.length-1] : cur.items[0]; const eP = det(edge); let cand = null, cs = 1e9, second = 1e9; for (const tr of T) { if (chain.has(tr.id)) continue; const st = dir > 0 ? tr.items[0] : tr.items[tr.items.length-1]; const gap = (st[0] - edge[0])*dir; if (gap < 1 || gap > 6) continue; const p = det(st), d = Math.hypot(p[0]-eP[0], p[1]-eP[1]), sim = bhat(p[5], anc.sig); const c = d*1.5 + (1-sim)*2 + gap*0.05; if (sim > 0.65 && d < 0.10 + gap*0.025) { if (c < cs) { second = cs; cs = c; cand = tr; } else if (c < second) second = c; } } if (!cand || second - cs < 0.08) { // lost: pick the player up again later, but only if their look is unmistakable in that frame cand = null; let bestSim = 0.85; for (const tr of T) { if (chain.has(tr.id) || tr.items.length < 3) continue; const st = dir > 0 ? tr.items[0] : tr.items[tr.items.length-1]; const gap = (st[0] - edge[0])*dir; if (gap < 1 || gap > 60) continue; const p = det(st), sim = bhat(p[5], anc.sig); if (sim <= bestSim) continue; const rivals = F[st[0]].p.filter(q => q !== p && bhat(q[5], anc.sig) > 0.72).length; if (!rivals) { bestSim = sim; cand = tr; } } if (!cand) break; } chain.add(cand.id); cur = cand; } } for (const id of chain) for (const it of T[id].items) { const dist = Math.abs(F[it[0]].t - anc.t); if (dist < out[it[0]].dist) { const p = det(it); out[it[0]] = {t:F[it[0]].t, i:it[0], ok:true, cx:p[0], cy:p[1], w:p[2], h:p[3], dist}; } } } return out; } function trackAt(t){ const tr = S.track; if (!tr || !tr.length) return null; let lo = 0, hi = tr.length-1; while (hi - lo > 1){ const m = (lo+hi)>>1; if (tr[m].t <= t) lo = m; else hi = m; } const a = tr[lo], b = tr[hi]; if (!a.ok && !b.ok) return null; if (!a.ok) return b; if (!b.ok) return a; const u = b.t > a.t ? clamp((t-a.t)/(b.t-a.t), 0, 1) : 0; return {ok:true, cx:a.cx+(b.cx-a.cx)*u, cy:a.cy+(b.cy-a.cy)*u, w:a.w+(b.w-a.w)*u, h:a.h+(b.h-a.h)*u}; } function frameAt(t){ const F = S.an && S.an.frames; if (!F || !F.length) return null; let lo = 0, hi = F.length-1; while (hi - lo > 1){ const m = (lo+hi)>>1; if (F[m].t <= t) lo = m; else hi = m; } const f = Math.abs(F[lo].t - t) < Math.abs(F[hi].t - t) ? F[lo] : F[hi]; return Math.abs(f.t - t) <= Math.max(0.6, S.an.step) ? f : null; } /* ===================== thumbnails ===================== */ let thumbJob = 0; async function makeThumbs(){ const job = ++thumbJob; S.thumbCache = S.thumbCache || {}; const need = S.clips.filter(c => !c.thumb); if (!need.length) return; try { if (scanVid.src.indexOf(S.source.url) < 0 && scanVid.currentSrc !== S.source.url) scanVid.src = S.source.url; await loaded(scanVid); const c = document.createElement("canvas"); c.width = 320; c.height = 180; const x = c.getContext("2d"); for (const clip of need) { if (job !== thumbJob) return; await seek(scanVid, Math.max(0, clip.peak - 1.2)); x.drawImage(scanVid, 0, 0, 320, 180); clip.thumb = c.toDataURL("image/jpeg", 0.72); S.thumbCache[clip.id] = clip.thumb; const img = document.querySelector(`[data-thumb="${clip.id}"]`); if (img) img.src = clip.thumb; } } catch(e) { console.warn("thumbs", e); } } /* ===================== drawing ===================== */ function sizeCanvas(){ const r = view.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1); const w = Math.round(r.width*d), h = Math.round(r.height*d); if (view.width !== w || view.height !== h) { view.width = w; view.height = h; } const tl = $("#tl"), tr = tl.getBoundingClientRect(); if (tl.width !== Math.round(tr.width*d)) { tl.width = Math.round(tr.width*d); tl.height = Math.round(tr.height*d); } } function cropFor(v, W, H, opts){ const vw = v.videoWidth, vh = v.videoHeight; const outAspect = W/H; let cw, ch; const usePlayer = opts.playerCam; if (opts.vertical) { ch = vh / (usePlayer ? 1.15 : 1); cw = ch*outAspect; if (cw > vw){ cw = vw; ch = cw/outAspect; } } else if (usePlayer) { cw = vw/1.75; ch = cw/outAspect; if (ch > vh){ ch = vh; cw = ch*outAspect; } } else return null; // target center const t = v.currentTime, tk = trackAt(t); let tx = 0.5, ty = 0.5; if (tk && tk.ok) { tx = tk.cx; ty = tk.cy - tk.h*0.1; } else { const f = frameAt(t); if (f && f.ax != null) { tx = f.ax; ty = f.ay; } } const st = opts.camState || cam; const k = opts.snap ? 1 : 0.09; st.x += (tx - st.x)*k; st.y += (ty - st.y)*k; let cx = st.x*vw - cw/2, cy = st.y*vh - ch/2; cx = clamp(cx, 0, vw-cw); cy = clamp(cy, 0, vh-ch); return {x:cx, y:cy, w:cw, h:ch}; } function drawFrameTo(ctx, W, H, v, opts){ ctx.fillStyle = "#05070B"; ctx.fillRect(0,0,W,H); if (!v.videoWidth) return; const vw = v.videoWidth, vh = v.videoHeight; const crop = cropFor(v, W, H, opts) || {x:0, y:0, w:vw, h:vh}; const s = Math.min(W/crop.w, H/crop.h), dw = crop.w*s, dh = crop.h*s, dx = (W-dw)/2, dy = (H-dh)/2; ctx.drawImage(v, crop.x, crop.y, crop.w, crop.h, dx, dy, dw, dh); const map = (nx, ny) => [dx + (nx*vw - crop.x)*s, dy + (ny*vh - crop.y)*s]; const px = W/1000; // AI overlay if (opts.scan && S.scanPreview) { ctx.lineWidth = Math.max(1.5, 2*px); for (const p of S.scanPreview.persons) { const [x,y] = map(p[0]-p[2]/2, p[1]-p[3]/2); ctx.strokeStyle = "rgba(255,90,31,.9)"; ctx.strokeRect(x, y, p[2]*vw*s, p[3]*vh*s); } for (const b of S.scanPreview.balls) { const [x,y] = map(b[0], b[1]); ctx.strokeStyle = "#FFC24B"; ctx.beginPath(); ctx.arc(x, y, 14*px, 0, 7); ctx.stroke(); } return; } if (opts.ai && !opts.clean) { const f = frameAt(v.currentTime); if (f) { ctx.lineWidth = Math.max(1, 1.4*px); for (const p of f.p) { const [x,y] = map(p[0]-p[2]/2, p[1]-p[3]/2), w = p[2]*vw*s, h = p[3]*vh*s, c = Math.min(w,h)*0.22; ctx.strokeStyle = "rgba(237,241,247,.55)"; ctx.beginPath(); ctx.moveTo(x, y+c); ctx.lineTo(x, y); ctx.lineTo(x+c, y); ctx.moveTo(x+w-c, y); ctx.lineTo(x+w, y); ctx.lineTo(x+w, y+c); ctx.moveTo(x, y+h-c); ctx.lineTo(x, y+h); ctx.lineTo(x+c, y+h); ctx.moveTo(x+w-c, y+h); ctx.lineTo(x+w, y+h); ctx.lineTo(x+w, y+h-c); ctx.stroke(); } for (const b of f.b) { const [x,y] = map(b[0], b[1]); ctx.strokeStyle = "#FFC24B"; ctx.lineWidth = 2*px; ctx.beginPath(); ctx.arc(x, y, 12*px, 0, 7); ctx.stroke(); } } } // shot result at the rim if ((opts.ai || opts.reel) && S.sport === "basketball" && S.shots) { const now = v.currentTime, sh = S.shots.find(q => now >= q.t - 0.4 && now <= q.end + 1.4); if (sh) { const [rx, ry] = map(sh.rim[0], sh.rim[1]), rw = sh.rim[2]*vw*s/2; const col = sh.made ? "#3DDC84" : "#FFC24B"; ctx.strokeStyle = col; ctx.lineWidth = Math.max(2, 3*px); ctx.beginPath(); ctx.ellipse(rx, ry, rw*1.25, rw*0.45, 0, 0, Math.PI*2); ctx.stroke(); if (now >= sh.end - 0.2) { const lab = sh.made ? "MADE" : "MISS"; ctx.font = `700 ${Math.round(18*px*1.3)}px Barlow Condensed, Arial Narrow, sans-serif`; const tw = ctx.measureText(lab).width + 16*px; ctx.fillStyle = col; roundRect(ctx, rx - tw/2, ry - rw*1.1 - 30*px, tw, 24*px, 5*px); ctx.fill(); ctx.fillStyle = "#06140c"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(lab, rx, ry - rw*1.1 - 18*px); ctx.textAlign = "left"; ctx.textBaseline = "alphabetic"; } } } if (S.picking && S.pickMode === "hoop" && S.hoopDraft && !opts.reel) { const hd = S.hoopDraft, [rx, ry] = map(hd.cx, hd.cy), rw = hd.w*vw*s/2; ctx.strokeStyle = "#FFC24B"; ctx.lineWidth = Math.max(2, 2.5*px); ctx.setLineDash([6*px, 4*px]); ctx.beginPath(); ctx.ellipse(rx, ry, rw, rw*0.32, 0, 0, Math.PI*2); ctx.stroke(); ctx.setLineDash([]); } if (S.picking && S.pickMode === "court" && S.courtDraft && !opts.reel) { const pts = S.courtDraft.pts.map(p => map(p[0], p[1])); ctx.strokeStyle = "#2EE6C5"; ctx.lineWidth = Math.max(2, 2.5*px); ctx.beginPath(); pts.forEach((p, i) => i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1])); if (pts.length === 4) ctx.closePath(); ctx.stroke(); ctx.font = `700 ${Math.round(15*px*1.3)}px Barlow Condensed, sans-serif`; ctx.textAlign = "center"; ctx.textBaseline = "middle"; pts.forEach((p, i) => { ctx.fillStyle = "#2EE6C5"; ctx.beginPath(); ctx.arc(p[0], p[1], 11*px, 0, 7); ctx.fill(); ctx.fillStyle = "#04201b"; ctx.fillText(String(i+1), p[0], p[1] + px); }); ctx.textAlign = "left"; ctx.textBaseline = "alphabetic"; } else if (S.Hinv && opts.ai && !opts.reel && !S.picking) { ctx.strokeStyle = "rgba(46,230,197,.45)"; ctx.lineWidth = Math.max(1.2, 1.6*px); for (const L of courtLines()) { ctx.beginPath(); let first = true; for (const [X, Y] of L) { const q = fromCourt(X, Y, v.currentTime); if (!q) continue; const [sx, sy] = map(q[0], q[1]); first ? ctx.moveTo(sx, sy) : ctx.lineTo(sx, sy); first = false; } ctx.stroke(); } } if (opts.ai && !opts.reel && !S.picking && S.moments) drawCoachOverlay(ctx, map, vw, vh, s, px, v.currentTime); // follow marker const tk = trackAt(v.currentTime); if (tk && tk.ok && (opts.ai || opts.reel) ) { const [x,y] = map(tk.cx, tk.cy + tk.h/2), rw = tk.w*vw*s*0.75; ctx.strokeStyle = "#2EE6C5"; ctx.lineWidth = Math.max(2, 3*px); ctx.beginPath(); ctx.ellipse(x, y, rw, rw*0.28, 0, 0, Math.PI*2); ctx.stroke(); const [hx, hy] = map(tk.cx, tk.cy - tk.h/2); const tag = S.follow && S.follow.number ? "#" + S.follow.number : "YOU"; ctx.font = `700 ${Math.round(16*px*1.4)}px Barlow Condensed, Arial Narrow, sans-serif`; const tw = ctx.measureText(tag).width + 14*px; ctx.fillStyle = "#2EE6C5"; roundRect(ctx, hx - tw/2, hy - 34*px, tw, 22*px, 5*px); ctx.fill(); ctx.beginPath(); ctx.moveTo(hx-6*px, hy-12*px); ctx.lineTo(hx+6*px, hy-12*px); ctx.lineTo(hx, hy-5*px); ctx.fill(); ctx.fillStyle = "#04201b"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(tag, hx, hy - 23*px); ctx.textAlign = "left"; ctx.textBaseline = "alphabetic"; } } function roundRect(ctx, x, y, w, h, r){ ctx.beginPath(); ctx.moveTo(x+r,y); ctx.arcTo(x+w,y,x+w,y+h,r); ctx.arcTo(x+w,y+h,x,y+h,r); ctx.arcTo(x,y+h,x,y,r); ctx.arcTo(x,y,x+w,y,r); ctx.closePath(); } function drawStage(){ sizeCanvas(); if (S.busy && S.scanPreview) return; if (S.reel) { drawReelFrame(vctx, view.width, view.height, S.reel, false); return; } drawFrameTo(vctx, view.width, view.height, vid, {ai:S.aiView, playerCam:S.playerCam}); if (S.picking && S.pickMode === "player") drawPickOverlay(); } function drawPickOverlay(){ const f = S.pickDet; if (!f) return; const W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight; const s = Math.min(W/vw, H/vh), dx = (W-vw*s)/2, dy = (H-vh*s)/2; vctx.fillStyle = "rgba(5,7,11,.35)"; vctx.fillRect(0,0,W,H); f.forEach((p, k) => { const x = dx + (p[0]-p[2]/2)*vw*s, y = dy + (p[1]-p[3]/2)*vh*s, w = p[2]*vw*s, h = p[3]*vh*s; vctx.strokeStyle = k === S.pickHover ? "#2EE6C5" : "rgba(46,230,197,.55)"; vctx.lineWidth = k === S.pickHover ? 4 : 2; roundRect(vctx, x, y, w, h, 6); vctx.stroke(); if (k === S.pickHover) { vctx.fillStyle = "rgba(46,230,197,.15)"; vctx.fill(); } }); } /* timeline: three lanes (shots, pace, coaching) over a time axis */ const TLG = 66, TLR = 10; function tlX(t, W, d, dur){ return TLG*d + clamp(t/dur, 0, 1)*(W - (TLG + TLR)*d); } function drawTimeline(){ const c = $("#tl"); sizeCanvas(); const rw = c.getBoundingClientRect().width; if (!rw) return; const x = c.getContext("2d"), W = c.width, H = c.height, d = W / rw; x.clearRect(0,0,W,H); const dur = (S.an && S.an.duration) || vid.duration || 1, X = t => tlX(t, W, d, dur); const lanes = {shots:[6, 46], pace:[54, 116], coach:[124, 156]}, axisY = 160*d; const L = (k, i) => lanes[k][i]*d; S.tlHits = []; // lane backgrounds and labels x.font = `600 ${10.5*d}px "Barlow Condensed", Arial Narrow, sans-serif`; x.textBaseline = "middle"; for (const [k, lab] of [["shots","SHOTS"],["pace","PACE"],["coach","COACH"]]) { x.fillStyle = "rgba(255,255,255,.025)"; roundRect(x, TLG*d - 4*d, L(k,0), W - (TLG - 4 + TLR)*d + 4*d, L(k,1) - L(k,0), 7*d); x.fill(); x.fillStyle = "#6B7489"; x.fillText(lab.split("").join(String.fromCharCode(8202)), 4*d, (L(k,0) + L(k,1))/2); } // grid + axis const stepS = dur > 1800 ? 300 : dur > 600 ? 120 : dur > 180 ? 30 : 10; x.strokeStyle = "rgba(255,255,255,.05)"; x.lineWidth = 1; x.fillStyle = "#5D6679"; x.font = `${10.5*d}px Barlow, sans-serif`; x.textAlign = "center"; for (let s = 0; s <= dur + 0.01; s += stepS) { const px = X(s); x.beginPath(); x.moveTo(px, L("shots",0)); x.lineTo(px, L("coach",1)); x.stroke(); x.fillText(fmt(s), px, axisY + 9*d); } x.textAlign = "left"; // pace: intensity bars const sp = S.speed; if (sp && sp.length) { const top = L("pace",0) + 4*d, base = L("pace",1) - 3*d, vmax = 22; for (let i=1;i 0.8) continue; const v = sp[i].v, z = intensityOf(v), h = clamp(v/vmax, 0.04, 1)*(base - top); x.fillStyle = z.col; x.globalAlpha = 0.85; x.fillRect(X(sp[i-1].t), base - h, Math.max(1, X(sp[i].t) - X(sp[i-1].t)) + 0.4, h); } x.globalAlpha = 1; // 9 mph sprint line const sy = base - 13/vmax*(base - top); x.strokeStyle = "rgba(255,90,31,.35)"; x.setLineDash([3*d, 4*d]); x.beginPath(); x.moveTo(X(0), sy); x.lineTo(X(dur), sy); x.stroke(); x.setLineDash([]); x.fillStyle = "rgba(255,138,92,.75)"; x.font = `600 ${9.5*d}px "Barlow Condensed", sans-serif`; x.textAlign = "right"; x.fillText("9 MPH", X(dur) - 3*d, sy - 6*d); x.textAlign = "left"; } else if (S.track && S.X) { for (let i=0, n=S.X.pres.length; i 0.5) { x.fillStyle = "rgba(46,230,197,.5)"; x.fillRect(X(i/n*dur), L("pace",1) - 8*d, (W - (TLG+TLR)*d)/n + 0.5, 5*d); } } // shots if (S.shots) S.shots.forEach((sh, i) => { const t = sh.relT || sh.t, px = X(t), cy = (L("shots",0) + L("shots",1))/2 + 5*d, mine = sh.mine === true || !S.follow; const r = (mine ? 6.5 : 4)*d, flagged = sh.form && sh.form.flags && sh.form.flags.length; if (flagged) { x.strokeStyle = "rgba(255,90,31,.55)"; x.lineWidth = 2*d; x.beginPath(); x.arc(px, cy, r + 4*d, 0, 7); x.stroke(); } x.beginPath(); x.arc(px, cy, r, 0, 7); if (sh.made) { x.fillStyle = mine ? "#3DDC84" : "rgba(61,220,132,.35)"; x.fill(); } else { x.strokeStyle = mine ? "#C3CBD9" : "rgba(140,150,170,.4)"; x.lineWidth = 1.8*d; x.stroke(); } if (mine) { x.fillStyle = "#8C96AA"; x.font = `600 ${10*d}px "Barlow Condensed", sans-serif`; x.textAlign = "center"; x.fillText(String(i+1), px, L("shots",0) + 7*d); x.textAlign = "left"; } const m = (S.moments || []).find(q => q.shot === sh); S.tlHits.push({x:px, y:cy, m: m || {t, shot:sh, kind:"shot"}}); }); // coaching flags const M = S.moments || [], cy = (L("coach",0) + L("coach",1))/2, stackAt = {}; let lastLab = -1e9; for (const m of M) { const col = m.kind === "fix" ? "#FF5A1F" : "#3DDC84"; if (m.end) { const a = X(m.t), b = X(m.end); x.fillStyle = "rgba(255,90,31,.16)"; roundRect(x, a, L("coach",0) + 4*d, b - a, L("coach",1) - L("coach",0) - 8*d, 5*d); x.fill(); x.strokeStyle = "rgba(255,90,31,.6)"; x.lineWidth = 1.2*d; x.stroke(); x.fillStyle = "#ff9b73"; x.font = `700 ${10*d}px "Barlow Condensed", sans-serif`; x.textAlign = "center"; if (b - a > 40*d) x.fillText("WALKING", (a+b)/2, cy + d); x.textAlign = "left"; S.tlHits.push({x:(a+b)/2, y:cy, m}); continue; } const px = X(m.t), k = Math.round(m.t*4), off = (stackAt[k] = (stackAt[k] || 0) + 1) - 1, yy = cy - 6*d + off*11*d - (M.filter(q => !q.end && Math.round(q.t*4) === k).length > 1 ? 0 : -6*d); x.save(); x.translate(px, yy); x.rotate(Math.PI/4); x.fillStyle = col; x.fillRect(-4.2*d, -4.2*d, 8.4*d, 8.4*d); x.restore(); if (m.kind === "fix" && px - lastLab > 44*d) { x.fillStyle = "#ffb495"; x.font = `700 ${9.5*d}px "Barlow Condensed", sans-serif`; x.fillText(SHORT[m.key] || "", px + 8*d, yy + d); lastLab = px; } S.tlHits.push({x:px, y:yy, m}); } // playhead const now = vid.currentTime || 0, ph = X(now); x.fillStyle = "rgba(237,241,247,.95)"; x.fillRect(ph - d, L("shots",0) - 2*d, 2*d, L("coach",1) - L("shots",0) + 4*d); x.beginPath(); x.arc(ph, L("shots",0) - 1*d, 3.5*d, 0, 7); x.fill(); x.textBaseline = "alphabetic"; } /* ===================== rail ===================== */ function renderRail(){ const L = $("#list"); if (!S.clips.length) { L.innerHTML = `
${S.an ? "No standout moments at this setting. Try Generous." : "Run the analysis to find plays."}
`; updateTiles(); return; } L.innerHTML = ""; S.clips.forEach((c, k) => { const el = document.createElement("div"); el.className = "clip" + (c.keep ? "" : " off") + (k === S.active ? " active" : ""); el.dataset.k = k; const tags = c.tags.map(t => `${esc(t[0])}`).join("") + (c.ai ? `Claude` : ""); let cap = ""; if (c.aiBusy) cap = `
`; else if (c.ai) { cap = `
${esc(c.ai.caption || "")}
`; if (S.follow && c.ai.followed === false) cap += `
Claude can't see ${S.follow.number ? "#" + esc(S.follow.number) : "your player"} in this play.
`; } el.innerHTML = `

${esc(c.title)}

${fmt(c.start)}–${fmt(c.end)} · Play ${k+1}
${cap}
${tags}
${c.pct}
`; L.appendChild(el); }); updateTiles(); } function updateTiles(){ const kept = S.clips.filter(c => c.keep); $("#tClips").textContent = S.clips.length; $("#tReel").textContent = fmt(kept.reduce((s,c) => s + (c.end - c.start), 0) + (kept.length ? 3.5 : 0)); if (S.follow && S.track) { $("#tPlayer").textContent = S.clips.filter(c => c.mine).length; $("#tPlayerLbl").textContent = (S.follow.number ? "#" + S.follow.number : "your player") + " on screen in"; } else { $("#tPlayer").textContent = "–"; $("#tPlayerLbl").textContent = "tap Follow"; } const st = $("#shotStats"); if (S.sport === "basketball" && S.shots) { const made = S.shots.filter(x => x.made).length, n = S.shots.length; st.innerHTML = n ? `Shots ${made}/${n} made · ${Math.round(made/n*100)}% · ${S.hoops.length} hoop${S.hoops.length > 1 ? "s" : ""} watched` : `No shots seen at the marked hoop${S.hoops.length > 1 ? "s" : ""}. Check the ring matches the rim.`; st.hidden = false; } else st.hidden = true; const any = kept.length > 0; ["#reelBtn","#exportBtn","#vertBtn","#claudeBtn","#recapBtn","#csvBtn"].forEach(s => $(s).disabled = !any); } function esc(s){ return String(s).replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); } $("#list").addEventListener("click", (e) => { const el = e.target.closest(".clip"); if (!el) return; const k = +el.dataset.k, c = S.clips[k], act = e.target.closest("[data-act]") && e.target.closest("[data-act]").dataset.act; if (act === "keep") { c.keep = e.target.checked; el.classList.toggle("off", !c.keep); updateTiles(); drawTimeline(); return; } if (act === "drop") { c.keep = false; renderRail(); drawTimeline(); return; } if (act === "s-") { c.start = Math.max(0, c.start - 1); c.trimmed = true; renderRail(); drawTimeline(); return; } if (act === "e+") { c.end = Math.min(S.an.duration, c.end + 1); c.trimmed = true; renderRail(); drawTimeline(); return; } if (e.target.closest(".keep")) return; playClip(k); }); /* ===================== playback ===================== */ let clipStop = null; async function playClip(k){ stopReel(); ensureAudio(); const c = S.clips[k]; S.active = k; clipStop = c.end; document.querySelectorAll(".clip").forEach(n => n.classList.toggle("active", +n.dataset.k === k)); await seek(vid, c.start); snapCam(); drawTimeline(); vid.playbackRate = S.slow ? 0.5 : 1; try { await vid.play(); } catch(e){} } function snapCam(){ const o = {ai:false, playerCam:true, snap:true}; if (vid.videoWidth) cropFor(vid, 16, 9, o); } /* iPhone: Web Audio is muted by the silent switch unless the page asks for "playback" audio. */ let silentEl = null; function iosUnlock(){ try { if (navigator.audioSession && navigator.audioSession.type !== "playback") navigator.audioSession.type = "playback"; } catch(e){} if (!("audioSession" in navigator)) { try { if (!silentEl) { silentEl = new Audio("audio/silence.mp3"); silentEl.loop = true; silentEl.setAttribute("playsinline", ""); } const p = silentEl.play(); if (p && p.catch) p.catch(()=>{}); } catch(e){} } } function wakeAudio(){ iosUnlock(); if (S.audioCtx && S.audioCtx.state !== "running") { try { const p = S.audioCtx.resume(); if (p && p.catch) p.catch(()=>{}); } catch(e){} } } ["pointerdown","touchend","click","keydown"].forEach(ev => document.addEventListener(ev, () => { if (S.audioCtx) wakeAudio(); }, {passive:true, capture:true})); document.addEventListener("visibilitychange", () => { if (!document.hidden && S.audioCtx) wakeAudio(); }); function ensureAudio(){ iosUnlock(); if (S.audioCtx) { if (S.audioCtx.state !== "running") wakeAudio(); return; } try { const AC = window.AudioContext || window.webkitAudioContext; const ctx = new AC(); const src = ctx.createMediaElementSource(vid), gain = ctx.createGain(); src.connect(gain); gain.connect(ctx.destination); S.audioCtx = ctx; S.recDest = ctx.createMediaStreamDestination(); gain.connect(S.recDest); } catch(e) { console.warn("audio graph", e); } } function loop(){ if (!vid.paused || S.reel) drawStage(); if (!vid.paused) { if (clipStop != null && !S.reel && vid.currentTime >= clipStop) { vid.pause(); clipStop = null; } $("#timeTxt").textContent = fmt(vid.currentTime) + " / " + fmt(vid.duration); if ((loop.n = (loop.n||0)+1) % 3 === 0) { drawTimeline(); updateCoachCard(); updateLiveHud(); } } requestAnimationFrame(loop); } vid.addEventListener("play", () => $("#playIc").innerHTML = ''); vid.addEventListener("pause", () => { $("#playIc").innerHTML = ''; drawStage(); drawTimeline(); }); vid.addEventListener("seeked", () => { drawStage(); drawTimeline(); updateCoachCard(); updateLiveHud(); $("#timeTxt").textContent = fmt(vid.currentTime) + " / " + fmt(vid.duration); }); vid.addEventListener("loadeddata", () => { drawStage(); drawTimeline(); $("#timeTxt").textContent = fmt(vid.currentTime) + " / " + fmt(vid.duration); }); $("#playBtn").onclick = async () => { if (S.reel) { stopReel(); return; } ensureAudio(); clipStop = null; vid.playbackRate = S.slow ? 0.5 : 1; if (vid.paused) { try { await vid.play(); } catch(e){} } else vid.pause(); }; $("#prevBtn").onclick = () => jump(-1); $("#nextBtn").onclick = () => jump(1); function jump(dir){ if (!S.clips.length) return; const t = vid.currentTime; let k = dir > 0 ? S.clips.findIndex(c => c.start > t + 0.5) : -1; if (dir < 0) { for (let i=S.clips.length-1;i>=0;i--) if (S.clips[i].start < t - 1.5) { k = i; break; } } if (k < 0) k = dir > 0 ? 0 : S.clips.length-1; playClip(k); } function bindToggle(id, key, after){ const b = $(id); b.onclick = () => { S[key] = !S[key]; b.setAttribute("aria-pressed", S[key]); after && after(); drawStage(); }; } bindToggle("#camToggle", "playerCam", () => { snapCam(); if (S.playerCam && !S.track) toast("Player Cam follows the action. Follow a player to lock onto them."); }); bindToggle("#aiToggle", "aiView"); bindToggle("#slowToggle", "slow", () => { vid.playbackRate = S.slow ? 0.5 : 1; }); $("#fsBtn").onclick = () => { const st = $("#stage"); try { (st.requestFullscreen || st.webkitRequestFullscreen).call(st).catch(()=>toast("Full screen isn't available here.")); } catch(e){ toast("Full screen isn't available here."); } }; // timeline: click a marker to watch that moment, or drag to scrub (function(){ const c = $("#tl"); let down = false, moved = false; const tOf = (e) => { const r = c.getBoundingClientRect(), dur = (S.an && S.an.duration) || vid.duration; if (!dur) return null; return clamp((e.clientX - r.left - TLG)/(r.width - TLG - TLR), 0, 1)*dur; }; const hitOf = (e) => { const r = c.getBoundingClientRect(), d = c.width / r.width, X = (e.clientX - r.left)*d, Y = (e.clientY - r.top)*d; let best = null, bd = 13*d; for (const h of S.tlHits || []) { const dd = Math.hypot(h.x - X, (h.y - Y)*0.6); if (dd < bd) { bd = dd; best = h; } } return best; }; const go = (e) => { const t = tOf(e); if (t == null) return; stopReel(); clipStop = null; vid.currentTime = t; S.active = S.clips.findIndex(k => t >= k.start && t <= k.end); }; c.addEventListener("pointerdown", e => { down = true; moved = false; c.setPointerCapture(e.pointerId); c._hit = hitOf(e); if (!c._hit) go(e); }); c.addEventListener("pointermove", e => { if (down) { moved = true; if (!c._hit) go(e); } else c.style.cursor = hitOf(e) ? "pointer" : "col-resize"; }); c.addEventListener("pointerup", () => { down = false; const h = c._hit; c._hit = null; if (h && !moved) { const m = h.m; if (m.kind === "shot") { const q = m.shot; playRange(Math.max(0, (q.relT || q.t) - 1.8), (q.rimT || q.end) + 1.9); } else playMoment(m); } renderRail(); }); })(); /* ===================== reel ===================== */ function reelInfo(){ const f = S.follow, sp = SPORTS[S.sport]; const who = f && (f.name || f.number) ? [f.name, f.number ? "#" + f.number : ""].filter(Boolean).join(" · ") : "Game highlights"; const team = f && f.team ? f.team : (S.source.sample ? "Suns" : sp.label); return {who, team, sport:sp.label}; } function drawTitleCard(ctx, W, H, u, end){ const px = Math.min(W, H*16/9)/1000, info = reelInfo(); const g = ctx.createLinearGradient(0,0,W,H); g.addColorStop(0, "#0B0F18"); g.addColorStop(1, "#1a0e08"); ctx.fillStyle = g; ctx.fillRect(0,0,W,H); const a = clamp(u*3, 0, 1), out = clamp((1-u)*4, 0, 1), al = Math.min(a, out); ctx.globalAlpha = al; ctx.fillStyle = "#FF5A1F"; ctx.fillRect(W*0.08, H*0.5 - 3*px, (W*0.22)*clamp(u*2.2,0,1), 6*px); ctx.fillStyle = "#EDF1F7"; ctx.textAlign = "left"; ctx.textBaseline = "alphabetic"; const big = W < H ? 96 : 120; if (!end) { ctx.font = `700 ${Math.round(big*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillText(info.who.toUpperCase(), W*0.08, H*0.5 - 24*px); ctx.font = `600 ${Math.round(30*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillStyle = "#8C96AA"; const kept = S.clips.filter(c => c.keep).length; ctx.fillText(`${info.team.toUpperCase()} · ${info.sport.toUpperCase()} · ${kept} PLAYS`, W*0.08, H*0.5 + 48*px); } else { ctx.font = `700 ${Math.round(80*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillText("CLUTCH", W*0.08, H*0.5 - 24*px); ctx.font = `600 ${Math.round(28*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillStyle = "#8C96AA"; ctx.fillText("MADE WITH CLUTCH HIGHLIGHT STUDIO", W*0.08, H*0.5 + 44*px); } ctx.globalAlpha = 1; } function drawReelFrame(ctx, W, H, R, recording){ if (R.phase === "title" || R.phase === "end") { drawTitleCard(ctx, W, H, (performance.now() - R.t0)/R.len, R.phase === "end"); return; } drawFrameTo(ctx, W, H, vid, {ai:false, reel:true, playerCam:S.playerCam || R.vertical, vertical:R.vertical, camState:R.cam}); const c = R.clips[R.i]; if (!c) return; const px = Math.min(W, H*16/9)/1000; const vertical = W < H; // lower third const text = (c.ai && c.ai.caption) ? c.ai.caption : c.title; const shotLab = c.shot === "made" ? " · MADE BASKET" : c.shot === "miss" ? " · SHOT ATTEMPT" : ""; const lt = (vid.currentTime - c.start); const a = clamp(lt*2.5, 0, 1); ctx.globalAlpha = a; const x = vertical ? W*0.06 : 34*px, y = vertical ? H*0.80 : H - 96*px; ctx.font = `600 ${Math.round((vertical ? 40 : 30)*px)}px Barlow Condensed, Arial Narrow, sans-serif`; const maxW = vertical ? W*0.88 : W*0.62; const lines = wrap(ctx, text.toUpperCase(), maxW - 30*px); const lh = (vertical ? 44 : 33)*px, boxH = 34*px + lines.length*lh; ctx.fillStyle = "rgba(10,13,19,.84)"; roundRect(ctx, x, y - boxH + 26*px, maxW, boxH, 8*px); ctx.fill(); ctx.fillStyle = "#FF5A1F"; ctx.fillRect(x, y - boxH + 26*px, 6*px, boxH); ctx.fillStyle = "#8C96AA"; ctx.font = `600 ${Math.round((vertical ? 22 : 17)*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillText(`PLAY ${R.i+1} OF ${R.clips.length}${shotLab}${c.mine && S.follow && S.follow.number ? " · #" + S.follow.number : ""}`, x + 20*px, y - boxH + 50*px); ctx.fillStyle = "#EDF1F7"; ctx.font = `600 ${Math.round((vertical ? 40 : 30)*px)}px Barlow Condensed, Arial Narrow, sans-serif`; lines.forEach((l, j) => ctx.fillText(l, x + 20*px, y - boxH + 52*px + (j+1)*lh)); ctx.globalAlpha = 1; // fades const toEnd = c.end - vid.currentTime; const fade = Math.max(clamp(1 - lt/0.35, 0, 1), clamp(1 - toEnd/0.35, 0, 1)); if (fade > 0) { ctx.fillStyle = `rgba(5,7,11,${fade})`; ctx.fillRect(0,0,W,H); } // brand bug ctx.fillStyle = "rgba(237,241,247,.7)"; ctx.font = `700 ${Math.round(18*px)}px Barlow Condensed, sans-serif`; ctx.textAlign = "right"; ctx.fillText("CLUTCH", W - 24*px, 36*px); ctx.textAlign = "left"; } function wrap(ctx, text, maxW){ const words = text.split(/\s+/), lines = []; let cur = ""; for (const w of words){ const t = cur ? cur + " " + w : w; if (ctx.measureText(t).width > maxW && cur){ lines.push(cur); cur = w; } else cur = t; } if (cur) lines.push(cur); return lines.slice(0,3); } async function runReel({record=false, vertical=false}={}){ const clips = S.clips.filter(c => c.keep).slice().sort((a,b) => a.start - b.start); if (!clips.length) return null; stopReel(); ensureAudio(); clipStop = null; const token = {}; const R = {token, clips, i:-1, phase:"title", t0:performance.now(), len:2200, vertical, cam:{x:.5,y:.5}}; S.reel = R; setHud(); let rec = null, chunks = [], canvas = null, ctx = null, rafId = 0, mime = ""; if (record) { canvas = document.createElement("canvas"); if (vertical) { canvas.width = 720; canvas.height = 1280; } else { canvas.width = 1280; canvas.height = 720; } ctx = canvas.getContext("2d"); const stream = canvas.captureStream(30); if (S.recDest) S.recDest.stream.getAudioTracks().forEach(t => stream.addTrack(t)); const types = ["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm"]; mime = types.find(t => window.MediaRecorder && MediaRecorder.isTypeSupported(t)) || ""; if (!window.MediaRecorder) { toast("This browser can't record video. Try Chrome or Safari on a laptop."); S.reel = null; return null; } rec = new MediaRecorder(stream, mime ? {mimeType:mime, videoBitsPerSecond:5e6} : undefined); rec.ondataavailable = e => e.data.size && chunks.push(e.data); rec.start(500); const paint = () => { if (S.reel !== R) return; drawReelFrame(ctx, canvas.width, canvas.height, R, true); rafId = requestAnimationFrame(paint); }; paint(); R.progress = $("#scan"); $("#scanTitle").textContent = vertical ? "Recording 9:16 reel" : "Recording reel"; } const total = clips.reduce((s,c) => s + c.end - c.start, 0) + 3.7; const startedAt = performance.now(); const showProg = () => { if (!record) return; const el = (performance.now() - startedAt)/1000; $("#scan").hidden = false; $("#scan").classList.add("rec"); $("#steps").style.display = "none"; $("#scanBar").style.width = clamp(el/total*100, 0, 100) + "%"; $("#scanFrames").textContent = fmt(el) + " / " + fmt(total); $("#scanPeople").textContent = "Keep this tab open"; $("#scanEta").textContent = ""; }; const wait = ms => new Promise(r => { const t0 = performance.now(); const f = () => { if (S.reel !== R) return r(); showProg(); if (performance.now() - t0 >= ms) r(); else requestAnimationFrame(f); }; f(); }); await wait(R.len); for (let i=0;i { const f = () => { if (S.reel !== R || vid.currentTime >= c.end || vid.ended) return r(); showProg(); requestAnimationFrame(f); }; f(); }); vid.pause(); } if (S.reel === R) { R.phase = "end"; R.t0 = performance.now(); R.len = 1500; await wait(1500); } const finished = S.reel === R; cancelAnimationFrame(rafId); let blob = null; if (rec) { await new Promise(r => { rec.onstop = r; rec.stop(); }); blob = new Blob(chunks, {type: mime || "video/webm"}); $("#steps").style.display = ""; $("#scan").hidden = true; $("#scan").classList.remove("rec"); $("#scanTitle").textContent = "Analyzing game"; } if (S.reel === R) S.reel = null; setHud(); drawStage(); return finished ? {blob, mime} : null; } function stopReel(){ if (S.reel) { S.reel = null; vid.pause(); $("#steps").style.display = ""; $("#scan").classList.remove("rec"); $("#scan").hidden = !S.busy; setHud(); } } $("#reelBtn").onclick = () => { runReel(); }; $("#mReel").onclick = () => $("#reelBtn").click(); async function doExport(vertical){ if (S.busy) return; toast("Recording in real time. Keep this tab open."); const r = await runReel({record:true, vertical}); if (!r || !r.blob || !r.blob.size) { toast("Recording stopped."); return; } const ext = /mp4/.test(r.mime) ? "mp4" : "webm"; S.exported = {blob:r.blob, name:`clutch-${vertical ? "vertical-" : ""}reel.${ext}`}; const url = URL.createObjectURL(r.blob); $("#emVid").src = url; $("#emSub").textContent = `${(r.blob.size/1e6).toFixed(1)} MB · ${ext.toUpperCase()} · ${vertical ? "1080×1920 style 9:16" : "1280×720"}`; $("#exportModal").hidden = false; } $("#exportBtn").onclick = () => doExport(false); $("#mExport").onclick = () => $("#reportDl").click(); $("#vertBtn").onclick = () => doExport(true); $("#emClose").onclick = () => { $("#exportModal").hidden = true; $("#emVid").pause(); }; $("#emSave").onclick = async () => { const dl = await cap("downloads"); if (!dl) { toast("Saving isn't available in this view. Open the artifact in claude.ai to save."); return; } try { await dl.save({filename:S.exported.name, data:S.exported.blob}); toast("Saved."); } catch(e){ toast(e && e.code === "declined" ? "Save cancelled." : "Couldn't save: " + ((e && e.message) || "unavailable")); } }; $("#csvBtn").onclick = async () => { const rows = [["play","start","end","title","shot","caption","score","kept","tags"]].concat(S.clips.map((c,k) => [k+1, fmt(c.start), fmt(c.end), c.title, c.shot || "", (c.ai && c.ai.caption) || "", c.pct, c.keep ? "yes" : "no", c.tags.map(t => t[0]).join("; ")])); const csv = rows.map(r => r.map(v => `"${String(v).replace(/"/g,'""')}"`).join(",")).join("\n"); const dl = await cap("downloads"); if (!dl) { try { await navigator.clipboard.writeText(csv); toast("Saving isn't available here, so the clip list was copied instead."); } catch(e){ toast("Saving isn't available in this view."); } return; } try { await dl.save({filename:"clutch-clips.csv", data:csv}); } catch(e){ if (e && e.code !== "declined") toast("Couldn't save the list."); } }; /* ===================== Claude ===================== */ async function grabStills(c){ if (scanVid.currentSrc.indexOf(S.source.url) < 0 && scanVid.src !== S.source.url) scanVid.src = S.source.url; await loaded(scanVid); const out = [], cv = document.createElement("canvas"); cv.width = 768; cv.height = Math.round(768*scanVid.videoHeight/scanVid.videoWidth); const x = cv.getContext("2d"); for (const t of [c.peak - 2.4, c.peak - 0.6, c.peak + 1.0]) { await seek(scanVid, clamp(t, c.start, c.end)); x.drawImage(scanVid, 0, 0, cv.width, cv.height); const tk = trackAt(scanVid.currentTime); if (tk && tk.ok) { x.strokeStyle = "#2EE6C5"; x.lineWidth = 3; roundRect(x, (tk.cx-tk.w/2)*cv.width - 4, (tk.cy-tk.h/2)*cv.height - 4, tk.w*cv.width + 8, tk.h*cv.height + 8, 6); x.stroke(); } out.push(await new Promise(r => cv.toBlob(r, "image/jpeg", 0.8))); } return out; } function parseJSON(t){ try { const m = String(t).match(/\{[\s\S]*\}/); return m ? JSON.parse(m[0]) : null; } catch(e){ return null; } } $("#claudeBtn").onclick = async () => { const sample = await cap("sample"); if (!sample) { toast("Claude captions work when this page is opened in claude.ai."); return; } let images = true; try { const l = await sample.limits(); images = !!(l && l.images); } catch(e){} if (!images) { toast("Image captions aren't enabled for this page yet."); return; } const kept = S.clips.filter(c => c.keep); kept.forEach(c => c.aiBusy = true); renderRail(); const sp = SPORTS[S.sport], f = S.follow; for (const c of kept) { try { const imgs = await grabStills(c); const who = f ? `The family is following ${f.name ? f.name + ", " : ""}the player ${f.number ? "wearing #" + f.number : "marked"}${f.team ? " on the " + f.team : ""}. A teal box marks where our tracker thinks that player is; the tracker can be wrong.` : "No specific player is being followed."; const prompt = `You caption youth ${sp.label.toLowerCase()} highlight clips for parents. Three frames from one clip, in time order (about 2.4s before the peak, at the peak, and 1s after). ${who} ${c.shot ? "Our rim detector says this clip contains a " + (c.shot === "made" ? "made basket" : "missed shot") + "; correct it if the frames clearly show otherwise. " : ""}Describe only what is visible. Do not invent scores, names or outcomes you cannot see; if unsure, say "attempt" rather than "scores". Reply with JSON only, no prose: {"title":"3-5 word headline, upper case style","caption":"one sentence, max 16 words, for an on-screen lower third","action":"score|shot|pass|save|block|steal|tackle|serve|rally|run|other","followed":true|false|null,"numbers_seen":[jersey numbers you can read],"confidence":0-1} "followed" = whether the followed player is visibly involved in the main action (null if no player is followed).`; const r = await sample(prompt, {images: imgs, modelTier:"default"}); const j = parseJSON(r && r.text); if (j) { c.ai = {title:j.title, caption:j.caption, action:j.action, followed: f ? (j.followed === true ? true : j.followed === false ? false : null) : null, nums:j.numbers_seen || [], conf:j.confidence}; if (j.title) c.title = j.title; } } catch(e) { c.aiBusy = false; renderRail(); if (e && e.code === "rate_limited") { toast("Claude is busy. Try again in a minute."); break; } if (e && (e.code === "not_granted" || e.code === "declined")) { toast("Captions need your OK to ask Claude."); break; } toast("Couldn't caption a clip."); } c.aiBusy = false; renderRail(); } kept.forEach(c => c.aiBusy = false); renderRail(); }; // Claude reads the jersey number on crops along the track and removes stretches where it's someone else $("#verifyBtn").onclick = async () => { const f = S.follow, tr = S.track; if (!f || !tr) return; if (!f.number) { toast("Add the jersey number first: tap Follow again on your player."); return; } const sample = await cap("sample"); if (!sample) { toast("Tracking checks work when this page is opened in claude.ai."); return; } let images = true; try { const l = await sample.limits(); images = !!(l && l.images); } catch(e){} if (!images) { toast("Image checks aren't enabled for this page yet."); return; } const pts = []; let lastT = -9; for (const q of tr) if (q.ok && q.t - lastT >= 2.5) { pts.push(q); lastT = q.t; } const picks = pts.length > 24 ? pts.filter((_, i) => i % Math.ceil(pts.length/24) === 0) : pts; if (!picks.length) { toast("Nothing to check yet."); return; } const btn = $("#verifyBtn"); btn.disabled = true; if (scanVid.src !== S.source.url) scanVid.src = S.source.url; await loaded(scanVid); const vw = scanVid.videoWidth, vh = scanVid.videoHeight, cv = document.createElement("canvas"); cv.width = 160; cv.height = 240; const x = cv.getContext("2d"); const res = []; let wrong = 0, ok = 0, unread = 0; try { for (let b = 0; b < picks.length; b += 6) { const batch = picks.slice(b, b + 6), imgs = []; $("#verifyTxt").textContent = `Checking ${Math.min(b + 6, picks.length)} of ${picks.length}…`; for (const q of batch) { await seek(scanVid, q.t); const bw = q.w*vw*1.5, bh = q.h*vh*1.25, sx = q.cx*vw - bw/2, sy = q.cy*vh - bh/2; x.fillStyle = "#000"; x.fillRect(0, 0, 160, 240); x.drawImage(scanVid, sx, sy, bw, bh, 0, 0, 160, 240); imgs.push(await new Promise(r => cv.toBlob(r, "image/jpeg", 0.85))); } const prompt = `You will see ${batch.length} cropped images of youth ${SPORTS[S.sport].label.toLowerCase()} players, in order. For each image, read the jersey number of the main player in the center of the crop. Use null when no number is clearly readable; do not guess. Reply with JSON only: {"numbers":[one entry per image, in order]}`; const r = await sample(prompt, {images: imgs, modelTier:"default"}); const j = parseJSON(r && r.text), nums = (j && Array.isArray(j.numbers)) ? j.numbers : []; batch.forEach((q, i) => { const n = nums[i] == null ? null : String(nums[i]).replace(/[^0-9]/g, ""); if (!n) { unread++; return; } if (n === f.number) ok++; else { wrong++; for (const t2 of S.track) if (t2.ok && Math.abs(t2.t - q.t) <= 1.3) t2.ok = false; } }); } S.verify = {checked: picks.length, ok, wrong, unread}; rescore(false); drawStage(); toast(`Claude checked ${picks.length} spots: ${ok} were #${f.number}, ${wrong} were someone else (removed), ${unread} unreadable.`); } catch(e) { if (e && e.code === "rate_limited") toast("Claude is busy. Try again in a minute."); else if (e && (e.code === "not_granted" || e.code === "declined")) toast("The check needs your OK to ask Claude."); else toast("The check stopped early."); } finally { btn.disabled = false; $("#verifyTxt").textContent = S.verify ? `Checked: ${S.verify.ok} of ${S.verify.checked} confirmed` : "Check the tracking with Claude"; } }; $("#recapBtn").onclick = async () => { const sample = await cap("sample"); const kept = S.clips.filter(c => c.keep); const lines = kept.map((c,k) => `${k+1}. ${fmt(c.start)} ${c.ai && c.ai.caption ? c.ai.caption : c.title}${c.mine ? " (our player involved)" : ""}`).join("\n"); const info = reelInfo(); if (!sample) { $("#tmText").value = `${info.who} · ${info.team}\n\n${lines}`; $("#tmSub").textContent = "Claude isn't available in this view, so here is the play list. Edit it, then copy."; $("#textModal").hidden = false; return; } $("#tmText").value = "Writing…"; $("#tmSub").textContent = "Written by Claude from your clips. Edit it, then copy."; $("#textModal").hidden = false; try { const r = await sample(`Write a warm, short recap (3 sentences, under 70 words) of a youth ${SPORTS[S.sport].label.toLowerCase()} game for a family group chat. Player: ${info.who}. Team: ${info.team}. Only use these highlight notes; do not invent scores or results:\n${lines}\nPlain text only.`, {modelTier:"quick", onText: ({text}) => { $("#tmText").value = text; }}); $("#tmText").value = r.text; } catch(e){ $("#tmText").value = `${info.who} · ${info.team}\n\n${lines}`; $("#tmSub").textContent = "Claude couldn't write this one, so here is the play list."; } }; $("#tmClose").onclick = () => $("#textModal").hidden = true; $("#tmCopy").onclick = async () => { try { await navigator.clipboard.writeText($("#tmText").value); toast("Copied."); } catch(e){ toast("Copy isn't available here. Select the text and copy it."); } }; /* ===================== follow a player ===================== */ $("#followBtn").onclick = async () => { if (S.picking) return endPick(); if (!vid.videoWidth) return; vid.pause(); stopReel(); S.picking = true; S.pickMode = "player"; $("#stage").classList.add("picking"); $("#pickbar").hidden = false; $("#pickMsg").textContent = "Tap the player you want the report for"; $("#hoopCtl").hidden = true; $("#courtCtl").hidden = true; // detections for this frame let persons = null; if (S.engine === "ready") { const lb = letterbox(vid); const img = c640.getImageData(0,0,640,640); const pix = new Uint8ClampedArray(img.data); const det = await detect(img); persons = det.persons.map(d => { const box = [d[0]/lb.w, d[1]/lb.h, d[2]/lb.w, d[3]/lb.h]; return [...box, d[4], signature(box, lb, pix)]; }).filter(p => p[3] > 0.05); } else { const f = frameAt(vid.currentTime); persons = f ? f.p : []; } S.pickDet = persons; S.pickHover = -1; drawStage(); if (!persons.length) { toast("No players found in this frame. Move to a moment where your player is clearly visible."); endPick(); } }; function endPick(){ S.picking = false; S.pickMode = null; S.hoopDraft = null; S.courtDraft = null; S.pickDet = null; $("#courtCtl").hidden = true; $("#stage").classList.remove("picking"); $("#pickbar").hidden = true; drawStage(); } $("#pickCancel").onclick = endPick; function pickAt(e){ const r = view.getBoundingClientRect(), d = view.width / r.width; const X = (e.clientX - r.left)*d, Y = (e.clientY - r.top)*d, W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight; const s = Math.min(W/vw, H/vh), dx = (W-vw*s)/2, dy = (H-vh*s)/2; const nx = (X - dx)/(vw*s), ny = (Y - dy)/(vh*s); let best = -1, bd = 1e9; (S.pickDet||[]).forEach((p,k) => { const inside = Math.abs(nx-p[0]) < p[2]/2 + 0.01 && Math.abs(ny-p[1]) < p[3]/2 + 0.01; const dd = Math.hypot(nx-p[0], ny-p[1]) - (inside ? 1 : 0); if (dd < bd){ bd = dd; best = k; } }); return bd < 0.12 ? best : -1; } view.addEventListener("pointermove", e => { if (!S.picking || S.pickMode !== "player") return; const k = pickAt(e); if (k !== S.pickHover){ S.pickHover = k; drawStage(); } }); view.addEventListener("click", e => { if (!S.picking) { if (!S.reel) $("#playBtn").click(); return; } if (S.pickMode === "court") { const r = view.getBoundingClientRect(), d = view.width / r.width, W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight; const sc = Math.min(W/vw, H/vh), dx = (W-vw*sc)/2, dy = (H-vh*sc)/2; const nx = ((e.clientX - r.left)*d - dx)/(vw*sc), ny = ((e.clientY - r.top)*d - dy)/(vh*sc); if (nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1) courtTap(nx, ny); return; } if (S.pickMode === "hoop") { const r = view.getBoundingClientRect(), d = view.width / r.width, W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight; const s = Math.min(W/vw, H/vh), dx = (W-vw*s)/2, dy = (H-vh*s)/2; const nx = ((e.clientX - r.left)*d - dx)/(vw*s), ny = ((e.clientY - r.top)*d - dy)/(vh*s); if (nx < 0 || nx > 1 || ny < 0 || ny > 1) return; S.hoopDraft = {t: vid.currentTime, cx: nx, cy: ny, w: (+$("#rimSize").value)/100}; $("#pickMsg").textContent = "Match the ring to the rim"; $("#hoopCtl").hidden = false; drawStage(); return; } const k = pickAt(e); if (k < 0) return; const p = S.pickDet[k]; S.pendingAnchor = {t: vid.currentTime, box: p.slice(0,4), sig: p[5]}; endPick(); const f = S.follow || {}; $("#fmNum").value = f.number || ""; $("#fmName").value = f.name || ""; $("#fmTeam").value = f.team || (S.source.sample ? "Suns" : ""); $("#fmTitle").textContent = S.follow ? "Same player, another moment" : "Pick this player"; $("#followModal").hidden = false; setTimeout(() => $("#fmNum").focus(), 50); }); $("#fmCancel").onclick = () => { $("#followModal").hidden = true; S.pendingAnchor = null; }; $("#fmOk").onclick = () => { const num = $("#fmNum").value.replace(/[^0-9]/g, "").slice(0,3), name = $("#fmName").value.trim(), team = $("#fmTeam").value.trim(); const sameNum = S.follow && S.follow.number === num; if (!S.follow || !sameNum) S.follow = {anchors:[], number:num, name, team}; S.follow.name = name; S.follow.team = team; S.follow.anchors.push(S.pendingAnchor); S.pendingAnchor = null; $("#followModal").hidden = true; applyFollow(); }; function applyFollow(quiet){ $("#followTxt").textContent = S.follow ? "Player " + (S.follow.number ? "#" + S.follow.number : "picked") : "Pick the player"; $("#followBtn").classList.toggle("on", !!S.follow); $("#verifyBtn").hidden = !S.follow; if (S.an) { S.track = buildTrack(); attributeShots(); rescore(false); renderReport(); if (!quiet) toast(S.track ? "Tracking updated. The teal band shows when they're on screen." : "Press Build report to track this player."); } setHud(); drawStage(); } /* ===================== hoop marking ===================== */ $("#hoopBtn").onclick = () => { if (S.picking) { endPick(); return; } if (!vid.videoWidth) return; vid.pause(); stopReel(); S.picking = true; S.pickMode = "hoop"; S.hoopDraft = null; $("#stage").classList.add("picking"); $("#pickbar").hidden = false; $("#hoopCtl").hidden = true; $("#courtCtl").hidden = true; $("#pickMsg").textContent = S.hoops.length >= 2 ? "Tap a rim to replace the older hoop" : "Pause where the rim is clear, then tap its middle"; drawStage(); }; $("#rimSize").addEventListener("input", () => { if (S.hoopDraft) { S.hoopDraft.w = (+$("#rimSize").value)/100; drawStage(); } }); $("#hoopSave").onclick = () => { const hd = S.hoopDraft; if (!hd) return; S.hoops.push({t: hd.t, cx: hd.cx, cy: hd.cy, w: hd.w}); if (S.hoops.length > 2) S.hoops.shift(); endPick(); updateHoopBtn(); if (S.an) runShots(); else toast("Hoop saved. Press Build report when the setup is done."); }; function updateHoopBtn(){ $("#hoopTxt").textContent = S.hoops.length ? (S.hoops.length === 1 ? "Hoop marked" : "2 hoops marked") : "Mark the hoop"; $("#hoopBtn").classList.toggle("on", S.hoops.length > 0); $("#courtTxt").textContent = S.calib ? "Court marked" : "Mark the court"; $("#courtBtn").classList.toggle("on", !!S.calib); if (S.calib) $("#courtBtn small").textContent = COURTS[S.calib.std].label; } async function runShots(){ if (S.busy || !S.hoops.length) return; S.busy = true; stopReel(); vid.pause(); const scan = $("#scan"); scan.hidden = false; document.querySelectorAll("#steps li").forEach(li => { li.classList.remove("on","done"); li.style.display = li.dataset.s === "shots" ? "" : "none"; }); const li = document.querySelector('#steps li[data-s="shots"]'); li.classList.add("on"); $("#scanTitle").textContent = "Counting shots"; $("#scanFrames").textContent = ""; $("#scanPeople").textContent = "Plays at normal speed"; $("#scanEta").textContent = ""; const bar = $("#scanBar"); bar.style.width = "2%"; setHud(); try { const t0 = performance.now(); await analyzeShots(p => { bar.style.width = (2 + p*96) + "%"; $("#scanFrames").textContent = Math.round(p*100) + "%"; }); li.classList.remove("on"); li.classList.add("done"); attributeShots(); if (S.an) rescore(false); else { renderRail(); drawTimeline(); } updateTiles(); renderReport(); const made = S.shots.filter(x => x.made).length; toast(S.shots.length ? `${S.shots.length} shots, ${made} made (${Math.round((performance.now()-t0)/1000)}s)` : "No shots seen. Make sure the ring sits on the rim."); } catch(e) { console.error(e); toast("Shot counting stopped: " + (e.message || e)); } finally { S.busy = false; document.querySelectorAll("#steps li").forEach(li2 => li2.style.display = ""); setTimeout(() => { scan.hidden = true; $("#scanTitle").textContent = "Analyzing game"; }, 500); setHud(); drawStage(); } } /* ===================== source loading ===================== */ async function loadSource(src){ stopReel(); S.source = src; S.an = null; S.track = null; S.clips = []; S.score = null; S.thumbCache = {}; S.active = -1; if (!src.sample) S.follow = null; S.hoops = []; S.shots = null; S.calib = null; S.H = null; S.Hinv = null; S.hoopPoses = null; S.form = null; S.plan = null; updateHoopBtn && updateHoopBtn(); $("#srcName").textContent = src.name; $("#srcSub").textContent = src.sub; $("#sampleBtn").hidden = !!src.sample; vid.src = src.url; await loaded(vid); $("#srcSub").textContent = src.sub.replace("{dur}", fmt(vid.duration)); applyFollow(); renderRail(); drawTimeline(); renderReport(); } let sampleBlobUrl = null; async function loadSample(){ if (!sampleBlobUrl) { $("#srcSub").textContent = "Loading sample workout…"; try { const r = await fetch("media/workout.mp4"); if (!r.ok) throw 0; sampleBlobUrl = URL.createObjectURL(await r.blob()); } catch(e) { sampleBlobUrl = "media/workout.mp4"; } } await loadSource({name:"Sample workout · #8 spot shooting", sub:"Synthetic practice footage · {dur} · free to use", url:sampleBlobUrl, sample:true}); try { const j = await (await fetch("media/workout_analysis.json")).json(); S.an = j.an; S.follow = j.follow; S.lastAnalyzeSec = j.seconds; S.hoops = j.hoops || []; S.shots = j.shots || null; S.hoopPoses = j.hoopPoses || null; S.calib = j.calib || null; buildCalib(); updateHoopBtn(); S.track = buildTrack(); applyFollow(true); attributeShots(); rescore(true); S.clips.forEach(c => { const t = j.thumbs && j.thumbs[c.id]; if (t) { c.thumb = t; S.thumbCache[c.id] = t; } }); renderRail(); makeThumbs(); renderReport(); renderHow(); } catch(e) { console.warn("no precomputed analysis", e); renderReport(); } drawStage(); } $("#uploadBtn").onclick = () => $("#fileIn").click(); $("#sampleBtn").onclick = () => loadSample(); $("#fileIn").onchange = e => { const f = e.target.files[0]; if (f) useFile(f); e.target.value = ""; }; async function useFile(f){ if (!/^video\//.test(f.type) && !/\.(mp4|mov|m4v|webm)$/i.test(f.name)) { toast("That file isn't a video. Use MP4, MOV or WebM."); return; } const url = URL.createObjectURL(f); await loadSource({name:f.name, sub:`Your video · {dur} · ${(f.size/1e6).toFixed(0)} MB · stays on this device`, url, sample:false, file:f}); $("#analyzeTxt").textContent = "Build report"; toast("Now mark the hoop, the court and the player, then press Build report."); } const stage = $("#stage"); ["dragenter","dragover"].forEach(ev => stage.addEventListener(ev, e => { e.preventDefault(); stage.classList.add("dragover"); })); ["dragleave","drop"].forEach(ev => stage.addEventListener(ev, e => { e.preventDefault(); stage.classList.remove("dragover"); })); stage.addEventListener("drop", e => { const f = e.dataTransfer.files[0]; if (f) useFile(f); }); $("#analyzeBtn").onclick = () => analyze(); /* ===================== sport + size ===================== */ S.sport = "basketball"; document.querySelectorAll("[data-size]").forEach(b => b.onclick = () => { S.size = b.dataset.size; document.querySelectorAll("[data-size]").forEach(c => c.setAttribute("aria-pressed", c === b)); rescore(false); }); $("#mineOnly").onclick = () => { if (!S.track) { toast("Follow a player first."); return; } S.mineFirst = !S.mineFirst; $("#mineOnly").setAttribute("aria-pressed", S.mineFirst); rescore(false); }; function setHud(){ const h = []; h.push(`${esc(SPORTS[S.sport].label)}`); if (S.busy) h.push(`Analyzing`); if (S.reel) h.push(`${S.reel.vertical ? "9:16 reel" : "Highlight reel"}`); if (S.follow) h.push(`Following ${S.follow.number ? "#" + esc(S.follow.number) : "player"}`); if (S.playerCam) h.push(`Player Cam`); $("#hud").innerHTML = h.join(""); } /* ===================== court marking ===================== */ const courtSel = $("#courtStd"); Object.entries(COURTS).forEach(([k, v]) => { const o = document.createElement("option"); o.value = k; o.textContent = v.label; courtSel.appendChild(o); }); const COURT_STEPS = ["Tap 1: a baseline corner of the paint", "Tap 2: the other baseline corner", "Tap 3: the free-throw line corner on the same side as 2", "Tap 4: the last free-throw line corner"]; $("#courtBtn").onclick = () => { if (S.picking) { endPick(); return; } if (!vid.videoWidth) return; vid.pause(); stopReel(); S.picking = true; S.pickMode = "court"; S.courtDraft = {t: vid.currentTime, pts: []}; courtSel.value = (S.calib && S.calib.std) || (S.source.sample ? "fiba" : "hs"); $("#stage").classList.add("picking"); $("#pickbar").hidden = false; $("#hoopCtl").hidden = true; $("#courtCtl").hidden = false; $("#courtSave").disabled = true; $("#pickMsg").textContent = COURT_STEPS[0]; drawStage(); }; $("#courtUndo").onclick = () => { if (!S.courtDraft) return; S.courtDraft.pts.pop(); $("#courtSave").disabled = true; $("#pickMsg").textContent = COURT_STEPS[S.courtDraft.pts.length]; drawStage(); }; $("#courtSave").onclick = () => { const d = S.courtDraft; if (!d || d.pts.length !== 4) return; S.calib = {t: d.t, pts: d.pts.slice(), std: courtSel.value, hoop: 0}; buildCalib(); if (!S.H) { toast("Those 4 taps don't make a usable shape. Try again, going around the paint in order."); S.calib = null; return; } endPick(); updateHoopBtn(); attributeShots(); renderReport(); drawStage(); toast("Court saved. Faint court lines now show on the video; check they sit on the real lines."); }; function courtTap(nx, ny){ const d = S.courtDraft; if (!d || d.pts.length >= 4) return; d.pts.push([nx, ny]); if (d.pts.length < 4) $("#pickMsg").textContent = COURT_STEPS[d.pts.length]; else { $("#pickMsg").textContent = "Pick the court type, then save"; $("#courtSave").disabled = false; } drawStage(); } // court lines in court feet, for drawing on video and charts function courtLines(){ const K = courtSpec(), L = K.lane/2, lines = []; lines.push([[-L,0],[L,0],[L,K.ft],[-L,K.ft],[-L,0]]); // paint const ftc = []; for (let a=0;a<=Math.PI;a+=Math.PI/24) ftc.push([6*Math.cos(a), K.ft + 6*Math.sin(a)]); lines.push(ftc); // free-throw circle const arc = []; const cx = K.corner3 || 0; if (K.corner3) { const yc = K.hoopY + Math.sqrt(Math.max(0, K.r3*K.r3 - K.corner3*K.corner3)); arc.push([-K.corner3,0],[-K.corner3,yc]); const a0 = Math.atan2(yc - K.hoopY, -K.corner3), a1 = Math.atan2(yc - K.hoopY, K.corner3); for (let a=a0; a>=a1; a-=0.04) arc.push([K.r3*Math.cos(a), K.hoopY + K.r3*Math.sin(a)]); arc.push([K.corner3,yc],[K.corner3,0]); } else { for (let a=Math.PI; a>=0; a-=0.04) arc.push([K.r3*Math.cos(a), K.hoopY + K.r3*Math.sin(a)]); } lines.push(arc); lines.push([[-25,0],[25,0]]); return lines; } /* ===================== tabs ===================== */ function setTab(name){ $("#tabReport").setAttribute("aria-selected", name === "report"); $("#tabClips").setAttribute("aria-selected", name === "clips"); $("#paneReport").hidden = name !== "report"; $("#paneClips").hidden = name !== "clips"; } $("#tabReport").onclick = () => setTab("report"); $("#tabClips").onclick = () => setTab("clips"); /* ===================== the report ===================== */ const pct = (m, a) => a ? Math.round(m/a*100) + "%" : "–"; const shotKey = sh => "s" + Math.round(sh.t*10); function quickRead(sh, mv){ const out = []; if (sh && sh.att) { out.push(`Shot ${sh.made} of ${sh.att} (${pct(sh.made, sh.att)})${sh.threesA ? `, ${sh.threesM} of ${sh.threesA} from three` : ""}${sh.pts ? `, ${sh.pts} points` : ""}.`); const zs = Object.entries(sh.zones).filter(([k, z]) => z.a >= 2 && k !== "back"); if (zs.length >= 2) { zs.sort((a, b) => b[1].m/b[1].a - a[1].m/a[1].a); const [bk, bz] = zs[0], [wk, wz] = zs[zs.length-1]; if (bz.m/bz.a > wz.m/wz.a) out.push(`Best spot: ${ZONES[bk].toLowerCase()} (${bz.m}/${bz.a}). Coldest: ${ZONES[wk].toLowerCase()} (${wz.m}/${wz.a}).`); } const mid = sh.zones.mid.a; if (sh.att >= 5 && mid/sh.att >= 0.4) out.push(`${Math.round(mid/sh.att*100)}% of shots were long twos. Worth a step back to the line, or a step in toward the rim.`); const miss = sh.shots.filter(s => !s.made && s.dist != null); const far = miss.filter(s => s.dist > 18).length; if (miss.length >= 2 && far/miss.length >= 0.6) out.push(`Most misses came from beyond 18 ft. Range and legs are the first thing to look at in form feedback.`); } else if (S.hoops.length && S.shots) out.push("No shots by this player yet. If that's wrong, confirm the player on the shots below."); if (mv) { const mins = mv.tracked/60; out.push(`Covered ${Math.round(mv.dist)} ft in ${mins >= 1 ? mins.toFixed(1) + " min" : Math.round(mv.tracked) + " s"} on camera, about ${Math.round(mv.dist/Math.max(mv.tracked,1)*60)} ft per minute. Top speed ${(mv.top*0.6818).toFixed(1)} mph; ${mv.sprints} sprint${mv.sprints === 1 ? "" : "s"}.`); } if (sh && sh.unsure) out.push(`${sh.unsure} shot${sh.unsure > 1 ? "s need" : " needs"} your OK: tap Yes or No in the shot list.`); return out; } function renderReport(){ const R = $("#report"); if (!R) return; if (S.shots || S.track) coachMoments(); else S.moments = null; const f = S.follow, sh = shootingStats(), mv = movementStats(); let h = ""; h += `
${f && f.number ? "#" + esc(f.number) : "?"}
${esc(f ? (f.name || (f.number ? "Player #" + f.number : "Your player")) : "All shots at the hoop")}${esc(f && f.team ? f.team + " · " : "")}${esc(S.source.name || "")}
`; const need = []; if (!S.hoops.length) need.push(["Mark the hoop", "Pause where the rim is clear, tap it, and size the ring. Needed for makes and misses."]); if (!S.calib) need.push(["Mark the court", "Tap the 4 corners of the paint. Needed for shot locations, distance and speed."]); if (!f) need.push(["Pick the player", "Tap them once. Skip this for a one-player shooting workout: every shot then counts."]); if (!S.an) need.push(["Build report", "Scans the video. About the video's length, on this device."]); if (need.length) h += `

To finish the report

    ${need.map(n => `
  • ${esc(n[0])}. ${esc(n[1])}
  • `).join("")}
`; if (sh || mv) { h += `
`; if (sh) h += `
${sh.made}/${sh.att}field goals${pct(sh.made, sh.att)}
${sh.threesM}/${sh.threesA}threes${pct(sh.threesM, sh.threesA)}
${S.calib ? sh.pts : "–"}pointsno free throws
`; if (mv) h += `
${Math.round(mv.dist)}feet run${(mv.dist/5280).toFixed(2)} mi
${(mv.top*0.6818).toFixed(1)}top mph1-second best
${mv.sprints}sprints1 s at 9+ mph
`; h += `
`; } h += scorecardHTML(); const qr = quickRead(sh, mv); if (qr.length) h += `

Quick read

    ${qr.map(x => `
  • ${esc(x)}
  • `).join("")}
`; if (S.plan) h += planHTML(S.plan); if (sh && S.calib) { h += `

Shot chart tap a shot to watch it

${["paint","mid","corner3","three"].map(k => { const z = sh.zones[k]; return ``; }).join("")}
ZoneMade%
${ZONES[k]}${z.m}/${z.a}${pct(z.m, z.a)}
`; } if (mv) { const tot = Object.values(mv.zoneT).reduce((a, b) => a + b, 0) || 1; h += `

Where they spent the time ${Math.round(mv.tracked)} s on camera

${["paint","mid","corner3","three","back"].filter(k => mv.zoneT[k] > 0).map(k => ``).join("")}
${ZONES[k]}${Math.round(mv.zoneT[k]/tot*100)}%
`; } if (S.shots && S.shots.length) { h += `

Every shot at the hoop ${S.shots.length} seen

`; S.shots.forEach((q, i) => { const loc = q.dist != null ? `${Math.round(q.dist)} ft · ${ZONES[q.zone]}` : "location needs the court"; let who = ""; if (S.follow) { const tag = S.follow.number ? "#" + esc(S.follow.number) : "player"; if (q.coach != null) who = `${q.coach ? "✓ " + tag : "Not " + tag} (you) `; else if (q.mine === true && q.sure) who = `✓ ${tag}`; else if (q.mine === false && q.sure) who = `Not ${tag} `; else who = `${tag}? `; } const fb = S.form && S.form[shotKey(q)]; h += `
${q.made ? "MADE" : "MISS"}${fmt(q.relT || q.t)} · ${esc(loc)}${who}${fb ? `
Form ${fb.rating ? fb.rating + "/5" : ""}: ${esc(fb.one_fix || fb.summary || "")}
` : ""}
`; }); h += `
`; } R.innerHTML = h || `
Upload a video to start.
`; if ($("#chart")) drawCourtCanvas($("#chart"), "shots", sh); if ($("#heat")) drawCourtCanvas($("#heat"), "heat", null, mv); renderHero(); renderMoments(); coachKey = ""; updateCoachCard(); updateLiveHud(); drawTimeline(); $("#planBtn").disabled = !(sh && sh.att) && !mv; $("#formBtn").disabled = !(sh && sh.att); $("#reportDl").disabled = !(sh || mv); $("#reportCopy").disabled = !(sh || mv); } $("#report").addEventListener("click", (e) => { const b = e.target.closest("button"); if (!b) return; const pick = (k) => S.shots[+b.dataset[k]]; if (b.dataset.play != null) { const q = pick("play"); playRange(Math.max(0, (q.relT || q.t) - 1.2), (q.rimT || q.end) + 1.6); } else if (b.dataset.yes != null) { pick("yes").coach = true; attributeShots(); renderReport(); } else if (b.dataset.no != null) { pick("no").coach = false; attributeShots(); renderReport(); } else if (b.dataset.undo != null) { pick("undo").coach = null; attributeShots(); renderReport(); } }); async function playRange(a, b){ stopReel(); ensureAudio(); clipStop = b; await seek(vid, a); vid.playbackRate = S.slow ? 0.5 : 1; try { await vid.play(); } catch(e){} } function drawCourtCanvas(cv, mode, sh, mv){ const d = Math.min(2, window.devicePixelRatio || 1), w = cv.getBoundingClientRect().width || 340, hh = w*0.66; cv.width = Math.round(w*d); cv.height = Math.round(hh*d); cv.style.height = hh + "px"; const x = cv.getContext("2d"), W = cv.width, H = cv.height, Ymax = 33; const P = (X, Y) => [(X + 25)/50*W, Y/Ymax*H]; x.fillStyle = "#0f1420"; x.fillRect(0, 0, W, H); if (mode === "heat" && mv) { const g = document.createElement("canvas"); g.width = 100; g.height = 66; const gx = g.getContext("2d"); for (const p of mv.path) { if (p.y > Ymax) continue; const [px, py] = [(p.x + 25)/50*100, p.y/Ymax*66]; const r = gx.createRadialGradient(px, py, 0, px, py, 6); r.addColorStop(0, "rgba(46,230,197,.22)"); r.addColorStop(1, "rgba(46,230,197,0)"); gx.fillStyle = r; gx.fillRect(px-6, py-6, 12, 12); } x.imageSmoothingEnabled = true; x.drawImage(g, 0, 0, W, H); } x.strokeStyle = "rgba(237,241,247,.35)"; x.lineWidth = 1.4*d; for (const L of courtLines()) { x.beginPath(); L.forEach(([X, Y], i) => { const [px, py] = P(X, Y); i ? x.lineTo(px, py) : x.moveTo(px, py); }); x.stroke(); } const K = courtSpec(), [hx, hy] = P(0, K.hoopY); x.strokeStyle = "#FF5A1F"; x.lineWidth = 2*d; x.beginPath(); x.arc(hx, hy, 0.75/50*W, 0, 7); x.stroke(); x.strokeStyle = "rgba(237,241,247,.6)"; x.beginPath(); const [b0] = P(-3, 4), [b1] = P(3, 4); x.moveTo(b0, P(0,4)[1]); x.lineTo(b1, P(0,4)[1]); x.stroke(); if (mode === "shots" && S.shots) { cv._hits = []; S.shots.forEach((q, i) => { if (!q.court || q.court[1] > Ymax) return; const [px, py] = P(q.court[0], q.court[1]), r = 5.5*d; cv._hits.push({i, px, py}); if (q.mine === false) return; const unsure = S.follow && q.mine !== true; if (unsure) { x.strokeStyle = "#8C96AA"; x.lineWidth = 1.5*d; x.beginPath(); x.arc(px, py, r, 0, 7); x.stroke(); } else if (q.made) { x.fillStyle = "#3DDC84"; x.beginPath(); x.arc(px, py, r, 0, 7); x.fill(); } else { x.strokeStyle = "#FF8A5C"; x.lineWidth = 2.2*d; x.beginPath(); x.moveTo(px - r, py - r); x.lineTo(px + r, py + r); x.moveTo(px + r, py - r); x.lineTo(px - r, py + r); x.stroke(); } }); cv.onclick = (e) => { const r = cv.getBoundingClientRect(), X = (e.clientX - r.left)*d, Y = (e.clientY - r.top)*d; let best = null, bd = 18*d; for (const hgt of cv._hits) { const dd = Math.hypot(hgt.px - X, hgt.py - Y); if (dd < bd) { bd = dd; best = hgt; } } if (best) { const q = S.shots[best.i]; playRange(Math.max(0, (q.relT || q.t) - 1.2), (q.rimT || q.end) + 1.6); } }; } } /* ===================== Claude: form feedback and plan ===================== */ async function grabPlayer(q){ if (scanVid.src !== S.source.url) scanVid.src = S.source.url; await loaded(scanVid); const vw = scanVid.videoWidth, vh = scanVid.videoHeight, cv = document.createElement("canvas"); cv.width = 300; cv.height = 400; const x = cv.getContext("2d"); const out = [], t0 = q.relT || q.t; for (const dt of [-0.4, -0.12, 0.12, 0.45]) { const t = Math.max(0, t0 + dt); await seek(scanVid, t); let box = q.shooterBox; const tk = S.follow && q.mine ? trackAt(t) : null; if (tk && tk.ok) box = [tk.cx, tk.cy, tk.w, tk.h]; if (!box) box = [0.5, 0.55, 0.3, 0.6]; const bh = box[3]*vh*1.7, bw = bh*0.75, sx = box[0]*vw - bw/2, sy = (box[1] - box[3]*0.25)*vh - bh/2; x.fillStyle = "#000"; x.fillRect(0, 0, 300, 400); x.drawImage(scanVid, sx, sy, bw, bh, 0, 0, 300, 400); out.push(await new Promise(r => cv.toBlob(r, "image/jpeg", 0.85))); } return out; } async function claudeReady(){ const sample = await cap("sample"); if (!sample) { toast("Claude features work when this page is opened in claude.ai."); return null; } try { const l = await sample.limits(); if (!(l && l.images)) { toast("Image features aren't enabled for this page yet."); return null; } } catch(e){} return sample; } $("#formBtn").onclick = async () => { const sh = shootingStats(); if (!sh || !sh.att) return; const sample = await claudeReady(); if (!sample) return; const btn = $("#formBtn"); btn.disabled = true; S.form = S.form || {}; const list = sh.shots.slice(0, 12); let k = 0; try { for (const q of list) { k++; btn.textContent = `Reviewing shot ${k} of ${list.length}…`; const imgs = await grabPlayer(q); const prompt = `You are a youth basketball shooting coach. Four frames of one player's shot, in time order: the set-up, the moment the ball leaves the hands, just after, and the follow-through. The shot was ${q.made ? "made" : "missed"}${q.dist != null ? ", from about " + Math.round(q.dist) + " feet" : ""}. Judge only what you can see. If a frame is too small or blurry to judge something, say "can't see". Keep each field under 14 words, plain words a 12-year-old understands. Reply with JSON only: {"rating":1-5,"balance":"","elbow":"","release":"","follow_through":"","one_fix":"the single most useful change","drill":"one drill name and how to do it in under 20 words"}`; const r = await sample(prompt, {images: imgs, modelTier: "default"}); const j = parseJSON(r && r.text); if (j) S.form[shotKey(q)] = j; renderReport(); } toast("Form feedback added to each shot. Build the improvement plan next."); } catch(e) { toast(e && e.code === "rate_limited" ? "Claude is busy. Try again in a minute." : e && (e.code === "not_granted" || e.code === "declined") ? "Form feedback needs your OK to ask Claude." : "Form feedback stopped early."); } finally { btn.disabled = false; btn.innerHTML = 'Form feedback'; } }; function reportFacts(){ const sh = shootingStats(), mv = movementStats(), f = S.follow; const lines = []; lines.push(`Player: ${f ? (f.name || "") + (f.number ? " #" + f.number : "") : "one shooter"}${f && f.team ? ", " + f.team : ""}.`); if (sh) { lines.push(`Shooting: ${sh.made}/${sh.att} FG, ${sh.threesM}/${sh.threesA} from three.`); for (const k of ["paint","mid","corner3","three"]) if (sh.zones[k].a) lines.push(`${ZONES[k]}: ${sh.zones[k].m}/${sh.zones[k].a}.`); sh.shots.forEach((q, i) => { const fb = S.form && S.form[shotKey(q)]; lines.push(`Shot ${i+1}: ${q.made ? "made" : "missed"}${q.dist != null ? ", " + Math.round(q.dist) + " ft, " + ZONES[q.zone] : ""}${fb ? `. Form ${fb.rating}/5; balance: ${fb.balance}; elbow: ${fb.elbow}; release: ${fb.release}; follow-through: ${fb.follow_through}; fix: ${fb.one_fix}` : ""}.`); }); } if (mv) lines.push(`Movement on camera: ${Math.round(mv.dist)} ft in ${Math.round(mv.tracked)} s, top speed ${(mv.top*0.6818).toFixed(1)} mph, ${mv.sprints} sprints.`); const fs = formSummary(); for (const k of Object.keys(FORM)) if (fs[k]) lines.push(`${FORM[k].label}: median ${fs[k].median} ${FORM[k].unit} (target ${FORM[k].target}), ${fs[k].flagged} of ${fs[k].n} shots off target.`); for (const m of S.moments || []) lines.push(`${fmt(m.t)}${m.end ? "–" + fmt(m.end) : ""} ${m.kind === "fix" ? "FIX" : "GOOD"}: ${m.title}. ${m.metric}.`); return lines.join("\n"); } $("#planBtn").onclick = async () => { const sample = await cap("sample"); if (!sample) { toast("The improvement plan works when this page is opened in claude.ai."); return; } const btn = $("#planBtn"); btn.disabled = true; btn.textContent = "Writing plan…"; try { const prompt = `You are a youth basketball coach writing a short, encouraging improvement plan for one player from game or practice data. Use only these facts; do not invent numbers. ${reportFacts()} ${S.form ? "" : "No form review was done yet; base the plan on the numbers and say a form review would sharpen it."} Reply with JSON only: {"summary":"2 sentences","strengths":["max 3 short items"],"fixes":[{"issue":"","why":"what in the data shows it","drill":"name + how","reps":"e.g. 3 x 10 makes"}],"week":[{"day":"Mon","focus":"","drill":"","minutes":20}]} At most 3 fixes and 4 practice days.`; const r = await sample(prompt, {modelTier: "default"}); const j = parseJSON(r && r.text); if (!j) throw new Error("unreadable"); S.plan = j; renderReport(); setTab("report"); const el = document.querySelector("#report .plan"); el && el.scrollIntoView({behavior:"smooth", block:"start"}); } catch(e) { toast(e && e.code === "rate_limited" ? "Claude is busy. Try again in a minute." : e && (e.code === "not_granted" || e.code === "declined") ? "The plan needs your OK to ask Claude." : "Couldn't write the plan. Try again."); } finally { btn.disabled = false; btn.textContent = "Improvement plan"; } }; function planHTML(p){ const li = a => (a || []).map(x => `
  • ${esc(x)}
  • `).join(""); return `

    Improvement plan by Claude

    ${esc(p.summary || "")}

    ${p.strengths && p.strengths.length ? `

    Keep doing

      ${li(p.strengths)}
    ` : ""} ${p.fixes && p.fixes.length ? `

    Work on

      ${p.fixes.map(f => `
    1. ${esc(f.issue || "")}. ${esc(f.why || "")}
      Drill: ${esc(f.drill || "")} (${esc(f.reps || "")})
    2. `).join("")}
    ` : ""} ${p.week && p.week.length ? `

    This week

    ${p.week.map(d => ``).join("")}
    ${esc(d.day || "")}${esc(d.focus || "")}: ${esc(d.drill || "")}${esc(String(d.minutes || ""))} min
    ` : ""}
    `; } /* ===================== export ===================== */ function summaryText(){ const sh = shootingStats(), mv = movementStats(), f = S.follow; const L = [`${f ? (f.name || "Player") + (f.number ? " #" + f.number : "") : "Shooting report"}${f && f.team ? " · " + f.team : ""}`, ""]; quickRead(sh, mv).forEach(x => L.push("• " + x)); const fc = fixCounts(); if (fc.length) { L.push("", "Work on:"); fc.slice(0, 3).forEach(([k, M], i) => L.push(`${i+1}. ${RULES[k].title} (${M.map(m => fmt(m.t)).join(", ")}): ${RULES[k].drill}, ${RULES[k].reps}`)); } if (S.plan) { L.push("", "Plan: " + (S.plan.summary || "")); (S.plan.fixes || []).forEach((x, i) => L.push(`${i+1}. ${x.issue}: ${x.drill} (${x.reps})`)); } L.push("", "Made with Clutch Coach"); return L.join("\n"); } function courtSVG(sh){ const K = courtSpec(), Ymax = 33, P = (X, Y) => [((X + 25)/50*500).toFixed(1), (Y/Ymax*330).toFixed(1)]; let s = ``; for (const L of courtLines()) s += ``; const h = P(0, K.hoopY); s += ``; for (const q of (sh ? sh.shots : [])) { if (!q.court || q.court[1] > Ymax) continue; const [x, y] = P(q.court[0], q.court[1]); s += q.made ? `` : ``; } return s + ``; } function reportHTMLDoc(){ const sh = shootingStats(), mv = movementStats(), f = S.follow; const title = `${f ? (f.name || "Player") + (f.number ? " #" + f.number : "") : "Shooting report"}`; const rows = sh ? sh.shots.map((q, i) => { const fb = S.form && S.form[shotKey(q)]; return `${i+1}${fmt(q.relT || q.t)}${q.made ? "Made" : "Missed"}${q.dist != null ? Math.round(q.dist) + " ft · " + ZONES[q.zone] : "–"}${fb ? esc(fb.one_fix || "") : ""}`; }).join("") : ""; return `${esc(title)} · Clutch Coach report

    ${esc(title)}

    ${esc(f && f.team ? f.team + " · " : "")}${esc(S.source.name || "")} · ${new Date().toLocaleDateString()}

    Numbers

    ${sh ? `
    ${sh.made}/${sh.att}field goals (${pct(sh.made, sh.att)})
    ${sh.threesM}/${sh.threesA}threes
    ${sh.pts}points
    ` : ""}${mv ? `
    ${Math.round(mv.dist)} ftrun on camera
    ${(mv.top*0.6818).toFixed(1)} mphtop speed
    ${mv.sprints}sprints
    ` : ""}

    Quick read

      ${quickRead(sh, mv).map(x => `
    • ${esc(x)}
    • `).join("")}
    ${S.calib && sh ? `

    Shot chart

    ${courtSVG(sh)}` : ""} ${S.plan ? planHTML(S.plan).replace(/var\\(--track\\)/g, "#2EE6C5") : ""} ${(S.moments || []).length ? `

    Coaching moments

    ${S.moments.map(m => ``).join("")}
    TimeWhatMeasuredFix and drill
    ${fmt(m.t)}${m.end ? "–" + fmt(m.end) : ""}${esc(m.title)}${esc(m.metric)}${esc(m.fix)}${m.drill ? `
    Drill: ${esc(m.drill)} (${esc(m.reps)})` : ""}
    ` : ""} ${rows ? `

    Shots

    ${rows}
    #TimeResultFromForm note
    ` : ""}

    Made with Clutch Coach. Stats come from video and can be off; the coach confirmed uncertain shots.

    `; } $("#reportDl").onclick = async () => { const dl = await cap("downloads"), name = `clutch-report${S.follow && S.follow.number ? "-" + S.follow.number : ""}.html`; if (!dl) { try { await navigator.clipboard.writeText(summaryText()); toast("Saving isn't available here, so the summary was copied instead."); } catch(e){ toast("Saving isn't available in this view."); } return; } try { await dl.save({filename: name, data: reportHTMLDoc()}); } catch(e) { if (e && e.code !== "declined") toast("Couldn't save the report."); } }; $("#reportCopy").onclick = async () => { try { await navigator.clipboard.writeText(summaryText()); toast("Summary copied."); } catch(e){ $("#tmText").value = summaryText(); $("#tmTitle").textContent = "Report summary"; $("#tmSub").textContent = "Copy isn't available here. Select the text and copy it."; $("#textModal").hidden = false; } }; /* ===================== how-it-works numbers ===================== */ async function renderHow(){ if (!S.source.sample || !S.shots) return; let T; try { T = await (await fetch("media/workout_truth.json")).json(); } catch(e){ return; } const rows = [], errs = []; let right = 0, auto = 0, wrong = 0, found = 0; for (const g of T.shots) { const q = S.shots.find(x => Math.abs((x.rimT || x.t) - g.rim) < 1.6 || (x.t <= g.rim && x.end >= g.rim - 0.3)); if (q) { found++; if (q.made === g.made) right++; } let err = null; if (q && q.court) { err = Math.hypot(q.court[0] - g.spot_ft[0], q.court[1] - g.spot_ft[1]); if (q.how === "traced" && q.mine === true) errs.push(err); } const cred = !q ? "–" : q.coach === true ? "Coach said yes" : q.mine === true && q.sure ? (auto++, "Auto") : q.mine === false && q.sure ? (wrong++, "Wrong player") : "Asks coach"; rows.push(`${fmt(g.release)}${Math.round(Math.hypot(g.spot_ft[0], g.spot_ft[1] - 5.17))} ft · ${g.pts}PT${q && q.court ? Math.round(q.dist) + " ft · " + q.pts + "PT" : "–"}${err != null ? err.toFixed(1) + " ft" : "–"}${g.made ? "Made" : "Missed"}${q && q.made === g.made ? " ✓" : " ✗"}${cred}`); } errs.sort((a,b) => a-b); $("#truthRows").innerHTML = rows.join(""); // form flaws planted in the sample, and what the coaching engine made of them const FLAW = {flat:["arc","Flat arc","entry_angle_deg","° into the rim","° into the rim"], fade:["drift","Fading away","drift_ft"," ft drift"," ft drift"], moving:["drift","Shooting on the move","drift_ft"," ft drift"," ft drift"], low:["arc","Low, flat release","entry_angle_deg","° into the rim","° into the rim"], slow:["trigger","Slow trigger","set_time"," s catch to release"," s catch to release"]}; const fr = []; let caught = 0, planted = 0, falseF = 0, clean = 0; for (const g of T.shots) { const q = S.shots.find(x => Math.abs((x.rimT || x.t) - g.rim) < 1.6); const f = q && q.form || {}; if (!g.flaw) { if (g.kind === "jumper" && f.flags) { clean++; falseF += f.flags.length; if (f.flags.length) fr.push(`${fmt(g.release)}None (clean rep)–${f.flags.map(k => FORM[k].label + " " + f[k]).join(", ")}False flag`); } continue; } planted++; const [k, name, tk, unit, mu] = FLAW[g.flaw], v = f[k], hit = (f.flags || []).includes(k); if (hit) caught++; fr.push(`${fmt(g.release)}${name}${g[tk]}${unit}${v != null ? v + mu : esc(f.unmeasured || "not measured")}${hit ? "Flagged ✓" : v == null ? "Not measured" : "Missed"}`); } const wk = (S.moments || []).find(m => m.key === "walk"); if (T.slow_walk) fr.push(`${fmt(T.slow_walk[0])}–${fmt(T.slow_walk[1])}Walking between reps1.3 m/s walk${wk ? fmt(wk.t) + "–" + fmt(wk.end) : "–"}${wk ? "Flagged ✓" : "Missed"}`); if ($("#formRows")) { $("#formRows").innerHTML = fr.join(""); $("#hForm").innerHTML = `${caught + (wk ? 1 : 0)}of ${planted + (T.slow_walk ? 1 : 0)}`; $("#hFalse").innerHTML = `${falseF}in ${clean} clean reps`; } $("#hShots").innerHTML = `${right}of ${T.attempts}`; $("#hLoc").innerHTML = `${errs.length ? errs[Math.floor(errs.length/2)].toFixed(1) : "–"}ft`; $("#hWho").innerHTML = `${auto}of ${T.attempts}`; const mv = movementStats(); if (mv) { $("#hSpeed").innerHTML = `${(mv.top*0.6818).toFixed(1)}mph`; $("#hSpeedP").textContent = `top speed; the true value is ${T.top_speed_mph} mph.`; $("#hPace").innerHTML = `${(mv.dist/Math.max(1, mv.tracked)).toFixed(1)}ft/s`; $("#hPaceP").textContent = `average pace while on camera; the true value is ${(T.distance_ft/T.duration).toFixed(1)} ft/s.`; $("#hCover").innerHTML = `${Math.round(mv.tracked/T.duration*100)}%`; } } /* ===================== routing + misc ===================== */ function route(){ const v = (location.hash || "#studio").slice(1); const name = ["studio","plans","how","status"].includes(v) ? v : "studio"; ["studio","plans","how","status"].forEach(n => $("#view-" + n).hidden = n !== name); document.querySelectorAll(".nav a").forEach(a => a.setAttribute("aria-current", a.dataset.view === name ? "page" : "false")); $(".mobilebar").style.display = name === "studio" ? "" : "none"; if (name === "studio") requestAnimationFrame(() => { drawStage(); drawTimeline(); }); } window.addEventListener("hashchange", route); window.addEventListener("resize", () => { drawStage(); drawTimeline(); }); document.addEventListener("keydown", e => { if (e.target.matches("input,textarea")) return; if (e.code === "Space") { e.preventDefault(); $("#playBtn").click(); } else if (e.key === "ArrowRight") jump(1); else if (e.key === "ArrowLeft") jump(-1); else if (e.key === "Escape") { stopReel(); endPick(); document.querySelectorAll(".modal").forEach(m => m.hidden = true); } }); let toastT; function toast(msg){ const t = $("#toast"); t.textContent = msg; t.classList.add("show"); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove("show"), 3800); } // test hook used to precompute the sample analysis window.__clutch = {S, coachMoments, formSummary, shotForm, speedSeries, attributeShots, renderReport, buildCalib, movementStats, shootingStats, toCourt, setShotMode(m){ SHOT_MODE = m; }, setMadeRule(f){ MADE_RULE = f; }, analyzeShots, runShots, updateHoopBtn, analyze, buildTrack, rescore, applyFollow, signature, setFollow(f){ S.follow = f; applyFollow(); }}; route(); setHud(); initEngine(); loadSample(); requestAnimationFrame(loop); cap("sample"); cap("downloads"); // sghadimi.com: on phones, bring the picture up under the header while marking the hoop, court or player new MutationObserver(() => { const st = document.getElementById("stage"); if (!st.classList.contains("picking") || !matchMedia("(max-width:700px), (max-height:500px)").matches) return; const top = document.querySelector(".top"); scrollTo({top: st.getBoundingClientRect().top + scrollY - (top ? top.offsetHeight : 0) - 8, behavior: "smooth"}); }).observe(document.getElementById("stage"), {attributes: true, attributeFilter: ["class"]});