// 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 recorder, audioContext, tabStream, micStream, uploadQueue = Promise.resolve(), recordingName; // state: idle | recording | transcribing | done | error ; popup polls it const recorderState = { state: "idle", name: "", t0: 0, t1: 0, chunks: 0, mic: false, text: "" }; // Toolbar icon follows state; failed uploads while recording show as error. The idle icon is drawn by background.js on startup. setInterval(() => chrome.runtime.sendMessage({ to: "bg", state: recorderState.state === "recording" && recorderState.failed ? "error" : recorderState.state }), 1000); // Messages from popup.js / teams.js are addressed with to:"off"; other messages are ignored. chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { if (message.to !== "off") return; if (message.cmd === "status") sendResponse(recorderState); // start is async: reply with ok, or with the error text (also stored in recorderState for the popup). if (message.cmd === "start") start(message.id, message.tabId).then(() => sendResponse({ ok: true }), error => { recorderState.state = "error"; recorderState.text = String(error); sendResponse({ err: String(error) }); }); // teams.js events are re-based to seconds since recording start; events from before start are dropped. if (message.cmd === "events") { for (const event of message.events) if (event.ts >= recorderState.t0) recorderState.ev.push({ t: (event.ts - recorderState.t0) / 1000, kind: event.kind, who_key: event.who_key, who: event.who, text: event.text }); } // Stop: MediaRecorder.onstop handles the finalisation. if (message.cmd === "stop") { recorder.stop(); sendResponse({ 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 (!recorderState.ev.length) return; const batch = recorderState.ev.splice(0); try { const response = await fetch(`${API}/events?name=${recordingName}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(batch) }); if (!response.ok) throw 0; recorderState.evSent += batch.length; } catch { recorderState.failed++; } } // Start recording the given tab (id from tabCapture.getMediaStreamId). async function start(streamId, tabId) { recordingName = "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 captureConstraint = { mandatory: { chromeMediaSource: "tab", chromeMediaSourceId: streamId } }; const videoConstraint = { mandatory: { ...captureConstraint.mandatory, maxFrameRate: 15 } }; // fewer fps = more bits per frame for slides/text tabStream = await navigator.mediaDevices.getUserMedia({ audio: captureConstraint, video: videoConstraint }); for (const t of tabStream.getVideoTracks()) t.contentHint = "detail"; // favor sharpness over motion // Mixer: tab audio + optional mic are mixed into one destination track. audioContext = new AudioContext(); const dest = audioContext.createMediaStreamDestination(); const tabSource = audioContext.createMediaStreamSource(tabStream); tabSource.connect(dest); tabSource.connect(audioContext.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 micStream = await navigator.mediaDevices.getUserMedia({ audio: true }); audioContext.createMediaStreamSource(micStream).connect(dest); } catch { micStream = null; } // Output stream: tab video + mixed audio. const outStream = new MediaStream([...tabStream.getVideoTracks(), ...dest.stream.getAudioTracks()]); // VP8 video + Opus audio at 3 Mbps video (1 Mbps gave blocky/ringing text on shared screens). recorder = new MediaRecorder(outStream, { mimeType: "video/webm;codecs=vp8,opus", videoBitsPerSecond: 3e6 }); // Each 10 s chunk is uploaded in order through the uploadQueue promise chain. recorder.ondataavailable = event => { // Chain the upload on uploadQueue so chunks reach the server in order; count success or failure, then flush events. uploadQueue = uploadQueue.then(() => fetch(`${API}/chunk?name=${recordingName}`, { method: "POST", body: event.data })).then(() => recorderState.chunks++, () => recorderState.failed++).then(flushEv); }; // Stop path: wait for uploads, release the capture, then ask the server to transcribe. recorder.onstop = async () => { recorderState.state = "transcribing"; recorderState.t1 = Date.now(); try { // Wait for all queued chunk uploads to finish before asking for transcription. await uploadQueue; await flushEv(); // Release tab/mic capture devices and the audio context. [tabStream, micStream].forEach(stream => stream && stream.getTracks().forEach(track => track.stop())); audioContext.close(); // Server concatenates the uploaded chunks and runs the transcription pipeline; body is the result text. const response = await fetch(`${API}/stop?name=${recordingName}`, { method: "POST" }); recorderState.text = await response.text(); recorderState.state = response.ok ? "done" : "error"; } catch (error) { recorderState.text = "server down or failed: " + error; recorderState.state = "error"; } recorder = null; }; // Reset per-session state and record the start time; events are kept in recorderState.ev until sent. Object.assign(recorderState, { state: "recording", name: recordingName, t0: Date.now(), chunks: 0, failed: 0, mic: !!micStream, text: "", ev: [], evSent: 0, tabId }); // 10 s timeslice: MediaRecorder emits a chunk every 10 s. recorder.start(10000); }