-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch.html
More file actions
472 lines (427 loc) · 19.3 KB
/
watch.html
File metadata and controls
472 lines (427 loc) · 19.3 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
<!DOCTYPE html>
<html><head><title>Watch Live Stream</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
* { box-sizing: border-box; }
body { margin: 0; background: #111; color: #eee; font-family: monospace; }
video { display: block; width: 100%; max-height: 72vh; background: #000; }
#bar { padding: 6px 8px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; background: #1a1a1a; border-top: 1px solid #333; }
#scrubRow { width: 100%; display: flex; align-items: center; gap: 6px; }
#scrub { flex: 1; cursor: pointer; }
#timeInfo { font-size: 11px; color: #aaa; white-space: nowrap; min-width: 80px; text-align: right; }
#playPos { font-size: 11px; color: #aaa; white-space: nowrap; min-width: 32px; }
button { background: #333; color: #eee; border: 1px solid #555; padding: 4px 10px; cursor: pointer; border-radius: 3px; font-family: monospace; }
button:hover { background: #444; }
#liveBtn { background: #600; border-color: #c44; }
#liveBtn.on { background: #c00; border-color: #f88; animation: pulse 1.5s ease-in-out infinite; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.65} }
#status { font-size: 11px; color: #888; padding: 3px 8px; }
#setup { padding: 12px; font-size: 13px; }
#setup input { width: 420px; max-width: 90vw; font-family: monospace; background: #222; color: #eee; border: 1px solid #555; padding: 4px; }
#dbg { margin: 6px 8px; padding: 6px; background: #0a0a0a; border: 1px solid #333; font-size: 10px; color: #8f8; min-height: 32px; max-height: 180px; overflow-y: auto; white-space: pre-wrap; word-break: break-all; }
</style>
</head>
<body>
<video id=v controls autoplay playsinline></video>
<div id=bar>
<button id=liveBtn>▶ Live</button>
<div id=scrubRow>
<span id=playPos>0s</span>
<input type=range id=scrub min=0 max=0 value=0>
<span id=timeInfo></span>
</div>
</div>
<div id=status>Waiting for stream...</div>
<div id=dbg></div>
<div id=setup>
Stream path: <input id=streamInput placeholder="stream/pubkey/stream-id">
<button id=loadBtn>Load</button>
<br><small style="color:#666">or open as watch.html?v=stream/pubkey/stream-id</small>
</div>
<script>
(function() {
const dbg = document.getElementById('dbg');
const _log = console.log.bind(console);
console.log = function(...args) {
_log(...args);
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
dbg.textContent += line + '\n';
dbg.scrollTop = dbg.scrollHeight;
};
console.log('dbg ready | MSE=' + !!window.MediaSource);
})();
const video = document.getElementById('v');
const liveBtn = document.getElementById('liveBtn');
const scrub = document.getElementById('scrub');
const timeInfo = document.getElementById('timeInfo');
const playPos = document.getElementById('playPos');
const statusEl = document.getElementById('status');
const setup = document.getElementById('setup');
let mime = ''; // recorder mime type from cues.json header line
let cues = []; // [{o: byteOffset, t: ms from recording start}]
let videoBase = ''; // http://host/stream/pk/id
let cuesUrl = ''; // videoBase + '.cues.json'
let liveMode = true;
// MSE state — one MediaSource per playback session (seek creates a new one)
let ms = null; // current MediaSource
let sb = null; // current SourceBuffer
let sbQueue = []; // ArrayBuffers / Uint8Arrays waiting to be appended
let streamCtrl = null; // AbortController for the current fetch stream
function status(msg) { statusEl.textContent = msg; }
// -- URL / setup ---------------------------------------------------------------
function initFromPath(path) {
path = path.trim();
if (!path.startsWith('stream/')) path = 'stream/' + path;
videoBase = `${location.protocol}//${location.host}/${path}`;
cuesUrl = videoBase + '.cues.json';
document.getElementById('streamInput').value = path.replace(/^stream\//, '');
setup.hidden = true;
status('fetching cues...');
pollCues();
}
(() => {
const params = new URLSearchParams(location.search);
const v = params.get('v') || location.hash.replace(/^#/, '');
if (v) { initFromPath(v); return; }
setup.hidden = false;
})();
document.getElementById('loadBtn').onclick = () => {
const v = document.getElementById('streamInput').value.trim();
if (v) initFromPath(v);
};
// -- Cue polling ---------------------------------------------------------------
// The server keeps the HTTP connection open after sending all available data.
// We detect "end of available data" by aborting 180 ms after the last chunk.
async function fetchCuesText() {
if (!cuesUrl) return '';
const ctrl = new AbortController();
let silenceTimer;
const resetSilence = () => {
clearTimeout(silenceTimer);
silenceTimer = setTimeout(() => ctrl.abort(), 180);
};
const chunks = [];
try {
const r = await fetch(cuesUrl, { signal: ctrl.signal, cache: 'no-store' });
if (!r.ok) { ctrl.abort(); return ''; }
const reader = r.body.getReader();
resetSilence();
while (true) {
const { done, value } = await reader.read().catch(() => ({ done: true }));
if (done) break;
chunks.push(value);
resetSilence();
}
} catch(e) { /* AbortError expected */ }
clearTimeout(silenceTimer);
if (!chunks.length) return '';
const total = chunks.reduce((s, c) => s + c.length, 0);
const all = new Uint8Array(total);
let pos = 0;
for (const c of chunks) { all.set(c, pos); pos += c.length; }
return new TextDecoder().decode(all);
}
function parseCues(text) {
const newCues = [];
let newMime = '';
for (const line of text.split('\n')) {
// NUL bytes mark the end of written data in the server's zero-padded block
if (!line || line.charCodeAt(0) === 0) break;
try {
const obj = JSON.parse(line);
if (obj.mime) newMime = obj.mime;
if (obj.o !== undefined) newCues.push({ o: obj.o, t: obj.t });
} catch(e) { /* partial last line — ignore */ }
}
let changed = false;
if (newMime && newMime !== mime) { mime = newMime; changed = true; }
if (newCues.length > cues.length) { cues = newCues; changed = true; }
return changed;
}
async function pollCues() {
if (!cuesUrl) return;
try {
const text = await fetchCuesText();
if (text && parseCues(text)) onCuesUpdated();
} catch(e) {}
setTimeout(pollCues, 2500);
}
function onCuesUpdated() {
if (!cues.length) return;
const durSec = cues[cues.length - 1].t / 1000;
scrub.max = Math.max(0, cues.length - 1);
timeInfo.textContent = `${durSec.toFixed(0)}s recorded`;
status(`${cues.length} keyframes | ${mime || '...'}`);
// Keep MS duration in sync as the recording grows
if (ms && ms.readyState === 'open') {
try { ms.duration = durSec; } catch(e) {}
}
if (liveMode && cues.length >= 2) {
scrub.value = cues.length - 1;
if (!ms) playFromCue(cues.length - 1); // initial start; stream loop handles the rest
}
}
// -- Scrubber / live button ----------------------------------------------------
let scrubActive = false;
scrub.addEventListener('mousedown', () => { scrubActive = true; });
scrub.addEventListener('input', () => {
liveMode = false;
liveBtn.classList.remove('on');
const idx = +scrub.value;
if (cues[idx]) playPos.textContent = `${(cues[idx].t / 1000).toFixed(0)}s`;
});
scrub.addEventListener('change', () => {
scrubActive = false;
const idx = +scrub.value;
if (cues[idx]) playFromCue(idx);
});
liveBtn.onclick = () => {
liveMode = true;
liveBtn.classList.add('on');
if (cues.length >= 2) {
scrub.value = cues.length - 1;
playFromCue(cues.length - 1);
}
};
video.addEventListener('timeupdate', () => {
if (scrubActive) return;
playPos.textContent = `${video.currentTime.toFixed(0)}s`;
if (liveMode && cues.length) {
const ms_ = video.currentTime * 1000;
for (let i = cues.length - 1; i >= 0; i--) {
if (cues[i].t <= ms_) { scrub.value = i; break; }
}
}
});
// -- Find true init-segment boundary ------------------------------------------
// MSE only wants EBML+SeekHead+Info+Tracks — no Cluster data.
// Walk the EBML structure properly so we don't match 1F43B675 inside element
// bodies (e.g. VP9 CodecPrivate data can contain those bytes by coincidence).
function findFirstCluster(buf) {
const b = new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer, buf.byteOffset || 0);
const n = b.length;
function u32(i) { return ((b[i]<<24)|(b[i+1]<<16)|(b[i+2]<<8)|b[i+3])>>>0; }
// EBML variable-length integer; returns {val, len}, val===-1 means unknown size
function vint(i) {
if (i >= n) return null;
const v = b[i];
let w, val;
if (v&0x80){w=1;val=v&0x7f; if(val===0x7f) val=-1;}
else if (v&0x40){w=2;val=((v&0x3f)<<8)|b[i+1]; if(val===0x3fff) val=-1;}
else if (v&0x20){w=3;val=((v&0x1f)<<16)|(b[i+1]<<8)|b[i+2]; if(val===0x1fffff) val=-1;}
else if (v&0x10){w=4;val=((v&0x0f)<<24)|(b[i+1]<<16)|(b[i+2]<<8)|b[i+3]; if(val===0x0fffffff) val=-1;}
else {w=8;val=-1;} // 5-8 byte VINTs treated as unknown
if (i+w > n) return null;
return {val, len:w};
}
let pos = 0;
// Skip EBML header element (1A 45 DF A3)
if (pos+4 > n || u32(pos) !== 0x1A45DFA3) return n;
pos += 4;
const es = vint(pos); if (!es || es.val < 0) return n;
pos += es.len + es.val;
// Segment element (18 53 80 67)
if (pos+4 > n || u32(pos) !== 0x18538067) return n;
pos += 4;
const ss = vint(pos); if (!ss) return n;
pos += ss.len; // enter Segment body
// Walk top-level Segment elements — all use 4-byte IDs (start with 0x1x)
while (pos+4 < n) {
const eid = u32(pos);
if (eid === 0x1F43B675) return pos; // Cluster
pos += 4;
const sz = vint(pos);
if (!sz || sz.val < 0) return pos - 4; // unknown-size element = Cluster
pos += sz.len + sz.val;
}
return n;
}
// -- MKV → WebM header patch ---------------------------------------------------
// MSE requires DocType="webm"; live recordings often carry DocType="matroska".
// The container structure is identical — only that 11-byte element differs.
// We replace: 42 82 88 "matroska" (DocType, len=8, "matroska")
// with: 42 82 84 "webm" EC 82 00 00 (DocType, len=4, "webm" + 4-byte EBML Void)
// Total bytes: 11 → 11, so no offsets elsewhere in the file change.
function hexDump(buf, n) {
const b = new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer, buf.byteOffset || 0, Math.min(n, buf.byteLength || buf.length));
return Array.from(b).map(x => x.toString(16).padStart(2,'0')).join(' ');
}
function patchMkvToWebm(buf) {
const src = buf instanceof ArrayBuffer ? buf : buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
const b = new Uint8Array(src);
const hexStr = hexDump(b, 16);
console.log('init[0..15]: ' + hexStr);
status('init[0..15]: ' + hexStr);
for (let i = 0; i < Math.min(b.length - 11, 128); i++) {
if (b[i] === 0x42 && b[i+1] === 0x82 && b[i+2] === 0x88 &&
b[i+3] === 0x6D && b[i+4] === 0x61 && b[i+5] === 0x74 && // "mat"
b[i+6] === 0x72 && b[i+7] === 0x6F && b[i+8] === 0x73 && // "ros"
b[i+9] === 0x6B && b[i+10] === 0x61) { // "ka"
const p = new Uint8Array(src.slice(0));
p[i+2] = 0x84; // DocType length = 4
p[i+3] = 0x77; p[i+4] = 0x65; // "we"
p[i+5] = 0x62; p[i+6] = 0x6D; // "bm"
p[i+7] = 0xEC; // EBML Void element ID
p[i+8] = 0x82; // Void size VINT = 2
p[i+9] = 0x00; p[i+10] = 0x00; // Void payload
console.log('patched matroska→webm at byte ' + i);
status('patched matroska→webm at byte ' + i);
return p.buffer;
}
}
console.log('no matroska DocType found — passing through as-is');
status('no matroska DocType found — passing through as-is');
return src;
}
// -- SourceBuffer append queue -------------------------------------------------
// appendBuffer is async; only one call may be in flight at a time.
function sbEnqueue(data) {
sbQueue.push(data);
sbDrain();
}
function sbDrain() {
if (!sb || sb.updating || !sbQueue.length) return;
try {
sb.appendBuffer(sbQueue[0]);
sbQueue.shift();
} catch(e) {
if (e.name === 'QuotaExceededError' && video.currentTime > 15) {
// Evict everything more than 10 s behind the playhead; retry on updateend.
sb.remove(0, video.currentTime - 10);
} else {
sbQueue.shift(); // drop on unexpected errors
}
}
}
// -- Playback (MSE streaming) --------------------------------------------------
// Each seek creates a fresh MediaSource + SourceBuffer. The init segment is
// fetched once as a small range request; then a streaming fetch loop delivers
// data chunks directly into the SourceBuffer with no intermediate blobs.
// When the server closes the connection (its range-response cap) the loop
// immediately re-fetches from the current byte offset — the browser never
// sees a gap in the buffer.
async function playFromCue(cueIdx) {
if (!videoBase || cues.length < 2) return;
if (streamCtrl) { streamCtrl.abort(); streamCtrl = null; }
liveBtn.classList.toggle('on', liveMode);
scrub.value = cueIdx;
const targetSec = cues[cueIdx].t / 1000;
playPos.textContent = `${targetSec.toFixed(0)}s`;
const initEnd = cues[1].o; // cues[0].o is always 0 (file start); cues[1].o is first cluster
const lookback = liveMode ? 2 : 1;
const startOff = cues[Math.max(0, cueIdx - lookback)].o;
console.log(`playFromCue ${cueIdx} initEnd=${initEnd} startOff=${startOff} mime="${mime}" MSE=${!!window.MediaSource}`);
status(`loading from ${targetSec.toFixed(1)}s...`);
if (!window.MediaSource) {
console.log('MediaSource not available on this browser');
status('MediaSource not supported');
return;
}
const thisMsRef = new MediaSource();
ms = thisMsRef;
sb = null;
sbQueue = [];
const prevSrc = video.src;
video.src = URL.createObjectURL(thisMsRef);
// Revoke the *previous* blob URL only; the new one must stay alive until
// the browser resolves it (sourceopen), otherwise code=4 fires immediately.
if (prevSrc && prevSrc.startsWith('blob:')) URL.revokeObjectURL(prevSrc);
thisMsRef.addEventListener('sourceopen', async () => {
if (ms !== thisMsRef) { status('MSE: superseded'); return; }
let mimeType = (mime || 'video/webm').replace('video/x-matroska', 'video/webm');
const supported = MediaSource.isTypeSupported(mimeType);
console.log(`MSE open | mime="${mimeType}" supported=${supported} initEnd=${initEnd}`);
status(`MSE open | mime="${mimeType}" supported=${supported} initEnd=${initEnd}`);
if (!supported) mimeType = 'video/webm';
try {
sb = thisMsRef.addSourceBuffer(mimeType);
} catch(e) {
status('addSourceBuffer failed: ' + e.message);
return;
}
sb.addEventListener('updateend', sbDrain);
try { thisMsRef.duration = cues[cues.length - 1].t / 1000; } catch(e) {}
const ctrl = new AbortController();
streamCtrl = ctrl;
const sig = ctrl.signal;
status(`fetching init bytes=0-${initEnd - 1}`);
try {
const r = await fetch(videoBase, {
headers: { Range: `bytes=0-${initEnd - 1}` },
signal: sig,
});
if (!r.ok || sig.aborted) { status(`init fetch failed: ${r.status}`); return; }
const initBuf = await r.arrayBuffer();
// Strip cluster data — MSE init segment must be headers-only.
const clusterOff = findFirstCluster(initBuf);
const initOnly = initBuf.slice(0, clusterOff);
// Ensure streaming starts at a cluster boundary, not inside headers.
if (startOff < clusterOff) startOff = clusterOff;
console.log(`init ${initOnly.byteLength}b (cluster at ${clusterOff}), streaming from ${startOff}`);
status(`init ${initOnly.byteLength}b (cluster@${clusterOff}), streaming from ${startOff}`);
sbEnqueue(patchMkvToWebm(initOnly));
} catch(e) { status('init fetch error: ' + e.message); return; }
// Once the browser has parsed the codec metadata, seek and play.
video.addEventListener('loadedmetadata', () => {
if (ms !== thisMsRef) return;
status(`loadedmetadata, seeking to ${targetSec.toFixed(1)}s`);
video.currentTime = targetSec;
video.play().catch(e => status('play() error: ' + e.message));
}, { once: true });
// Stream data chunks directly into the SourceBuffer.
await streamData(thisMsRef, startOff, sig);
}, { once: true });
video.addEventListener('error', () => {
const e = video.error;
const msg = 'video error code=' + (e && e.code) + ' ' + (e && e.message);
console.log(msg);
status(msg);
}, { once: true });
}
async function streamData(thisMsRef, off, sig) {
// Cue offsets are MediaRecorder chunk boundaries, not Cluster boundaries.
// Scan the first bytes we receive for the Cluster element ID (1F 43 B6 75)
// and discard everything before it so MSE never sees a partial Cluster.
let synced = false;
while (!sig.aborted && ms === thisMsRef) {
if (thisMsRef.readyState !== 'open') break;
let r;
try {
r = await fetch(videoBase, {
headers: { Range: `bytes=${off}-${off + 0x3FFFFFF}` },
signal: sig,
});
} catch(e) { break; }
if (!r.ok || sig.aborted) break;
const reader = r.body.getReader();
while (true) {
let chunk;
try { chunk = await reader.read(); } catch(e) { break; }
if (chunk.done || sig.aborted) break;
off += chunk.value.byteLength;
let data = chunk.value;
if (!synced) {
// Find first Cluster ID in this chunk
let cp = -1;
for (let i = 0; i < data.length - 3; i++) {
if (data[i]===0x1F && data[i+1]===0x43 && data[i+2]===0xB6 && data[i+3]===0x75) {
cp = i; break;
}
}
if (cp < 0) continue; // no cluster yet — discard and keep reading
console.log(`synced cluster at stream byte ${off - data.length + cp}`);
data = data.slice(cp);
synced = true;
}
sbEnqueue(data.slice());
}
if (sig.aborted) break;
// Server closed the connection. If we haven't reached the last known
// keyframe yet, re-fetch immediately. Otherwise wait for new cues.
const lastKnownOff = cues.length ? cues[cues.length - 1].o : 0;
if (off <= lastKnownOff) continue;
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
</script>
</body></html>