UNPKG

mpegts-demuxer

Version:

Demuxes an MPEG Transport Stream into elementary packets.

79 lines (59 loc) 1.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MpegTsDemuxer = void 0; var _stream = require("stream"); var _constants = require("./constants"); var _classes = require("./classes"); var _utils = require("./utils"); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } class MpegTsDemuxer extends _stream.Transform { constructor() { super({ readableObjectMode: true, flush: callback => { this.finalize(); callback(); }, transform: (chunk, encoding, callback) => { this.process(chunk); callback(); } }); _defineProperty(this, "pids", new Map()); _defineProperty(this, "pmt", new _classes.Pmt()); _defineProperty(this, "unprocessed", Buffer.alloc(0)); _defineProperty(this, "cb", p => { this.push(p); }); } process(chunk) { const { pmt, pids, cb } = this; // Add the chunk to the unprocessed data this.unprocessed = Buffer.concat([this.unprocessed, chunk]); const mem = (0, _utils.getSafeDataView)(this.unprocessed); // Loop through all the data let ptr = 0; while (this.unprocessed.length - ptr >= _constants.PACKET_LEN) { // Demux packet will return the number of bytes it has analyzed, or zero if a full // packet was consumed const consumedBytes = (0, _utils.demuxPacket)(pmt, mem, ptr, pids, cb, false) || _constants.PACKET_LEN; ptr += consumedBytes; } this.unprocessed = this.unprocessed.slice(ptr); } finalize() { const { pids, cb } = this; pids.forEach(s => { const packet = s.finalize(); if (packet) cb(packet); }); } } exports.MpegTsDemuxer = MpegTsDemuxer;