// RTP/JPEG depacketizer (RFC 2435). A camera that streams MJPEG over RTSP sends each // frame as RTP packets carrying the JPEG *scan data* only, plus an 8-byte JPEG header // (type, Q, width/8, height/8) and, for Q >= 128, the quantization tables in-band. // The receiver rebuilds the JFIF headers (SOI, DQT, DRI, SOF0, standard DHT, SOS) in // front of the reassembled scan data. No decode, no re-encode: we only reframe bytes. // // MEASURED on park-lab (2026-11-17, Hikvision DS-2CD1043G2-LIU fw V5.8.10 and // DS-2CD1083G2-LIU fw V5.8.4, sub-stream 102 set to MJPEG 640×360): type 1 (4:2:0), // Q 48 / 63 (tables derived from Q, none in-band), no restart markers, the last packet // of every frame carries RTP padding. Frames rebuilt here decode cleanly. // See wiki/decisions/camera-live-view.md. /** Hard cap on one reassembled frame. A 640×360 MJPEG frame is ~15–30 KB; a frame * growing past this is a broken stream, not a big picture — drop it. */ export const MAX_FRAME_BYTES = 2 * 1024 * 1024; // Standard JPEG luma/chroma quantizers (ITU T.81 Annex K), in ZIGZAG order — which is // the order a DQT segment carries. RFC 2435 Appendix A scales these by Q. const LUMA_Q = [ 16, 11, 12, 14, 12, 10, 16, 14, 13, 14, 18, 17, 16, 19, 24, 40, 26, 24, 22, 22, 24, 49, 35, 37, 29, 40, 58, 51, 61, 60, 57, 51, 56, 55, 64, 72, 92, 78, 64, 68, 87, 69, 55, 56, 80, 109, 81, 87, 95, 98, 103, 104, 103, 62, 77, 113, 121, 112, 100, 120, 92, 101, 103, 99, ]; const CHROMA_Q = [ 17, 18, 18, 24, 21, 24, 47, 26, 26, 47, 99, 66, 56, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, ]; /** RFC 2435 Appendix A MakeTables: Q 1..99 → luma+chroma tables (128 bytes, zigzag). */ export function tablesForQ(q: number): Buffer { const qq = Math.min(99, Math.max(1, q)); const factor = qq < 50 ? Math.floor(5000 / qq) : 200 - qq * 2; const scale = (v: number) => Math.min(255, Math.max(1, Math.floor((v * factor + 50) / 100))); return Buffer.from([...LUMA_Q.map(scale), ...CHROMA_Q.map(scale)]); } // Standard Huffman tables (ITU T.81 K.3), the ones RFC 2435 mandates. const DC_LUMA_BITS = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; const DC_CHROMA_BITS = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; const DC_VALS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; const AC_LUMA_BITS = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; const AC_LUMA_VALS = Buffer.from( "01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9fa", "hex", ); const AC_CHROMA_BITS = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; const AC_CHROMA_VALS = Buffer.from( "000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9fa", "hex", ); function dht(tableClass: number, id: number, bits: number[], vals: ArrayLike): Buffer { const len = 3 + bits.length + vals.length; return Buffer.from([0xff, 0xc4, len >> 8, len & 0xff, (tableClass << 4) | id, ...bits, ...Array.from(vals)]); } const HUFFMAN = Buffer.concat([ dht(0, 0, DC_LUMA_BITS, DC_VALS), dht(1, 0, AC_LUMA_BITS, AC_LUMA_VALS), dht(0, 1, DC_CHROMA_BITS, DC_VALS), dht(1, 1, AC_CHROMA_BITS, AC_CHROMA_VALS), ]); /** Build the JFIF headers that precede the scan data (RFC 2435 Appendix B). */ export function jpegHeader(type: number, width: number, height: number, qtables: Buffer, dri: number): Buffer { const parts: Buffer[] = [Buffer.from([0xff, 0xd8])]; const tableCount = Math.floor(qtables.length / 64); for (let i = 0; i < tableCount; i++) { parts.push(Buffer.from([0xff, 0xdb, 0, 67, i]), qtables.subarray(i * 64, i * 64 + 64)); } if (dri) parts.push(Buffer.from([0xff, 0xdd, 0, 4, dri >> 8, dri & 0xff])); // Type 0 = 4:2:2 (luma 2×1), type 1 = 4:2:0 (luma 2×2); types 64/65 = same + restart markers. const lumaSampling = (type & 0x3f) === 0 ? 0x21 : 0x22; const chromaTable = tableCount > 1 ? 1 : 0; parts.push( Buffer.from([ 0xff, 0xc0, 0, 17, 8, height >> 8, height & 0xff, width >> 8, width & 0xff, 3, 1, lumaSampling, 0, 2, 0x11, chromaTable, 3, 0x11, chromaTable, ]), ); parts.push(HUFFMAN); parts.push(Buffer.from([0xff, 0xda, 0, 12, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0])); return Buffer.concat(parts); } /** The RTP fixed header + CSRCs + optional extension; returns the payload (padding stripped). */ export function rtpPayload(packet: Buffer): { payload: Buffer; marker: boolean; seq: number } | null { if (packet.length < 12 || packet[0]! >> 6 !== 2) return null; const csrc = packet[0]! & 0x0f; let offset = 12 + csrc * 4; if (packet[0]! & 0x10) { if (packet.length < offset + 4) return null; offset += 4 + packet.readUInt16BE(offset + 2) * 4; } let end = packet.length; if (packet[0]! & 0x20) end -= packet[packet.length - 1]!; if (end < offset) return null; return { payload: packet.subarray(offset, end), marker: (packet[1]! & 0x80) !== 0, seq: packet.readUInt16BE(2) }; } /** * Reassembles RTP/JPEG packets into complete JPEG frames. Feed every RTP packet of the * video track to `push`; it returns a finished frame on the packet carrying the marker * bit, else null. A lost packet (sequence gap or fragment offset mismatch) drops the * frame in progress — the next frame starts clean. Memory is bounded by MAX_FRAME_BYTES. */ export class JpegDepacketizer { #chunks: Buffer[] = []; #size = 0; #expectOffset = 0; #lastSeq: number | null = null; #header: Buffer | null = null; /** Q-derived tables are the same every frame; cache the last Q's. */ #qCache: { q: number; tables: Buffer } | null = null; /** Frames dropped for loss/overflow (diagnostic). */ dropped = 0; push(packet: Buffer): Buffer | null { const rtp = rtpPayload(packet); if (!rtp) return null; const { payload, marker, seq } = rtp; const gap = this.#lastSeq !== null && ((this.#lastSeq + 1) & 0xffff) !== seq; this.#lastSeq = seq; if (gap) this.#reset(true); if (payload.length < 8) return null; const fragOffset = payload.readUIntBE(1, 3); const type = payload[4]!; const q = payload[5]!; const width = payload[6]! * 8; const height = payload[7]! * 8; let pos = 8; let dri = 0; if (type >= 64 && type <= 127) { if (payload.length < pos + 4) return null; dri = payload.readUInt16BE(pos); pos += 4; } if (fragOffset === 0) { if (this.#chunks.length > 0) this.#reset(true); // previous frame never finished let tables: Buffer; if (q >= 128) { if (payload.length < pos + 4) return null; const len = payload.readUInt16BE(pos + 2); pos += 4; if (len === 0 || payload.length < pos + len) return null; // tables "sent earlier": unsupported tables = Buffer.from(payload.subarray(pos, pos + len)); pos += len; } else { if (this.#qCache?.q !== q) this.#qCache = { q, tables: tablesForQ(q) }; tables = this.#qCache.tables; } this.#header = jpegHeader(type, width, height, tables, dri); this.#expectOffset = 0; } else if (!this.#header || fragOffset !== this.#expectOffset) { // Joined mid-frame, or a fragment went missing: wait for the next frame start. if (this.#header) this.#reset(true); return null; } const data = payload.subarray(pos); this.#size += data.length; if (this.#size > MAX_FRAME_BYTES) { this.#reset(true); return null; } this.#chunks.push(Buffer.from(data)); this.#expectOffset = fragOffset + data.length; if (!marker) return null; const body = Buffer.concat(this.#chunks, this.#size); const header = this.#header!; this.#reset(false); const hasEoi = body.length >= 2 && body[body.length - 2] === 0xff && body[body.length - 1] === 0xd9; return Buffer.concat(hasEoi ? [header, body] : [header, body, Buffer.from([0xff, 0xd9])]); } #reset(dropped: boolean): void { if (dropped && this.#chunks.length > 0) this.dropped++; this.#chunks = []; this.#size = 0; this.#expectOffset = 0; this.#header = null; } }