// Offscreen document: records the Teams tab (tabCapture) and uploads 10 s WebM chunks to the local server. // Local server endpoint (server.py); must match start.js port 18765. const API = "http://127.0.0.1:18765"; let rec, ctx, tab, mic, q = Promise.resolve(), name; // state: idle | recording | transcribing | done | error ; popup polls it const S = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" }; // Messages from popup.js / teams.js are addressed with to:"off"; other messages are ignored. chrome.runtime.onMessage.addListener((m, _s, send) => { if (m.to !== "off") return; if (m.cmd === "status") send(S); // start is async: reply with ok, or with the error text (also stored in S for the popup). if (m.cmd === "start") start(m.id, m.tabId).then(() => send({ ok: true }), e => { S.state = "error"; S.text = String(e); send({ err: String(e) }); }); // teams.js events are re-based to seconds since recording start; events from before start are dropped. if (m.cmd === "events") { for (const e of m.events) if (e.ts >= S.t0) S.ev.push({ t: (e.ts - S.t0) / 1000, kind: e.kind, who_key: e.who_key, who: e.who, text: e.text }); } // Stop: MediaRecorder.onstop handles the finalisation. if (m.cmd === "stop") { rec.stop(); send({ ok: true }); } // Keep the message channel open for the async replies above. return true; }); // Send buffered Teams events to the server; on failure count it so the popup can warn. async function flushEv() { if (!S.ev.length) return; const b = S.ev.splice(0); try { const r = await fetch(`${API}/events?name=${name}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) }); if (!r.ok) throw 0; S.evSent += b.length; } catch { S.failed++; } } // Start recording the given tab (id from tabCapture.getMediaStreamId). async function start(id, tabId) { name = "teams_" + new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19); // Tab capture stream: the chromeMediaSource constraint is the only way to get tab audio/video in an extension. const src = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: id } }; tab = await navigator.mediaDevices.getUserMedia({ audio: src, video: src }); // Mixer: tab audio + optional mic are mixed into one destination track. ctx = new AudioContext(); const dest = ctx.createMediaStreamDestination(); const t = ctx.createMediaStreamSource(tab); t.connect(dest); t.connect(ctx.destination); // tabCapture mutes the tab; play it back // Mic is optional: needs the one-time grant from mic.html; without it the recording is tab-only. try { // needs one-time grant via mic.html mic = await navigator.mediaDevices.getUserMedia({ audio: true }); ctx.createMediaStreamSource(mic).connect(dest); } catch { mic = null; } // Output stream: tab video + mixed audio. const out = new MediaStream([...tab.getVideoTracks(), ...dest.stream.getAudioTracks()]); // VP8 video + Opus audio at 1 Mbps video, a format the server's ffmpeg pipeline accepts. rec = new MediaRecorder(out, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 1e6 }); // Each 10 s chunk is uploaded in order through the q promise chain. rec.ondataavailable = e => { // Chain the upload on q so chunks reach the server in order; count success or failure, then flush events. q = q.then(() => fetch(`${API}/chunk?name=${name}`, { method: "POST", body: e.data })).then(() => S.chunks++, () => S.failed++).then(flushEv); }; // Stop path: wait for uploads, release the capture, then ask the server to transcribe. rec.onstop = async () => { S.state = "transcribing"; S.t1 = Date.now(); try { // Wait for all queued chunk uploads to finish before asking for transcription. await q; await flushEv(); // Release tab/mic capture devices and the audio context. [tab, mic].forEach(s => s && s.getTracks().forEach(t => t.stop())); ctx.close(); // Server concatenates the uploaded chunks and runs the transcription pipeline; body is the result text. const r = await fetch(`${API}/stop?name=${name}`, { method: "POST" }); S.text = await r.text(); S.state = r.ok ? "done" : "error"; } catch (e) { S.text = "server down or failed: " + e; S.state = "error"; } rec = null; }; // Reset per-session state and record the start time; events are kept in S.ev until sent. Object.assign(S, { state: "recording", name, t0: Date.now(), chunks: 0, failed: 0, mic: !!mic, text: "", ev: [], evSent: 0, tabId }); // 10 s timeslice: MediaRecorder emits a chunk every 10 s. rec.start(10000); }