Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
2406 lines (2272 loc) · 93.7 KB
/
Copy pathcontent.js
File metadata and controls
2406 lines (2272 loc) · 93.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Echoly content script — owns WebRTC PeerConnection lifecycle, the in-page
// overlay panel, and YT video element capture. Background tells us when to
// start/stop/update; we tell background what's happening via CONTENT_STATE.
//
// Layered: F9 version guard, F6 token-guarded async, F5 captureStream retry,
// F1 overlay panel, F2 history, F3 source captions, F4 handover.
(() => {
// ───── F9 — Idempotent version guard ──────────────────────────────────────
const ECHOLY_VERSION = "0.6.1";
const GLOBAL_KEY = "__echolyContentVersion";
if (window[GLOBAL_KEY] === ECHOLY_VERSION) return;
// Older copy may have left UI behind; clean up before re-installing listeners.
document.querySelectorAll(".ec-root").forEach((el) => el.remove());
window[GLOBAL_KEY] = ECHOLY_VERSION;
// ───── Constants ──────────────────────────────────────────────────────────
// KYMA_BASE is the BYOK fallback. v0.6.1: background.js may pass an alt
// apiBase (Echoly's server proxy) in settings.apiBase when the user is
// signed in without their own Kyma key. Sites that fetch Kyma read the
// session-scoped `apiBase` instead of this constant when set.
const KYMA_BASE = "https://api.kymaapi.com/v1";
let apiBase = KYMA_BASE; // overwritten on each session start
const OPENAI_CALLS_URL = "https://api.openai.com/v1/realtime/translations/calls";
const SESSION_LIMIT_MS = 60 * 60 * 1000;
const SESSION_WARNING_MS = 55 * 60 * 1000;
const HEARTBEAT_MS = 30_000;
const CAPTION_POLL_MS = 350;
const HISTORY_MAX = 16;
const VOICE_GAIN_MAX = 2.0; // unity at slider 50, 2× boost at 100
const LAYOUT_KEY = "echolyOverlayLayout";
const RTL_LANGS = new Set(["ar", "fa", "he", "ur"]);
const LANGUAGES = [
["en", "English"], ["vi", "Vietnamese"], ["ja", "Japanese"],
["ko", "Korean"], ["zh", "Chinese"], ["fr", "French"],
["es", "Spanish"], ["de", "German"], ["pt", "Portuguese"],
["hi", "Hindi"], ["id", "Indonesian"], ["it", "Italian"],
["ru", "Russian"],
];
const LANG_NAME = Object.fromEntries(LANGUAGES);
const REALTIME_VOICES = [
"marin", "alloy", "ash", "ballad", "coral",
"echo", "sage", "shimmer", "verse",
];
// Standard tier voices — `speech-02-turbo` IDs. Cross-language: each
// voice handles all 13 target languages. Curated 2026-05-08.
const STANDARD_VOICES = [
["English_magnetic_voiced_man", "Magnetic Man"],
["English_captivating_female1", "Captivating Female"],
["English_ManWithDeepVoice", "Deep Voice Man"],
["English_ConfidentWoman", "Confident Woman"],
["Chinese (Mandarin)_News_Anchor","News Anchor"],
];
const STANDARD_DEFAULT_VOICE = STANDARD_VOICES[0][0];
// Standard pipeline tunables. CHUNK_MS too short = wasteful per-call
// overhead; too long = unbearable lag. 5s is the sweet spot for podcast/
// keynote speech where sentences average 3-6s.
const STANDARD_CHUNK_MS = 5000;
const STANDARD_MIN_CHUNK_BYTES = 2000; // sub-2KB blobs are silence
const STANDARD_RECORDER_MIMES = [
"audio/webm;codecs=opus",
"audio/webm",
"audio/ogg;codecs=opus",
"audio/mp4",
];
// ───── F6 — Token-guarded session state ───────────────────────────────────
// Every async callback that could mutate session state captures `pageToken`
// in closure and checks `if (token !== pageToken) return` before mutating.
// Each new session bumps pageToken so stale callbacks are silently dropped.
let pageToken = 0;
let session = null; // active session
let prevSession = null; // held during handover until new is fully ready
let settings = null;
let history = [];
let currentTargetText = "";
let currentSourceText = "";
let captionPollTimer = null;
let heartbeatTimer = null;
let warningTimer = null;
let limitTimer = null;
let warningShown = false;
let videoEl = null;
let onYTPause = null;
let onYTPlay = null;
let lastSpaUrl = location.href;
let layout = loadLayout();
// SF3 — Original-volume drift guard: YouTube's player re-applies its
// own internally-cached volume on certain events (ad insertion, video
// element refresh, etc.), stomping our `video.volume = X` write. We
// hook `volumechange` and snap the volume back to our desired value
// when drift is detected. `desiredOriginalVol` < 0 means "not engaged"
// (no session active); >=0 is the value we're enforcing. The write
// timestamp avoids a feedback loop with our own writes triggering the
// same listener.
let desiredOriginalVol = -1;
let lastOriginalWriteAt = 0;
let onVolumeDrift = null;
// SF8 Phase 1 — Playback-rate awareness. Real fix (rate-aware scheduling
// + Realtime model research) is later phases. For now we just warn the
// user that translation may drift at non-1× speeds, so they have the
// right expectation. Toast is debounced so a series of rate changes
// (e.g. dragging YT's speed slider) doesn't spam.
let onRateChange = null;
let lastRateToastAt = 0;
// ───── Background channel ─────────────────────────────────────────────────
// Extension reload (dev mode update or Chrome auto-update) invalidates the
// content script's runtime handle. After that, sendMessage throws SYNC
// ("Extension context invalidated") — .catch() can't catch a sync throw,
// so wrap the whole call. Once invalidated we also stop emitting and tear
// down the overlay so the orphaned script doesn't keep firing.
let runtimeAlive = true;
function notifyBackground(msg) {
if (!runtimeAlive) return;
try {
const res = chrome.runtime?.id ? chrome.runtime.sendMessage(msg) : null;
if (res && typeof res.catch === "function") res.catch(() => {});
} catch (err) {
if (String(err?.message || err).includes("Extension context invalidated")) {
runtimeAlive = false;
try { handleUnload?.(); } catch {}
}
}
}
function emitState(partial) {
notifyBackground({ type: "CONTENT_STATE", ...partial });
}
function emitEnded(reason) {
notifyBackground({ type: "CONTENT_ENDED", reason });
}
// ───── F1 — Overlay panel ─────────────────────────────────────────────────
let root = null;
let elements = {};
function loadLayout() {
try {
return {
left: null, top: null, width: null, height: null, sideCollapsed: false,
...JSON.parse(localStorage.getItem(LAYOUT_KEY) || "{}"),
};
} catch {
return { left: null, top: null, width: null, height: null, sideCollapsed: false };
}
}
function saveLayout() {
try { localStorage.setItem(LAYOUT_KEY, JSON.stringify(layout)); } catch {}
}
function clampLayout() {
const maxW = Math.max(300, window.innerWidth - 24);
const maxH = Math.max(130, window.innerHeight - 24);
const w = Math.min(Math.max(layout.width || 560, 300), maxW);
const h = Math.min(Math.max(layout.height || 200, 130), maxH);
const left = Math.min(
Math.max(layout.left ?? window.innerWidth - w - 24, 12),
Math.max(12, window.innerWidth - w - 12),
);
const top = Math.min(
Math.max(layout.top ?? window.innerHeight - h - 96, 12),
Math.max(12, window.innerHeight - h - 12),
);
layout = { ...layout, left, top, width: w, height: h };
}
function applyLayout() {
if (!root) return;
clampLayout();
root.style.left = layout.left + "px";
root.style.top = layout.top + "px";
root.style.width = layout.width + "px";
root.style.height = layout.height + "px";
root.style.right = "auto";
root.style.bottom = "auto";
root.classList.toggle("is-side-collapsed", !!layout.sideCollapsed);
root.classList.toggle("is-compact", layout.width < 560 || layout.height < 210);
root.classList.toggle("is-roomy", layout.width > 760 && layout.height > 235);
root.style.setProperty(
"--ec-target-lines",
String(Math.max(2, Math.min(8, Math.floor((layout.height - 74) / 38)))),
);
if (elements.hideBtn) {
elements.hideBtn.textContent = layout.sideCollapsed ? "Show" : "Hide";
}
}
function buildOverlay() {
if (root) return;
root = document.createElement("aside");
root.className = "ec-root";
root.dataset.state = "ready";
root.innerHTML = `
<div class="ec-toolbar" data-ec-drag>
<span class="ec-brand">
<span class="ec-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round">
<path d="M7 9v6M11 6v12M15 8v8M19 11v2"/>
</svg>
</span>
<span class="ec-wordmark">Echoly</span>
<span class="ec-state" data-ec-status>Ready</span>
</span>
<span class="ec-spacer"></span>
<select class="ec-select" data-ec-language aria-label="Target language"></select>
<select class="ec-select" data-ec-voice aria-label="Voice"></select>
<button class="ec-btn" type="button" data-ec-hide>Hide</button>
<button class="ec-btn ec-btn-primary" type="button" data-ec-stop>Stop</button>
</div>
<div class="ec-body">
<div class="ec-main">
<div class="ec-target" data-ec-target></div>
</div>
<div class="ec-side" data-ec-side>
<div class="ec-source" data-ec-source hidden></div>
<div class="ec-history" data-ec-history hidden></div>
</div>
</div>
<span class="ec-resize-edge ec-resize-edge-n" data-ec-resize="n"></span>
<span class="ec-resize-edge ec-resize-edge-e" data-ec-resize="e"></span>
<span class="ec-resize-edge ec-resize-edge-s" data-ec-resize="s"></span>
<span class="ec-resize-edge ec-resize-edge-w" data-ec-resize="w"></span>
<span class="ec-resize-corner ec-resize-corner-nw" data-ec-resize="nw"></span>
<span class="ec-resize-corner ec-resize-corner-ne" data-ec-resize="ne"></span>
<span class="ec-resize-corner ec-resize-corner-sw" data-ec-resize="sw"></span>
<span class="ec-resize-corner ec-resize-corner-se" data-ec-resize="se"></span>
`;
document.documentElement.appendChild(root);
elements = {
status: root.querySelector("[data-ec-status]"),
langSelect: root.querySelector("[data-ec-language]"),
voiceSelect: root.querySelector("[data-ec-voice]"),
target: root.querySelector("[data-ec-target]"),
source: root.querySelector("[data-ec-source]"),
history: root.querySelector("[data-ec-history]"),
hideBtn: root.querySelector("[data-ec-hide]"),
stopBtn: root.querySelector("[data-ec-stop]"),
drag: root.querySelector("[data-ec-drag]"),
};
// Populate language picker
for (const [code, name] of LANGUAGES) {
const opt = document.createElement("option");
opt.value = code;
opt.textContent = name;
elements.langSelect.appendChild(opt);
}
populateVoicePicker(settings?.tier || "realtime");
elements.langSelect.value = settings?.targetLanguage || "vi";
elements.langSelect.addEventListener("change", () => {
const newLang = elements.langSelect.value;
if (settings?.tier === "standard") {
// Standard pipeline picks up the new prompt on the next chunk; no
// tear-down needed. Push to background so popup stays in sync.
settings.targetLanguage = newLang;
notifyBackground({ type: "UPDATE_SETTINGS", settings: { targetLanguage: newLang } });
setStatusText("Switching to " + (LANG_NAME[newLang] || newLang));
setOverlayState("live");
} else {
requestHandover({ targetLanguage: newLang });
}
});
elements.voiceSelect.addEventListener("change", () => {
const newVoice = elements.voiceSelect.value;
if (settings?.tier === "standard") {
settings.standardVoice = newVoice;
notifyBackground({ type: "UPDATE_SETTINGS", settings: { standardVoice: newVoice } });
} else {
requestHandover({ realtimeVoice: newVoice });
}
});
elements.hideBtn.addEventListener("click", () => {
layout.sideCollapsed = !layout.sideCollapsed;
saveLayout();
applyLayout();
});
elements.stopBtn.addEventListener("click", () => {
stopSession("user-stop");
notifyBackground({ type: "CONTENT_STATE", running: false, status: "Stopped" });
emitEnded("Stopped");
});
bindDragResize();
applyLayout();
window.addEventListener("resize", applyLayout);
}
// Tier-aware voice list rebuild. Realtime exposes 9 OpenAI voices + Auto;
// Standard exposes 5 curated voices. Called from buildOverlay and
// on tier change so the dropdown matches the active pipeline.
function populateVoicePicker(tier) {
if (!elements.voiceSelect) return;
elements.voiceSelect.replaceChildren();
if (tier === "standard") {
for (const [id, name] of STANDARD_VOICES) {
const opt = document.createElement("option");
opt.value = id; opt.textContent = name;
elements.voiceSelect.appendChild(opt);
}
elements.voiceSelect.value = settings?.standardVoice || STANDARD_DEFAULT_VOICE;
} else {
const autoOpt = document.createElement("option");
autoOpt.value = ""; autoOpt.textContent = "Auto";
elements.voiceSelect.appendChild(autoOpt);
for (const v of REALTIME_VOICES) {
const opt = document.createElement("option");
opt.value = v; opt.textContent = v.charAt(0).toUpperCase() + v.slice(1);
elements.voiceSelect.appendChild(opt);
}
elements.voiceSelect.value = settings?.realtimeVoice ?? "marin";
}
}
function setOverlayState(state) {
if (root) root.dataset.state = state;
}
function setStatusText(text) {
if (elements.status) elements.status.textContent = text;
}
function setTargetText(text) {
if (!elements.target) return;
elements.target.textContent = text;
const lang = settings?.targetLanguage;
elements.target.dir = RTL_LANGS.has(lang) ? "rtl" : "ltr";
}
// Toast accepts plain text + optional CTA. Built via DOM APIs (not innerHTML)
// because the text often comes from upstream API errors — a crafted error
// body would otherwise be an XSS vector inside youtube.com's origin.
function showToast(text, opts, durationMs) {
if (!root) return;
if (typeof opts === "number") { durationMs = opts; opts = null; }
if (!durationMs) durationMs = 8000;
let toast = root.querySelector(".ec-toast");
if (toast) toast.remove();
toast = document.createElement("div");
toast.className = "ec-toast";
toast.textContent = String(text || "");
if (opts && opts.cta) {
toast.append(" ");
const a = document.createElement("a");
a.href = String(opts.cta);
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = String(opts.ctaLabel || "Open");
toast.appendChild(a);
}
root.appendChild(toast);
setTimeout(() => toast.remove(), durationMs);
}
function removeOverlay() {
if (!root) return;
window.removeEventListener("resize", applyLayout);
root.remove();
root = null;
elements = {};
}
// ───── Drag + resize ──────────────────────────────────────────────────────
function bindDragResize() {
let dragMode = null;
let pointer = null;
elements.drag.addEventListener("pointerdown", (e) => {
if (e.button !== 0) return;
if (e.target.closest("button, select, input")) return;
dragMode = "move";
pointer = capturePointer(e);
root.setPointerCapture?.(e.pointerId);
e.preventDefault();
});
for (const handle of root.querySelectorAll("[data-ec-resize]")) {
handle.addEventListener("pointerdown", (e) => {
if (e.button !== 0) return;
dragMode = "resize-" + handle.dataset.ecResize;
pointer = capturePointer(e);
handle.setPointerCapture?.(e.pointerId);
e.preventDefault();
});
}
root.addEventListener("pointermove", (e) => {
if (!dragMode || !pointer) return;
const dx = e.clientX - pointer.x;
const dy = e.clientY - pointer.y;
if (dragMode === "move") {
layout.left = pointer.left + dx;
layout.top = pointer.top + dy;
} else {
const m = dragMode.slice(7); // remove "resize-"
if (m.includes("e")) layout.width = pointer.width + dx;
if (m.includes("s")) layout.height = pointer.height + dy;
if (m.includes("w")) {
layout.width = pointer.width - dx;
layout.left = pointer.left + dx;
}
if (m.includes("n")) {
layout.height = pointer.height - dy;
layout.top = pointer.top + dy;
}
}
applyLayout();
});
root.addEventListener("pointerup", () => {
if (dragMode) saveLayout();
dragMode = null;
pointer = null;
});
root.addEventListener("pointercancel", () => {
dragMode = null;
pointer = null;
});
}
function capturePointer(e) {
const rect = root.getBoundingClientRect();
return {
x: e.clientX, y: e.clientY,
left: layout.left ?? rect.left,
top: layout.top ?? rect.top,
width: layout.width ?? rect.width,
height: layout.height ?? rect.height,
};
}
// ───── F2 — History rendering ─────────────────────────────────────────────
function pushHistoryTurn(opts = {}) {
if (!currentTargetText && !opts.marker) return;
const entry = {
time: new Date().toTimeString().slice(0, 5),
target: currentTargetText.slice(0, 280),
source: currentSourceText.slice(0, 220),
lang: settings?.targetLanguage,
voice: settings?.realtimeVoice,
marker: opts.marker || null,
};
history.unshift(entry);
if (history.length > HISTORY_MAX) history.length = HISTORY_MAX;
currentTargetText = "";
renderHistory();
}
function renderHistory() {
if (!elements.history) return;
elements.history.replaceChildren();
if (!history.length) {
elements.history.hidden = true;
return;
}
elements.history.hidden = false;
for (const turn of history) {
if (turn.marker) {
const wrap = document.createElement("div");
wrap.className = "ec-h-marker";
const chip = document.createElement("span");
chip.className = "ec-h-marker-chip";
chip.textContent = turn.marker;
wrap.appendChild(chip);
elements.history.appendChild(wrap);
}
const item = document.createElement("div");
item.className = "ec-h-item";
const meta = document.createElement("span");
meta.className = "ec-h-meta";
meta.textContent = turn.time;
const text = document.createElement("span");
text.className = "ec-h-text";
text.textContent = turn.target;
item.append(meta, text);
elements.history.appendChild(item);
}
}
// ───── F3 — Source caption polling ────────────────────────────────────────
let lastSeenCaption = "";
function readYTCaptions() {
const segs = document.querySelectorAll(".ytp-caption-segment");
return Array.from(segs).map((s) => s.textContent).join(" ").trim().replace(/\s+/g, " ");
}
function startCaptionPoll() {
stopCaptionPoll();
lastSeenCaption = "";
captionPollTimer = setInterval(() => {
if (!settings?.showSource) return;
const text = readYTCaptions();
if (!text || text === lastSeenCaption) return;
lastSeenCaption = text;
currentSourceText = text;
if (elements.source) {
elements.source.textContent = text.slice(-220);
}
}, CAPTION_POLL_MS);
}
function stopCaptionPoll() {
if (captionPollTimer) {
clearInterval(captionPollTimer);
captionPollTimer = null;
}
}
function applySourceVisibility() {
if (!elements.source) return;
elements.source.hidden = !settings?.showSource;
}
// ───── F5 — captureStream re-acquisition with playback nudge ──────────────
function findVideo() {
return document.querySelector("video.html5-main-video") || document.querySelector("video");
}
// Live streams report duration === Infinity (or NaN before metadata).
// Non-live VOD has a finite duration. Used to skip the pause-then-play
// sync orchestration on live, where pausing would push the user out of
// the live edge into DVR mode permanently.
function isLive(video) {
return !video || !isFinite(video.duration);
}
function nudgePlay(video) {
if (!video.paused) return Promise.resolve();
const p = video.play();
if (!p?.then) return Promise.resolve();
return Promise.race([p.catch(() => {}), new Promise((r) => setTimeout(r, 250))]);
}
async function captureWithRetry(video, timeoutMs = 9000) {
if (typeof video.captureStream !== "function" && typeof video.mozCaptureStream !== "function") {
throw new Error("This Chrome build cannot capture YouTube audio.");
}
const start = Date.now();
let lastStream;
while (Date.now() - start < timeoutMs) {
if (video.paused) await nudgePlay(video);
lastStream = (video.captureStream || video.mozCaptureStream).call(video);
if (lastStream.getAudioTracks().length) {
return new MediaStream(lastStream.getAudioTracks());
}
lastStream.getTracks().forEach((t) => t.stop());
await new Promise((r) => setTimeout(r, 300));
}
throw new Error("YouTube audio not ready. Press play, then Start again.");
}
// ───── Kyma error parser ──────────────────────────────────────────────────
function parseKymaError(status, errText) {
try {
const parsed = JSON.parse(errText);
const err = parsed.error || {};
if (err.code === "insufficient_balance") {
const cta = err.cta_url || "https://kymaapi.com/billing";
return { user: "Out of Kyma balance.", cta, ctaLabel: "Top up" };
}
if (err.code === "too_many_sessions") {
return { user: "Three sessions already running. Stop one or wait." };
}
if (err.code === "upstream_error") {
return { user: "Provider unreachable. Try again shortly." };
}
if (err.code === "rate_limited") {
return { user: "Provider rate limit hit. Wait 30s." };
}
if (err.message) return { user: "Kyma " + status + ": " + err.message };
} catch {}
return { user: "Kyma " + status + ": " + (errText || "").slice(0, 160) };
}
// ───── Heartbeat + session timer (60-min cap, one-shot 55-min warning) ────
function startHeartbeat(kymaSessionId, kymaKey) {
stopHeartbeat();
if (!kymaSessionId || !kymaKey) return;
heartbeatTimer = setInterval(() => {
if (!session) return;
fetch(`${apiBase}/realtime/translations/sessions/${kymaSessionId}/heartbeat`, {
method: "POST",
headers: { Authorization: "Bearer " + kymaKey },
}).catch(() => {});
}, HEARTBEAT_MS);
}
function stopHeartbeat() {
if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
}
function startSessionTimer() {
clearSessionTimer();
warningShown = false;
warningTimer = setTimeout(() => {
if (warningShown) return;
warningShown = true;
showToast("Session ends in 5 min", 6000);
}, SESSION_WARNING_MS);
limitTimer = setTimeout(() => {
stopSession("auto-stop-60min");
emitEnded("Auto-stopped at 60 min — start again to continue.");
}, SESSION_LIMIT_MS);
}
function clearSessionTimer() {
if (warningTimer) { clearTimeout(warningTimer); warningTimer = null; }
if (limitTimer) { clearTimeout(limitTimer); limitTimer = null; }
}
// ───── End Kyma session (release collateral immediately, no 90s wait) ─────
async function endKymaSession(kymaSessionId, kymaKey) {
if (!kymaSessionId || !kymaKey) return;
try {
await fetch(`${apiBase}/realtime/translations/sessions/${kymaSessionId}/end`, {
method: "POST",
headers: { Authorization: "Bearer " + kymaKey },
keepalive: true,
});
} catch {}
}
// Waits for the PeerConnection to reach "connected" state, or resolves
// false on timeout / failure. Used to gate `video.play()` on the
// non-live Realtime sync flow so audio capture starts only once the
// WebRTC channel can actually accept it (SF6).
function waitForPCConnected(pc, timeoutMs = 3000) {
if (pc.connectionState === "connected") return Promise.resolve(true);
return new Promise((resolve) => {
let done = false;
const finish = (ok) => {
if (done) return;
done = true;
pc.removeEventListener("connectionstatechange", handler);
clearTimeout(timer);
resolve(ok);
};
const handler = () => {
if (pc.connectionState === "connected") finish(true);
else if (pc.connectionState === "failed" || pc.connectionState === "closed") finish(false);
};
const timer = setTimeout(() => finish(false), timeoutMs);
pc.addEventListener("connectionstatechange", handler);
});
}
// ───── Session core (build PeerConnection through Kyma → OpenAI) ─────────
async function buildRealtimeSession(token, audioStream, opts) {
const kymaKey = opts.kymaKey;
const lang = opts.targetLanguage || "vi";
const voice = opts.realtimeVoice || "";
setStatusText("Connecting");
setOverlayState("connecting");
let mintResp;
try {
mintResp = await fetch(`${apiBase}/realtime/translations/client_secrets`, {
method: "POST",
headers: { Authorization: "Bearer " + kymaKey, "Content-Type": "application/json" },
body: JSON.stringify({
session: {
model: "gpt-realtime-translate",
audio: { output: { language: lang, ...(voice ? { voice } : {}) } },
},
}),
});
} catch (e) {
throw new Error("Network error reaching Kyma.");
}
if (token !== pageToken) throw new Error("Stale session.");
if (!mintResp.ok) {
const text = await mintResp.text().catch(() => "");
const parsed = parseKymaError(mintResp.status, text);
const err = new Error(parsed.user);
err.cta = parsed.cta;
err.ctaLabel = parsed.ctaLabel;
throw err;
}
const mint = await mintResp.json();
if (token !== pageToken) throw new Error("Stale session.");
const clientSecret = mint.value;
const kymaSessionId = mint.kyma_session_id;
if (!clientSecret) throw new Error("Kyma response missing client_secret.");
const pc = new RTCPeerConnection();
for (const track of audioStream.getAudioTracks()) pc.addTrack(track, audioStream);
const dc = pc.createDataChannel("oai-events");
dc.addEventListener("message", (e) => {
if (token !== pageToken && session?.token !== token) return;
handleRealtimeEvent(e.data, token);
});
// Pre-create AudioContext + outputGain BEFORE registering ontrack, so
// the Voice volume slider has a valid target the moment the session
// is returned to startSession — even before the first remote audio
// track arrives (which can be 2-5s into a Realtime cold-start). The
// ontrack handler then just wires the remote stream into the existing
// graph. (SF3 fix.)
let preCtx = null;
let preGain = null;
try {
preCtx = new (window.AudioContext || window.webkitAudioContext)();
if (preCtx.state === "suspended") preCtx.resume().catch(() => {});
preGain = preCtx.createGain();
preGain.gain.value = computeGain(settings?.voiceVolume ?? 100);
preGain.connect(preCtx.destination);
} catch {
try { preCtx?.close(); } catch {}
preCtx = null;
preGain = null;
}
const newSession = {
token, pc, dc,
stream: audioStream,
remoteAudio: null,
audioCtx: preCtx,
outputGain: preGain,
kymaSessionId,
kymaKey,
targetLanguage: lang,
realtimeVoice: voice,
};
pc.addEventListener("track", (event) => {
if (newSession.remoteAudio) return;
const audio = document.createElement("audio");
audio.autoplay = true;
// Default to muted; flipped to false if we have to fall back to
// HTMLAudio playback (no Web Audio path or it's stuck suspended).
audio.muted = true;
audio.srcObject = event.streams[0];
document.body.appendChild(audio);
newSession.remoteAudio = audio;
const ctxRunning =
newSession.audioCtx &&
newSession.audioCtx.state !== "closed";
if (newSession.outputGain && ctxRunning) {
try {
const src = newSession.audioCtx.createMediaStreamSource(event.streams[0]);
src.connect(newSession.outputGain);
// Best-effort second resume in case ctx is still suspended at
// track time (some Chrome versions block initial resume until
// first node connect).
if (newSession.audioCtx.state === "suspended") {
newSession.audioCtx.resume().catch(() => {});
}
} catch {
// Web Audio wiring failed mid-flight. Tear down Web Audio path
// and play through the HTMLAudio element instead (capped at 1.0).
try { newSession.audioCtx.close(); } catch {}
newSession.audioCtx = null;
newSession.outputGain = null;
audio.muted = false;
audio.volume = Math.min((settings?.voiceVolume ?? 100) / 100, 1.0);
}
} else {
// No usable Web Audio context — HTMLAudio fallback.
if (newSession.audioCtx) { try { newSession.audioCtx.close(); } catch {} }
newSession.audioCtx = null;
newSession.outputGain = null;
audio.muted = false;
audio.volume = Math.min((settings?.voiceVolume ?? 100) / 100, 1.0);
}
});
pc.addEventListener("iceconnectionstatechange", () => {
if (token !== pageToken && session?.token !== token) return;
if (["closed", "failed", "disconnected"].includes(pc.iceConnectionState)) {
// Network drop or remote close
if (newSession === session) {
stopSession("connection-lost");
emitEnded("Connection lost.");
}
}
});
const offer = await pc.createOffer();
if (token !== pageToken) throw new Error("Stale session.");
await pc.setLocalDescription(offer);
const sdpResp = await fetch(OPENAI_CALLS_URL, {
method: "POST",
headers: { Authorization: "Bearer " + clientSecret, "Content-Type": "application/sdp" },
body: offer.sdp,
});
if (token !== pageToken) {
try { pc.close(); } catch {}
throw new Error("Stale session.");
}
if (!sdpResp.ok) {
const t = await sdpResp.text().catch(() => "");
try { pc.close(); } catch {}
void endKymaSession(kymaSessionId, kymaKey);
throw new Error(`SDP exchange ${sdpResp.status}: ${t.slice(0, 160)}`);
}
const answerSdp = await sdpResp.text();
if (token !== pageToken) {
try { pc.close(); } catch {}
throw new Error("Stale session.");
}
await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
return newSession;
}
function handleRealtimeEvent(raw, token) {
if (token !== pageToken && session?.token !== token) return;
let evt;
try { evt = JSON.parse(raw); } catch { return; }
if (evt.type === "error") {
setStatusText("Translation error");
return;
}
const isDelta =
evt.type === "session.output_transcript.delta" ||
evt.type === "response.audio_transcript.delta" ||
evt.type === "response.output_audio_transcript.delta" ||
(evt.type === "response.text.delta" && typeof evt.delta === "string");
if (isDelta && evt.delta) {
currentTargetText += evt.delta;
setTargetText(currentTargetText);
setOverlayState("live");
return;
}
const isDone =
evt.type === "session.output_transcript.done" ||
evt.type === "response.audio_transcript.done" ||
evt.type === "response.output_audio_transcript.done" ||
evt.type === "response.text.done";
if (isDone) {
if (evt.transcript) currentTargetText = evt.transcript;
setTargetText(currentTargetText);
pushHistoryTurn();
return;
}
}
function computeGain(voiceVolume) {
return voiceVolume === 0 ? 0 : (voiceVolume / 100) * VOICE_GAIN_MAX;
}
function applyVolumes(originalVolume, voiceVolume) {
// Original audio (the YT video element itself). Locate it on-demand so
// the slider has effect even before the user clicks Start — without this
// the popup felt frozen pre-session. videoEl global is set during an
// active session; otherwise findVideo() pulls the live YT element.
const video = videoEl || (typeof findVideo === "function" ? findVideo() : null);
if (video) {
const vol = Math.max(0, Math.min(1, (originalVolume ?? 18) / 100));
desiredOriginalVol = vol;
lastOriginalWriteAt = Date.now();
video.volume = vol;
video.muted = vol === 0;
}
// Voice (the translated dub). Web Audio GainNode with a brief ramp so
// rapid slider drags don't crackle. setValueAtTime + linearRampToValueAtTime
// is the documented way to schedule gain changes without pop artifacts.
// Only meaningful when a session is active and emitting dub audio.
if (session?.outputGain && session?.audioCtx) {
const target = computeGain(voiceVolume ?? 100);
const ctx = session.audioCtx;
const gain = session.outputGain.gain;
const now = ctx.currentTime;
try {
gain.cancelScheduledValues(now);
gain.setValueAtTime(gain.value, now);
gain.linearRampToValueAtTime(target, now + 0.04);
} catch {
// Older AudioContext implementations may reject scheduling — fall
// back to direct assignment which always works (just less smooth).
gain.value = target;
}
} else if (session?.remoteAudio) {
session.remoteAudio.volume = Math.min((voiceVolume ?? 100) / 100, 1.0);
session.remoteAudio.muted = voiceVolume === 0;
}
}
// SF3 — Hook video element's volumechange and snap back to our desired
// value when YouTube's player re-applies its own (ad insertion, video
// refresh, etc.). Bound when a session starts, unbound on stop. We
// ignore events fired within ~200ms of our own write to avoid a
// self-triggered feedback loop.
function bindVolumeDriftGuard(video) {
if (!video) return;
unbindVolumeDriftGuard();
onVolumeDrift = () => {
if (desiredOriginalVol < 0 || !video) return;
if (Date.now() - lastOriginalWriteAt < 200) return;
if (Math.abs(video.volume - desiredOriginalVol) > 0.01) {
lastOriginalWriteAt = Date.now();
video.volume = desiredOriginalVol;
video.muted = desiredOriginalVol === 0;
}
};
video.addEventListener("volumechange", onVolumeDrift);
}
function unbindVolumeDriftGuard() {
if (videoEl && onVolumeDrift) {
try { videoEl.removeEventListener("volumechange", onVolumeDrift); } catch {}
}
onVolumeDrift = null;
desiredOriginalVol = -1;
}
// SF8 Phase 1 — Listen to `ratechange` on the video element and toast a
// warning when playback is not 1×. Caller must invoke AFTER buildOverlay
// so showToast has a panel to render into.
function bindRateChangeWarn(video) {
if (!video) return;
unbindRateChangeWarn();
const warn = (rate) => {
if (Date.now() - lastRateToastAt < 4000) return;
lastRateToastAt = Date.now();
const r = Math.round(rate * 100) / 100;
showToast(
`Echoly works best at 1× speed (current: ${r}×). Translation may drift behind the speaker.`,
5000,
);
};
if (Math.abs(video.playbackRate - 1.0) > 0.01) warn(video.playbackRate);
onRateChange = () => {
if (!video) return;
if (Math.abs(video.playbackRate - 1.0) < 0.01) return;
warn(video.playbackRate);
};
video.addEventListener("ratechange", onRateChange);
}
function unbindRateChangeWarn() {
if (videoEl && onRateChange) {
try { videoEl.removeEventListener("ratechange", onRateChange); } catch {}
}
onRateChange = null;
}
// ───── F4 — Voice / language handover (zero-gap) ──────────────────────────
async function requestHandover(partial) {
if (!session) return;
const newSettings = { ...settings, ...partial };
const same =
newSettings.targetLanguage === session.targetLanguage &&
(newSettings.realtimeVoice || "") === (session.realtimeVoice || "");
if (same) return;
// Mark current turn into history with marker chip showing the change
const fromLang = LANG_NAME[session.targetLanguage] || session.targetLanguage;
const toLang = LANG_NAME[newSettings.targetLanguage] || newSettings.targetLanguage;
if (newSettings.targetLanguage !== session.targetLanguage) {
pushHistoryTurn({ marker: `${fromLang} → ${toLang}` });
setStatusText("Switching to " + toLang);
} else {
pushHistoryTurn({ marker: "Switching voice" });
setStatusText("Switching voice");
}
setOverlayState("connecting");
const newToken = ++pageToken;
settings = newSettings;
notifyBackground({ type: "UPDATE_SETTINGS", settings: newSettings });
if (elements.langSelect) elements.langSelect.value = newSettings.targetLanguage;
if (elements.voiceSelect) elements.voiceSelect.value = newSettings.realtimeVoice || "";
let newSession;
try {
newSession = await buildRealtimeSession(newToken, session.stream, {
kymaKey: settings.kymaKey,
targetLanguage: newSettings.targetLanguage,
realtimeVoice: newSettings.realtimeVoice,
});
if (newToken !== pageToken) {
// Yet another change came in; abandon this build
try { newSession.pc.close(); } catch {}
return;
}
} catch (err) {
if (newToken !== pageToken) return;
setStatusText("Switch failed — keeping current session");
setOverlayState("live");
showToast(err.message, { cta: err.cta, ctaLabel: err.ctaLabel }, 9000);
// Old session stays running — no swap performed
return;
}
// Swap: mute old, install new, close old
prevSession = session;
session = newSession;
setStatusText("Translating");
setOverlayState("live");
// Wait briefly for new audio track to arrive before muting old
setTimeout(() => {
if (prevSession) {
try {
if (prevSession.remoteAudio) {
prevSession.remoteAudio.pause();
prevSession.remoteAudio.srcObject = null;
prevSession.remoteAudio.remove();
}
if (prevSession.outputGain) prevSession.outputGain.disconnect();
if (prevSession.audioCtx) prevSession.audioCtx.close();
prevSession.pc?.close();
} catch {}
void endKymaSession(prevSession.kymaSessionId, prevSession.kymaKey);
prevSession = null;
}
}, 400);