ebml-stream
Version:
Ebml parser and encoder
94 lines (93 loc) • 2.86 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
const EbmlTagPosition_1 = require("./models/enums/EbmlTagPosition");
const EbmlTagId_1 = require("./models/enums/EbmlTagId");
class EbmlStreamEncoder extends stream_1.Transform {
constructor(options = {}) {
super(Object.assign({}, options, { writableObjectMode: true }));
this.dataBuffer = Buffer.alloc(0);
this.mCorked = false;
this.openTags = [];
}
_transform(chunk, enc, done) {
if (chunk) {
if (!chunk.id) {
throw new Error(`No id found for ${JSON.stringify(chunk)}`);
}
switch (chunk.position) {
case EbmlTagPosition_1.EbmlTagPosition.Start:
this.startTag(chunk);
break;
case EbmlTagPosition_1.EbmlTagPosition.Content:
this.writeTag(chunk);
break;
case EbmlTagPosition_1.EbmlTagPosition.End:
this.endTag(chunk);
break;
default:
break;
}
}
done();
}
bufferAndFlush(buffer) {
this.dataBuffer = Buffer.concat([this.dataBuffer, buffer]);
this._flush(() => { });
}
_flush(callback) {
let chunk = null;
if (this.dataBuffer.length > 0 && !this.mCorked) {
chunk = Buffer.from(this.dataBuffer);
this.dataBuffer = Buffer.alloc(0);
this.push(chunk);
}
callback();
}
_bufferAndFlush(buffer) {
this.bufferAndFlush(buffer);
}
flush() {
this._flush(() => { });
}
get buffer() {
return this.dataBuffer;
}
set buffer(val) {
this.dataBuffer = val;
}
get stack() {
return this.openTags;
}
cork() {
this.mCorked = true;
}
uncork() {
this.mCorked = false;
this._flush(() => { });
}
writeTag(tag) {
if (this.openTags.length > 0) {
this.openTags[this.openTags.length - 1].Children.push(tag);
}
else {
this.bufferAndFlush(tag.encode());
}
}
startTag(tag) {
if (this.openTags.length > 0) {
this.openTags[this.openTags.length - 1].Children.push(tag);
}
this.openTags.push(tag);
}
endTag(tag) {
const inMemoryTag = this.openTags.pop();
if (tag.id !== inMemoryTag.id) {
throw `Logic error - closing tag "${EbmlTagId_1.EbmlTagId[tag.id]}" is not expected tag "${EbmlTagId_1.EbmlTagId[inMemoryTag.id]}"`;
}
if (this.openTags.length < 1) {
this.bufferAndFlush(inMemoryTag.encode());
}
}
}
exports.EbmlStreamEncoder = EbmlStreamEncoder;