private void DecodeElementaryStream(BitSplitter bs)
{
int marker = (int)bs.GetInteger(2);
if (marker != 2) throw new DemuxException("Invalid PES: first marker missing");
ReadFlags(bs);
if (bs.BitOffset != 0) throw new DemuxException("Alignment problem in PES (internal)");
HeaderLength = (int)bs.GetInteger(8);
int head_start = bs.ByteOffset;
if (HasPTS && HasDTS) {
ReadDTS_PTS(bs);
} else if (HasPTS) {
ReadPTS(bs);
}
if (HasESCR) bs.SkipBytes(6); // not currently used.
if (HasEsRate) bs.SkipBits(24); // not currently used.
if (UsesTrickMode) bs.SkipBytes(1); // ignored
if (MoreCopyright) bs.SkipBytes(1); // ignored
if (HasPesCRC) bs.SkipBytes(2); // ignored
if (HasPesExtension) ReadExtendedHeader(bs);
// skip anything that's left
int head_end = bs.ByteOffset;
int to_skip = HeaderLength - (head_end - head_start);
if (to_skip < 0) throw new DemuxException("Invalid PES: declared header length did not match measured length");
bs.SkipBytes(to_skip);
// Now, the remaining bytes are data and padding
int data_length = PacketLength - (HeaderLength + to_skip) - 3; // no idea where the '3' is coming from...
byte[] data = bs.RemainingBytes();
if (data.Length < data_length)
throw new DemuxException("Invalid PES: packet shorter than described");
/*if (data.Length != data_length)
throw new DemuxException("Possible issue: expect length != real length");*/
MemoryStream ms = new MemoryStream(data, 0, data_length);
FrameData = ms.ToArray();
}