Code
·
268 lines
·
9064 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xtremegaida.DataStructures;
namespace MediaContainers.Matroska;
public class MatroskaReader : IDisposable
{
private static readonly EBMLDocType[] docTypes = new EBMLDocType[]
{
new EBMLDocType("matroska", 4, 4),
new EBMLDocType("webm", 4, 4),
};
private readonly DataBufferCache cache;
private readonly EBMLDocumentReader document;
private readonly MatroskaSeekHead seekHead = new();
private readonly MatroskaInfo info = new();
private readonly MatroskaTracks tracks = new();
private readonly MatroskaTags tags = new();
private readonly MatroskaCues cues = new();
private readonly DataQueueMemoryReaderMutable memoryReader = new();
private readonly byte[] readBytes = new byte[8];
private MatroskaTrackEntry[] trackByNumber;
private Queue<MatroskaFrame> frameQueue;
private long clusterTimestamp;
private int scanIndex;
private int minTrackNumber;
private int[] lacingSizes;
private bool readTrackInfo;
private volatile bool disposed;
public virtual EBMLDocType[] SupportedDocTypes => docTypes;
public EBMLDocumentReader Document => document;
public MatroskaSeekHead SeekHead => seekHead;
public MatroskaInfo Info => info;
public MatroskaTracks Tracks => tracks;
public MatroskaTags Tags => tags;
public MatroskaCues Cues => cues;
static MatroskaReader()
{
MatroskaSpecification.RegisterFormat();
}
public MatroskaReader(EBMLDocumentReader doc, DataBufferCache cache = null)
{
if (doc == null) { throw new ArgumentNullException(nameof(doc)); }
var docTypes = SupportedDocTypes;
var canRead = false;
for (int i = docTypes.Length - 1; i >= 0; i--)
{
if (doc.CanBeReadBy(docTypes[i])) { canRead = true; break; }
}
if (!canRead)
{
throw new ArgumentException("Unsupported DocType: " + doc.Header.DocType + " " + doc.Header.DocTypeReadVersion, nameof(doc));
}
document = doc;
if (doc.Body.Definition != MatroskaSpecification.Segment)
{
throw new ArgumentException("Expected Segment as document body", nameof(doc));
}
this.cache = cache ?? DataBufferCache.DefaultCache;
}
public static async ValueTask<MatroskaReader> Read(IDataQueueReader reader, bool keepReaderOpen = false,
DataBufferCache cache = null, CancellationToken cancellationToken = default)
{
var doc = await EBMLDocumentReader.Read(reader, keepReaderOpen, cache, cancellationToken);
var matroska = new MatroskaReader(doc, cache);
await matroska.ReadTrackInfo(cancellationToken);
return matroska;
}
public static async ValueTask<MatroskaReader> Read(Stream stream, bool keepStreamOpen = false,
DataBufferCache cache = null, CancellationToken cancellationToken = default)
{
var doc = await EBMLDocumentReader.Read(stream, keepStreamOpen, cache, cancellationToken);
var matroska = new MatroskaReader(doc, cache);
await matroska.ReadTrackInfo(cancellationToken);
return matroska;
}
public static bool CanReadDocument(EBMLDocumentReader doc)
{
for (int i = docTypes.Length - 1; i >= 0; i--)
{
if (doc.CanBeReadBy(docTypes[i])) { return true; }
}
return false;
}
public void ScanTrackInfo()
{
var body = document.Body;
for (; scanIndex < body.Children.Length; scanIndex++)
{
var element = body.Children[scanIndex];
if (element.Definition == MatroskaSpecification.SeekHead)
{
seekHead.AddSeekIndex(document.Reader, element as EBMLMasterElement, document.Body.DataOffset);
}
else if (element.Definition == MatroskaSpecification.Info)
{
info.ReadFrom(element as EBMLMasterElement);
}
else if (element.Definition == MatroskaSpecification.Tracks)
{
tracks.AddTrackEntry(element as EBMLMasterElement);
}
else if (element.Definition == MatroskaSpecification.Tags)
{
tags.AddTagEntry(element as EBMLMasterElement);
}
else if (element.Definition == MatroskaSpecification.Cues)
{
cues.AddCueEntry(element as EBMLMasterElement, document.Body.DataOffset);
}
}
if (tracks.Count > 0)
{
int maxTrackNumber = tracks[0].TrackNumber;
minTrackNumber = maxTrackNumber;
for (int i = tracks.Count - 1; i >= 0; i--)
{
if (maxTrackNumber < tracks[i].TrackNumber) { maxTrackNumber = tracks[i].TrackNumber; }
if (minTrackNumber > tracks[i].TrackNumber) { minTrackNumber = tracks[i].TrackNumber; }
}
var range = maxTrackNumber + 1 - minTrackNumber;
if (range > 256) { trackByNumber = null; }
else
{
trackByNumber = new MatroskaTrackEntry[range];
for (int i = tracks.Count - 1; i >= 0; i--)
{
trackByNumber[tracks[i].TrackNumber - minTrackNumber] = tracks[i];
}
}
}
}
public async ValueTask ReadTrackInfo(CancellationToken cancellationToken = default)
{
if (readTrackInfo) { return; }
readTrackInfo = true;
document.Reader.MaxInlineBinarySize = 4096;
while (document.Reader.LastCachedElement?.Definition != MatroskaSpecification.Cluster)
{
if (await document.Reader.ReadNextElement(true, cancellationToken) == null) { break; }
}
ScanTrackInfo();
}
public async ValueTask<MatroskaFrame> ReadFrame(CancellationToken cancellationToken = default)
{
if (frameQueue != null && frameQueue.Count > 0) { return frameQueue.Dequeue(); }
if (!readTrackInfo) { await ReadTrackInfo(cancellationToken); }
while (true)
{
document.Reader.MaxInlineBinarySize = 0;
var element = await document.Reader.ReadNextElementRaw(false, cancellationToken);
if (element.Definition == null) { return default; }
if (element.Definition == MatroskaSpecification.Timestamp)
{
clusterTimestamp = (long)element.Value.UnsignedInteger;
}
else if (element.Definition == MatroskaSpecification.SimpleBlock ||
element.Definition == MatroskaSpecification.Block)
{
var reader = element.Reader;
if (reader == null) { memoryReader.SetBuffer(element.Binary); reader = memoryReader; }
MatroskaTrackEntry trackEntry = null;
var trackIndexVint = await EBMLVInt.Read(reader, cancellationToken);
var trackIndex = (int)trackIndexVint.Value;
if (trackByNumber != null)
{
var idx = trackIndex - minTrackNumber;
if (idx < trackByNumber.Length) { trackEntry = trackByNumber[idx]; }
}
else
{
for (int idx = tracks.Count - 1; idx >= 0; idx--)
{
if (tracks[idx].TrackNumber == trackIndex) { trackEntry = tracks[idx]; break; }
}
}
if (await reader.ReadAsync(new Memory<byte>(readBytes, 0, 3), true, cancellationToken) < 3) { return default; }
var timestampOffset = (short)((readBytes[0] << 8) | readBytes[1]);
var timestamp = clusterTimestamp + timestampOffset;
var flags = readBytes[2];
MatroskaFrame firstFrame = default;
int frameCount = 0;
if ((flags & 0x06) != 0) // Has lacing
{
if (lacingSizes == null) { lacingSizes = new int[256]; }
frameCount = await reader.ReadByteAsync(cancellationToken);
if ((flags & 0x06) == 0x02) // Xiph
{
for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
{
lacingSizes[frameIndex] = await XiphLacingSize.Read(reader, cancellationToken);
}
}
else if ((flags & 0x06) == 0x04) // EBML
{
for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
{
var val = await EBMLVInt.Read(reader, cancellationToken);
if (frameIndex == 0) { lacingSizes[frameIndex] = (int)val.Value; }
else { lacingSizes[frameIndex] = (int)val.SignedValue + lacingSizes[frameIndex - 1]; }
}
}
else // Fixed
{
var fixedSize = (int)reader.UnreadLength / (frameCount + 1);
for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
{
lacingSizes[frameIndex] = fixedSize;
}
}
}
for (int frameIndex = 0; frameIndex <= frameCount; frameIndex++)
{
DataBuffer buffer = null;
try
{
var size = frameIndex == frameCount ? (int)reader.UnreadLength : lacingSizes[frameIndex];
buffer = cache.Pop(size);
buffer.WriteOffset = await reader.ReadAsync(new Memory<byte>(buffer.Buffer, 0, size), true, cancellationToken);
var frame = new MatroskaFrame(trackEntry, trackIndex, timestamp, buffer, (flags & 0x80) != 0);
if (frameIndex == 0) { firstFrame = frame; }
else
{
if (frameQueue == null) { frameQueue = new Queue<MatroskaFrame>(); }
frameQueue.Enqueue(frame);
}
buffer = null;
}
finally { buffer?.Dispose(); }
}
return firstFrame;
}
else if (element.Definition != MatroskaSpecification.Cluster &&
element.Definition.Type == EBMLElementType.Master &&
!element.Definition.Path.StartsWith(@"\Segment\Cluster"))
{
readTrackInfo = false;
await ReadTrackInfo(cancellationToken);
}
}
}
public virtual void Dispose()
{
if (disposed) { return; }
disposed = true;
document.Dispose();
if (frameQueue != null)
{
while (frameQueue.Count > 0) { frameQueue.Dequeue().Buffer.Dispose(); }
frameQueue = null;
}
}
}