// Shared by the browser and the local relay. Network reads never wait for JPEG decoding. const decoder = new TextDecoder(); const HEADER_END = new Uint8Array([13, 10, 13, 10]); class ByteQueue { constructor() { this.chunks = []; this.head = 0; this.offset = 0; this.length = 0; } append(bytes) { if (!(bytes instanceof Uint8Array)) throw new TypeError('Expected binary stream data.'); if (bytes.length) { this.chunks.push(bytes); this.length += bytes.length; } } indexOf(marker) { let matched = 0, position = 0; for (let c = this.head; c < this.chunks.length; c++) { const chunk = this.chunks[c]; for (let i = c === this.head ? this.offset : 0; i < chunk.length; i++, position++) { // The header delimiter has only a one-byte overlap (CR LF CR LF). if (chunk[i] !== marker[matched]) matched = chunk[i] === marker[0] ? 1 : 0; else matched++; if (matched === marker.length) return position - marker.length + 1; } } return -1; } read(length) { if (!Number.isSafeInteger(length) || length < 0 || length > this.length) throw new RangeError('Incomplete stream data.'); const result = new Uint8Array(length); let written = 0; while (written < length) { const chunk = this.chunks[this.head]; const count = Math.min(length - written, chunk.length - this.offset); result.set(chunk.subarray(this.offset, this.offset + count), written); written += count; this.offset += count; this.length -= count; if (this.offset === chunk.length) { this.head++; this.offset = 0; } } if (this.head === this.chunks.length) { this.chunks = []; this.head = 0; } else if (this.head >= 32) { this.chunks = this.chunks.slice(this.head); this.head = 0; } return result; } } export class MjpegParser { constructor(boundary, onFrame, { maxFrameBytes = 16 * 1024 * 1024, maxHeaderBytes = 16384 } = {}) { if (typeof boundary !== 'string' || !/^[\x21-\x7e]{1,150}$/.test(boundary) || /[\r\n]/.test(boundary)) throw new Error('Invalid MJPEG boundary.'); this.boundary = '--' + boundary; this.onFrame = onFrame; this.maxFrameBytes = maxFrameBytes; this.maxHeaderBytes = maxHeaderBytes; this.queue = new ByteQueue(); this.expected = null; this.metadata = null; this.frames = 0; } push(bytes) { this.queue.append(bytes); for (;;) { if (this.expected === null) { const at = this.queue.indexOf(HEADER_END); if (at < 0) { if (this.queue.length > this.maxHeaderBytes) throw new Error('实时流头部超过限制。'); return; } if (at > this.maxHeaderBytes) throw new Error('实时流头部超过限制。'); const header = decoder.decode(this.queue.read(at + HEADER_END.length)).replace(/^\r\n/, ''); if (!header.startsWith(this.boundary + '\r\n')) throw new Error('实时流边界无效。'); const lengths = [...header.matchAll(/(?:^|\r\n)Content-Length:\s*(\d+)\s*(?=\r\n)/ig)]; if (lengths.length !== 1) throw new Error('实时图像缺少有效长度信息。'); const size = Number(lengths[0][1]); if (!Number.isSafeInteger(size) || size <= 0 || size > this.maxFrameBytes) throw new Error('实时图像长度超过限制。'); const field = name => header.match(new RegExp('(?:^|\\r\\n)' + name + ':\\s*([^\\r\\n]+)', 'i'))?.[1]?.trim() || null; this.expected = size; this.metadata = { capturedUtc: field('X-Frame-Captured-Utc'), sequence: field('X-Frame-Sequence'), sourceWidth: field('X-Frame-Source-Width'), sourceHeight: field('X-Frame-Source-Height'), encodedUtc: field('X-Frame-Encoded-Utc'), encodeMs: field('X-Frame-Encode-Ms'), ageMs: field('X-Frame-Age-Ms'), headerReceivedAt: performance.now() }; } if (this.queue.length < this.expected) return; const jpeg = this.queue.read(this.expected); const metadata = this.metadata; this.expected = null; this.metadata = null; this.frames++; this.onFrame({ bytes: jpeg, ...metadata }); } } finish() { if (this.expected !== null) throw new Error('实时图像在接收完成前已断开。'); } } // Exactly one frame is being decoded and at most one newest frame is waiting. // Replacing the pending frame intentionally loses frames to keep control latency low. export class LatestFrameScheduler { constructor(render, onError = () => {}) { this.render = render; this.onError = onError; this.pending = null; this.active = false; this.closed = false; this.waiters = []; this.stats = { received: 0, rendered: 0, dropped: 0, decodeErrors: 0, renderMs: 0 }; } push(frame) { if (this.closed) return; this.stats.received++; if (this.pending) this.stats.dropped++; this.pending = frame; if (!this.active) this.pump(); } async pump() { this.active = true; try { while (!this.closed && this.pending) { const frame = this.pending; this.pending = null; const started = performance.now(); try { if (await this.render(frame) !== false && !this.closed) this.stats.rendered++; } catch (error) { this.stats.decodeErrors++; this.onError(error); } this.stats.renderMs = performance.now() - started; } } finally { this.active = false; for (const resolve of this.waiters.splice(0)) resolve(); } } stop() { this.closed = true; this.pending = null; } idle() { return this.active ? new Promise(resolve => this.waiters.push(resolve)) : Promise.resolve(); } metrics() { return { ...this.stats, decoding: this.active, pendingFrames: this.pending ? 1 : 0 }; } } export function boundaryFromContentType(contentType) { const match = contentType.match(/boundary\s*=\s*(?:"([^"]+)"|([^;\s]+))/i); if (!match) throw new Error('实时流格式无效。'); return match[1] || match[2]; }