mediabunny 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +4 -4
  2. package/dist/mediabunny.d.ts +4 -2
  3. package/dist/modules/codec-data.d.ts +95 -0
  4. package/dist/modules/codec-data.d.ts.map +1 -0
  5. package/dist/modules/codec-data.js +1103 -0
  6. package/dist/modules/codec.d.ts +250 -0
  7. package/dist/modules/codec.d.ts.map +1 -0
  8. package/dist/modules/codec.js +1100 -0
  9. package/dist/modules/conversion.d.ts +158 -0
  10. package/dist/modules/conversion.d.ts.map +1 -0
  11. package/dist/modules/conversion.js +866 -0
  12. package/dist/modules/custom-coder.d.ts +119 -0
  13. package/dist/modules/custom-coder.d.ts.map +1 -0
  14. package/dist/modules/custom-coder.js +91 -0
  15. package/dist/modules/demuxer.d.ts +17 -0
  16. package/dist/modules/demuxer.d.ts.map +1 -0
  17. package/dist/modules/demuxer.js +12 -0
  18. package/dist/modules/index.d.ts +25 -0
  19. package/dist/modules/index.d.ts.map +1 -0
  20. package/dist/modules/index.js +24 -0
  21. package/dist/modules/input-format.d.ts +121 -0
  22. package/dist/modules/input-format.d.ts.map +1 -0
  23. package/dist/modules/input-format.js +333 -0
  24. package/dist/modules/input-track.d.ts +138 -0
  25. package/dist/modules/input-track.d.ts.map +1 -0
  26. package/dist/modules/input-track.js +230 -0
  27. package/dist/modules/input.d.ts +55 -0
  28. package/dist/modules/input.d.ts.map +1 -0
  29. package/dist/modules/input.js +104 -0
  30. package/dist/modules/isobmff/isobmff-boxes.d.ts +202 -0
  31. package/dist/modules/isobmff/isobmff-boxes.d.ts.map +1 -0
  32. package/dist/modules/isobmff/isobmff-boxes.js +1111 -0
  33. package/dist/modules/isobmff/isobmff-demuxer.d.ts +163 -0
  34. package/dist/modules/isobmff/isobmff-demuxer.d.ts.map +1 -0
  35. package/dist/modules/isobmff/isobmff-demuxer.js +2080 -0
  36. package/dist/modules/isobmff/isobmff-misc.d.ts +14 -0
  37. package/dist/modules/isobmff/isobmff-misc.d.ts.map +1 -0
  38. package/dist/modules/isobmff/isobmff-misc.js +20 -0
  39. package/dist/modules/isobmff/isobmff-muxer.d.ts +142 -0
  40. package/dist/modules/isobmff/isobmff-muxer.d.ts.map +1 -0
  41. package/dist/modules/isobmff/isobmff-muxer.js +858 -0
  42. package/dist/modules/isobmff/isobmff-reader.d.ts +36 -0
  43. package/dist/modules/isobmff/isobmff-reader.d.ts.map +1 -0
  44. package/dist/modules/isobmff/isobmff-reader.js +105 -0
  45. package/dist/modules/matroska/ebml.d.ts +156 -0
  46. package/dist/modules/matroska/ebml.d.ts.map +1 -0
  47. package/dist/modules/matroska/ebml.js +529 -0
  48. package/dist/modules/matroska/matroska-demuxer.d.ts +119 -0
  49. package/dist/modules/matroska/matroska-demuxer.d.ts.map +1 -0
  50. package/dist/modules/matroska/matroska-demuxer.js +1330 -0
  51. package/dist/modules/matroska/matroska-misc.d.ts +14 -0
  52. package/dist/modules/matroska/matroska-misc.d.ts.map +1 -0
  53. package/dist/modules/matroska/matroska-misc.js +20 -0
  54. package/dist/modules/matroska/matroska-muxer.d.ts +71 -0
  55. package/dist/modules/matroska/matroska-muxer.d.ts.map +1 -0
  56. package/dist/modules/matroska/matroska-muxer.js +729 -0
  57. package/dist/modules/media-sink.d.ts +272 -0
  58. package/dist/modules/media-sink.d.ts.map +1 -0
  59. package/dist/modules/media-sink.js +1264 -0
  60. package/dist/modules/media-source.d.ts +230 -0
  61. package/dist/modules/media-source.d.ts.map +1 -0
  62. package/dist/modules/media-source.js +1095 -0
  63. package/dist/modules/misc.d.ts +127 -0
  64. package/dist/modules/misc.d.ts.map +1 -0
  65. package/dist/modules/misc.js +462 -0
  66. package/dist/modules/mp3/mp3-demuxer.d.ts +32 -0
  67. package/dist/modules/mp3/mp3-demuxer.d.ts.map +1 -0
  68. package/dist/modules/mp3/mp3-demuxer.js +160 -0
  69. package/dist/modules/mp3/mp3-misc.d.ts +37 -0
  70. package/dist/modules/mp3/mp3-misc.d.ts.map +1 -0
  71. package/dist/modules/mp3/mp3-misc.js +122 -0
  72. package/dist/modules/mp3/mp3-muxer.d.ts +27 -0
  73. package/dist/modules/mp3/mp3-muxer.d.ts.map +1 -0
  74. package/dist/modules/mp3/mp3-muxer.js +112 -0
  75. package/dist/modules/mp3/mp3-reader.d.ts +25 -0
  76. package/dist/modules/mp3/mp3-reader.d.ts.map +1 -0
  77. package/dist/modules/mp3/mp3-reader.js +73 -0
  78. package/dist/modules/mp3/mp3-writer.d.ts +30 -0
  79. package/dist/modules/mp3/mp3-writer.d.ts.map +1 -0
  80. package/dist/modules/mp3/mp3-writer.js +72 -0
  81. package/dist/modules/muxer.d.ts +32 -0
  82. package/dist/modules/muxer.d.ts.map +1 -0
  83. package/dist/modules/muxer.js +50 -0
  84. package/dist/modules/ogg/ogg-demuxer.d.ts +53 -0
  85. package/dist/modules/ogg/ogg-demuxer.d.ts.map +1 -0
  86. package/dist/modules/ogg/ogg-demuxer.js +701 -0
  87. package/dist/modules/ogg/ogg-misc.d.ts +27 -0
  88. package/dist/modules/ogg/ogg-misc.d.ts.map +1 -0
  89. package/dist/modules/ogg/ogg-misc.js +78 -0
  90. package/dist/modules/ogg/ogg-muxer.d.ts +58 -0
  91. package/dist/modules/ogg/ogg-muxer.d.ts.map +1 -0
  92. package/dist/modules/ogg/ogg-muxer.js +345 -0
  93. package/dist/modules/ogg/ogg-reader.d.ts +37 -0
  94. package/dist/modules/ogg/ogg-reader.d.ts.map +1 -0
  95. package/dist/modules/ogg/ogg-reader.js +104 -0
  96. package/dist/modules/output-format.d.ts +285 -0
  97. package/dist/modules/output-format.d.ts.map +1 -0
  98. package/dist/modules/output-format.js +385 -0
  99. package/dist/modules/output.d.ts +134 -0
  100. package/dist/modules/output.d.ts.map +1 -0
  101. package/dist/modules/output.js +269 -0
  102. package/dist/modules/packet.d.ts +86 -0
  103. package/dist/modules/packet.d.ts.map +1 -0
  104. package/dist/modules/packet.js +133 -0
  105. package/dist/modules/pcm.d.ts +12 -0
  106. package/dist/modules/pcm.d.ts.map +1 -0
  107. package/dist/modules/pcm.js +85 -0
  108. package/dist/modules/reader.d.ts +40 -0
  109. package/dist/modules/reader.d.ts.map +1 -0
  110. package/dist/modules/reader.js +153 -0
  111. package/dist/modules/sample.d.ts +186 -0
  112. package/dist/modules/sample.d.ts.map +1 -0
  113. package/dist/modules/sample.js +798 -0
  114. package/dist/modules/source.d.ts +76 -0
  115. package/dist/modules/source.d.ts.map +1 -0
  116. package/dist/modules/source.js +183 -0
  117. package/dist/modules/subtitles.d.ts +37 -0
  118. package/dist/modules/subtitles.d.ts.map +1 -0
  119. package/dist/modules/subtitles.js +89 -0
  120. package/dist/modules/target.d.ts +58 -0
  121. package/dist/modules/target.d.ts.map +1 -0
  122. package/dist/modules/target.js +63 -0
  123. package/dist/modules/wave/riff-reader.d.ts +19 -0
  124. package/dist/modules/wave/riff-reader.d.ts.map +1 -0
  125. package/dist/modules/wave/riff-reader.js +38 -0
  126. package/dist/modules/wave/riff-writer.d.ts +18 -0
  127. package/dist/modules/wave/riff-writer.d.ts.map +1 -0
  128. package/dist/modules/wave/riff-writer.js +25 -0
  129. package/dist/modules/wave/wave-demuxer.d.ts +42 -0
  130. package/dist/modules/wave/wave-demuxer.d.ts.map +1 -0
  131. package/dist/modules/wave/wave-demuxer.js +239 -0
  132. package/dist/modules/wave/wave-muxer.d.ts +27 -0
  133. package/dist/modules/wave/wave-muxer.d.ts.map +1 -0
  134. package/dist/modules/wave/wave-muxer.js +108 -0
  135. package/dist/modules/writer.d.ts +85 -0
  136. package/dist/modules/writer.d.ts.map +1 -0
  137. package/dist/modules/writer.js +347 -0
  138. package/package.json +14 -10
  139. package/src/codec-data.ts +1394 -0
  140. package/src/codec.ts +1392 -0
  141. package/src/conversion.ts +1199 -0
  142. package/src/custom-coder.ts +162 -0
  143. package/src/demuxer.ts +22 -0
  144. package/src/index.ts +148 -0
  145. package/src/input-format.ts +386 -0
  146. package/src/input-track.ts +341 -0
  147. package/src/input.ts +138 -0
  148. package/src/isobmff/isobmff-boxes.ts +1365 -0
  149. package/src/isobmff/isobmff-demuxer.ts +2646 -0
  150. package/src/isobmff/isobmff-misc.ts +29 -0
  151. package/src/isobmff/isobmff-muxer.ts +1210 -0
  152. package/src/isobmff/isobmff-reader.ts +137 -0
  153. package/src/matroska/ebml.ts +595 -0
  154. package/src/matroska/matroska-demuxer.ts +1677 -0
  155. package/src/matroska/matroska-misc.ts +29 -0
  156. package/src/matroska/matroska-muxer.ts +999 -0
  157. package/src/media-sink.ts +1577 -0
  158. package/src/media-source.ts +1406 -0
  159. package/src/misc.ts +584 -0
  160. package/src/mp3/mp3-demuxer.ts +228 -0
  161. package/src/mp3/mp3-misc.ts +154 -0
  162. package/src/mp3/mp3-muxer.ts +153 -0
  163. package/src/mp3/mp3-reader.ts +93 -0
  164. package/src/mp3/mp3-writer.ts +112 -0
  165. package/src/muxer.ts +88 -0
  166. package/src/ogg/ogg-demuxer.ts +985 -0
  167. package/src/ogg/ogg-misc.ts +116 -0
  168. package/src/ogg/ogg-muxer.ts +480 -0
  169. package/src/ogg/ogg-reader.ts +143 -0
  170. package/src/output-format.ts +689 -0
  171. package/src/output.ts +427 -0
  172. package/src/packet.ts +180 -0
  173. package/src/pcm.ts +112 -0
  174. package/src/reader.ts +205 -0
  175. package/src/sample.ts +1029 -0
  176. package/src/source.ts +279 -0
  177. package/src/subtitles.ts +131 -0
  178. package/src/target.ts +106 -0
  179. package/src/tsconfig.json +13 -0
  180. package/src/wave/riff-reader.ts +48 -0
  181. package/src/wave/riff-writer.ts +30 -0
  182. package/src/wave/wave-demuxer.ts +317 -0
  183. package/src/wave/wave-muxer.ts +145 -0
  184. package/src/writer.ts +461 -0
  185. /package/dist/{mediabunny.js → bundles/mediabunny.cjs} +0 -0
  186. /package/dist/{mediabunny.min.js → bundles/mediabunny.min.cjs} +0 -0
  187. /package/dist/{mediabunny.min.mjs → bundles/mediabunny.min.mjs} +0 -0
  188. /package/dist/{mediabunny.mjs → bundles/mediabunny.mjs} +0 -0
@@ -0,0 +1,999 @@
1
+ /*!
2
+ * Copyright (c) 2025-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+
9
+ import {
10
+ Bitstream,
11
+ COLOR_PRIMARIES_MAP,
12
+ MATRIX_COEFFICIENTS_MAP,
13
+ TRANSFER_CHARACTERISTICS_MAP,
14
+ UNDETERMINED_LANGUAGE,
15
+ assert,
16
+ colorSpaceIsComplete,
17
+ normalizeRotation,
18
+ promiseWithResolvers,
19
+ roundToMultiple,
20
+ textEncoder,
21
+ toUint8Array,
22
+ writeBits,
23
+ } from '../misc';
24
+ import {
25
+ CODEC_STRING_MAP,
26
+ EBML,
27
+ EBMLElement,
28
+ EBMLFloat32,
29
+ EBMLFloat64,
30
+ EBMLId,
31
+ EBMLSignedInt,
32
+ EBMLWriter,
33
+ } from './ebml';
34
+ import { buildMatroskaMimeType } from './matroska-misc';
35
+ import { MkvOutputFormat, WebMOutputFormat } from '../output-format';
36
+ import { Output, OutputAudioTrack, OutputSubtitleTrack, OutputTrack, OutputVideoTrack } from '../output';
37
+ import {
38
+ SubtitleConfig,
39
+ SubtitleCue,
40
+ SubtitleMetadata,
41
+ formatSubtitleTimestamp,
42
+ inlineTimestampRegex,
43
+ parseSubtitleTimestamp,
44
+ } from '../subtitles';
45
+ import {
46
+ OPUS_INTERNAL_SAMPLE_RATE,
47
+ PCM_AUDIO_CODECS,
48
+ PcmAudioCodec,
49
+ SubtitleCodec,
50
+ generateAv1CodecConfigurationFromCodecString,
51
+ generateVp9CodecConfigurationFromCodecString,
52
+ parsePcmCodec,
53
+ validateAudioChunkMetadata,
54
+ validateSubtitleMetadata,
55
+ validateVideoChunkMetadata,
56
+ } from '../codec';
57
+ import { Muxer } from '../muxer';
58
+ import { Writer } from '../writer';
59
+ import { EncodedPacket } from '../packet';
60
+ import { parseOpusIdentificationHeader } from '../codec-data';
61
+
62
+ const MIN_CLUSTER_TIMESTAMP_MS = -(2 ** 15);
63
+ const MAX_CLUSTER_TIMESTAMP_MS = 2 ** 15 - 1;
64
+ const APP_NAME = 'https://github.com/Vanilagy/mediabunny';
65
+ const SEGMENT_SIZE_BYTES = 6;
66
+ const CLUSTER_SIZE_BYTES = 5;
67
+
68
+ type InternalMediaChunk = {
69
+ data: Uint8Array;
70
+ type: 'key' | 'delta';
71
+ timestamp: number;
72
+ duration: number;
73
+ additions: Uint8Array | null;
74
+ };
75
+
76
+ type SeekHead = {
77
+ id: number;
78
+ data: {
79
+ id: number;
80
+ data: ({
81
+ id: number;
82
+ data: Uint8Array;
83
+ size?: undefined;
84
+ } | {
85
+ id: number;
86
+ size: number;
87
+ data: number;
88
+ })[];
89
+ }[];
90
+ };
91
+
92
+ type MatroskaTrackData = {
93
+ chunkQueue: InternalMediaChunk[];
94
+ lastWrittenMsTimestamp: number | null;
95
+ } & ({
96
+ track: OutputVideoTrack;
97
+ type: 'video';
98
+ info: {
99
+ width: number;
100
+ height: number;
101
+ decoderConfig: VideoDecoderConfig;
102
+ };
103
+ } | {
104
+ track: OutputAudioTrack;
105
+ type: 'audio';
106
+ info: {
107
+ numberOfChannels: number;
108
+ sampleRate: number;
109
+ decoderConfig: AudioDecoderConfig;
110
+ };
111
+ } | {
112
+ track: OutputSubtitleTrack;
113
+ type: 'subtitle';
114
+ info: {
115
+ config: SubtitleConfig;
116
+ };
117
+ });
118
+
119
+ type MatroskaVideoTrackData = MatroskaTrackData & { type: 'video' };
120
+ type MatroskaAudioTrackData = MatroskaTrackData & { type: 'audio' };
121
+ type MatroskaSubtitleTrackData = MatroskaTrackData & { type: 'subtitle' };
122
+
123
+ const TRACK_TYPE_MAP: Record<OutputTrack['type'], number> = {
124
+ video: 1,
125
+ audio: 2,
126
+ subtitle: 17,
127
+ };
128
+
129
+ export class MatroskaMuxer extends Muxer {
130
+ private writer: Writer;
131
+ private ebmlWriter: EBMLWriter;
132
+ private format: WebMOutputFormat | MkvOutputFormat;
133
+
134
+ private trackDatas: MatroskaTrackData[] = [];
135
+ private allTracksKnown = promiseWithResolvers();
136
+
137
+ private segment: EBMLElement | null = null;
138
+ private segmentInfo: EBMLElement | null = null;
139
+ private seekHead: SeekHead | null = null;
140
+ private tracksElement: EBMLElement | null = null;
141
+ private segmentDuration: EBMLElement | null = null;
142
+ private cues: EBMLElement | null = null;
143
+
144
+ private currentCluster: EBMLElement | null = null;
145
+ private currentClusterStartMsTimestamp: number | null = null;
146
+ private currentClusterMaxMsTimestamp: number | null = null;
147
+ private trackDatasInCurrentCluster = new Map<MatroskaTrackData, {
148
+ firstMsTimestamp: number;
149
+ }>();
150
+
151
+ private duration = 0;
152
+
153
+ constructor(output: Output, format: MkvOutputFormat) {
154
+ super(output);
155
+
156
+ this.writer = output._writer;
157
+ this.format = format;
158
+
159
+ this.ebmlWriter = new EBMLWriter(this.writer);
160
+
161
+ if (this.format._options.appendOnly) {
162
+ this.writer.ensureMonotonicity = true;
163
+ }
164
+ }
165
+
166
+ async start() {
167
+ const release = await this.mutex.acquire();
168
+
169
+ this.writeEBMLHeader();
170
+
171
+ if (!this.format._options.appendOnly) {
172
+ this.createSeekHead();
173
+ }
174
+
175
+ this.createSegmentInfo();
176
+ this.createCues();
177
+
178
+ await this.writer.flush();
179
+
180
+ release();
181
+ }
182
+
183
+ private writeEBMLHeader() {
184
+ if (this.format._options.onEbmlHeader) {
185
+ this.writer.startTrackingWrites();
186
+ }
187
+
188
+ const ebmlHeader: EBML = { id: EBMLId.EBML, data: [
189
+ { id: EBMLId.EBMLVersion, data: 1 },
190
+ { id: EBMLId.EBMLReadVersion, data: 1 },
191
+ { id: EBMLId.EBMLMaxIDLength, data: 4 },
192
+ { id: EBMLId.EBMLMaxSizeLength, data: 8 },
193
+ { id: EBMLId.DocType, data: this.format instanceof WebMOutputFormat ? 'webm' : 'matroska' },
194
+ { id: EBMLId.DocTypeVersion, data: 2 },
195
+ { id: EBMLId.DocTypeReadVersion, data: 2 },
196
+ ] };
197
+ this.ebmlWriter.writeEBML(ebmlHeader);
198
+
199
+ if (this.format._options.onEbmlHeader) {
200
+ const { data, start } = this.writer.stopTrackingWrites(); // start should be 0
201
+ this.format._options.onEbmlHeader(data, start);
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Creates a SeekHead element which is positioned near the start of the file and allows the media player to seek to
207
+ * relevant sections more easily. Since we don't know the positions of those sections yet, we'll set them later.
208
+ */
209
+ private createSeekHead() {
210
+ const kaxCues = new Uint8Array([0x1c, 0x53, 0xbb, 0x6b]);
211
+ const kaxInfo = new Uint8Array([0x15, 0x49, 0xa9, 0x66]);
212
+ const kaxTracks = new Uint8Array([0x16, 0x54, 0xae, 0x6b]);
213
+
214
+ const seekHead = { id: EBMLId.SeekHead, data: [
215
+ { id: EBMLId.Seek, data: [
216
+ { id: EBMLId.SeekID, data: kaxCues },
217
+ { id: EBMLId.SeekPosition, size: 5, data: 0 },
218
+ ] },
219
+ { id: EBMLId.Seek, data: [
220
+ { id: EBMLId.SeekID, data: kaxInfo },
221
+ { id: EBMLId.SeekPosition, size: 5, data: 0 },
222
+ ] },
223
+ { id: EBMLId.Seek, data: [
224
+ { id: EBMLId.SeekID, data: kaxTracks },
225
+ { id: EBMLId.SeekPosition, size: 5, data: 0 },
226
+ ] },
227
+ ] };
228
+ this.seekHead = seekHead;
229
+ }
230
+
231
+ private createSegmentInfo() {
232
+ const segmentDuration: EBML = { id: EBMLId.Duration, data: new EBMLFloat64(0) };
233
+ this.segmentDuration = segmentDuration;
234
+
235
+ const segmentInfo: EBML = { id: EBMLId.Info, data: [
236
+ { id: EBMLId.TimestampScale, data: 1e6 },
237
+ { id: EBMLId.MuxingApp, data: APP_NAME },
238
+ { id: EBMLId.WritingApp, data: APP_NAME },
239
+ !this.format._options.appendOnly ? segmentDuration : null,
240
+ ] };
241
+ this.segmentInfo = segmentInfo;
242
+ }
243
+
244
+ private createTracks() {
245
+ const tracksElement = { id: EBMLId.Tracks, data: [] as EBML[] };
246
+ this.tracksElement = tracksElement;
247
+
248
+ for (const trackData of this.trackDatas) {
249
+ const codecId = CODEC_STRING_MAP[trackData.track.source._codec];
250
+ assert(codecId);
251
+
252
+ let seekPreRollNs = 0;
253
+ if (trackData.type === 'audio' && trackData.track.source._codec === 'opus') {
254
+ seekPreRollNs = 1e6 * 80; // In "Matroska ticks" (nanoseconds)
255
+
256
+ const description = trackData.info.decoderConfig.description;
257
+ if (description) {
258
+ const bytes = toUint8Array(description);
259
+ const header = parseOpusIdentificationHeader(bytes);
260
+
261
+ // Use the preSkip value from the header
262
+ seekPreRollNs = Math.round(1e9 * (header.preSkip / OPUS_INTERNAL_SAMPLE_RATE));
263
+ }
264
+ }
265
+
266
+ tracksElement.data.push({ id: EBMLId.TrackEntry, data: [
267
+ { id: EBMLId.TrackNumber, data: trackData.track.id },
268
+ { id: EBMLId.TrackUID, data: trackData.track.id },
269
+ { id: EBMLId.TrackType, data: TRACK_TYPE_MAP[trackData.type] },
270
+ { id: EBMLId.FlagLacing, data: 0 },
271
+ { id: EBMLId.Language, data: trackData.track.metadata.languageCode ?? UNDETERMINED_LANGUAGE },
272
+ { id: EBMLId.CodecID, data: codecId },
273
+ { id: EBMLId.CodecDelay, data: 0 },
274
+ { id: EBMLId.SeekPreRoll, data: seekPreRollNs },
275
+ (trackData.type === 'video' ? this.videoSpecificTrackInfo(trackData) : null),
276
+ (trackData.type === 'audio' ? this.audioSpecificTrackInfo(trackData) : null),
277
+ (trackData.type === 'subtitle' ? this.subtitleSpecificTrackInfo(trackData) : null),
278
+ ] });
279
+ }
280
+ }
281
+
282
+ private videoSpecificTrackInfo(trackData: MatroskaVideoTrackData) {
283
+ const { frameRate, rotation } = trackData.track.metadata;
284
+
285
+ const elements: EBMLElement['data'] = [
286
+ (trackData.info.decoderConfig.description
287
+ ? {
288
+ id: EBMLId.CodecPrivate,
289
+ data: toUint8Array(trackData.info.decoderConfig.description),
290
+ }
291
+ : null),
292
+ (frameRate
293
+ ? {
294
+ id: EBMLId.DefaultDuration,
295
+ data: 1e9 / frameRate,
296
+ }
297
+ : null),
298
+ ];
299
+
300
+ // Convert from clockwise to counter-clockwise
301
+ const flippedRotation = rotation ? normalizeRotation(-rotation) : 0;
302
+
303
+ const colorSpace = trackData.info.decoderConfig.colorSpace;
304
+ const videoElement: EBMLElement = { id: EBMLId.Video, data: [
305
+ { id: EBMLId.PixelWidth, data: trackData.info.width },
306
+ { id: EBMLId.PixelHeight, data: trackData.info.height },
307
+ (colorSpaceIsComplete(colorSpace)
308
+ ? {
309
+ id: EBMLId.Colour,
310
+ data: [
311
+ {
312
+ id: EBMLId.MatrixCoefficients,
313
+ data: MATRIX_COEFFICIENTS_MAP[colorSpace.matrix],
314
+ },
315
+ {
316
+ id: EBMLId.TransferCharacteristics,
317
+ data: TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer],
318
+ },
319
+ {
320
+ id: EBMLId.Primaries,
321
+ data: COLOR_PRIMARIES_MAP[colorSpace.primaries],
322
+ },
323
+ {
324
+ id: EBMLId.Range,
325
+ data: colorSpace.fullRange ? 2 : 1,
326
+ },
327
+ ],
328
+ }
329
+ : null),
330
+ (flippedRotation
331
+ ? {
332
+ id: EBMLId.Projection,
333
+ data: [
334
+ {
335
+ id: EBMLId.ProjectionType,
336
+ data: 0, // rectangular
337
+ },
338
+ {
339
+ id: EBMLId.ProjectionPoseRoll,
340
+ data: new EBMLFloat32((flippedRotation + 180) % 360 - 180), // [0, 270] -> [-180, 90]
341
+ },
342
+ ],
343
+ }
344
+ : null),
345
+ ] };
346
+
347
+ elements.push(videoElement);
348
+
349
+ return elements;
350
+ }
351
+
352
+ private audioSpecificTrackInfo(trackData: MatroskaAudioTrackData) {
353
+ const pcmInfo = (PCM_AUDIO_CODECS as readonly string[]).includes(trackData.track.source._codec)
354
+ ? parsePcmCodec(trackData.track.source._codec as PcmAudioCodec)
355
+ : null;
356
+
357
+ return [
358
+ (trackData.info.decoderConfig.description
359
+ ? {
360
+ id: EBMLId.CodecPrivate,
361
+ data: toUint8Array(trackData.info.decoderConfig.description),
362
+ }
363
+ : null),
364
+ { id: EBMLId.Audio, data: [
365
+ { id: EBMLId.SamplingFrequency, data: new EBMLFloat32(trackData.info.sampleRate) },
366
+ { id: EBMLId.Channels, data: trackData.info.numberOfChannels },
367
+ pcmInfo ? { id: EBMLId.BitDepth, data: 8 * pcmInfo.sampleSize } : null,
368
+ ] },
369
+ ];
370
+ }
371
+
372
+ private subtitleSpecificTrackInfo(trackData: MatroskaSubtitleTrackData) {
373
+ return [
374
+ { id: EBMLId.CodecPrivate, data: textEncoder.encode(trackData.info.config.description) },
375
+ ];
376
+ }
377
+
378
+ private createSegment() {
379
+ const segment: EBML = {
380
+ id: EBMLId.Segment,
381
+ size: this.format._options.appendOnly ? -1 : SEGMENT_SIZE_BYTES,
382
+ data: [
383
+ !this.format._options.appendOnly ? this.seekHead as EBML : null,
384
+ this.segmentInfo,
385
+ this.tracksElement,
386
+ ],
387
+ };
388
+ this.segment = segment;
389
+
390
+ if (this.format._options.onSegmentHeader) {
391
+ this.writer.startTrackingWrites();
392
+ }
393
+
394
+ this.ebmlWriter.writeEBML(segment);
395
+
396
+ if (this.format._options.onSegmentHeader) {
397
+ const { data, start } = this.writer.stopTrackingWrites();
398
+ this.format._options.onSegmentHeader(data, start);
399
+ }
400
+ }
401
+
402
+ private createCues() {
403
+ this.cues = { id: EBMLId.Cues, data: [] };
404
+ }
405
+
406
+ private get segmentDataOffset() {
407
+ assert(this.segment);
408
+ return this.ebmlWriter.dataOffsets.get(this.segment)!;
409
+ }
410
+
411
+ private allTracksAreKnown() {
412
+ for (const track of this.output._tracks) {
413
+ if (!track.source._closed && !this.trackDatas.some(x => x.track === track)) {
414
+ return false; // We haven't seen a sample from this open track yet
415
+ }
416
+ }
417
+
418
+ return true;
419
+ }
420
+
421
+ async getMimeType() {
422
+ await this.allTracksKnown.promise;
423
+
424
+ const codecStrings = this.trackDatas.map((trackData) => {
425
+ if (trackData.type === 'video') {
426
+ return trackData.info.decoderConfig.codec;
427
+ } else if (trackData.type === 'audio') {
428
+ return trackData.info.decoderConfig.codec;
429
+ } else {
430
+ const map: Record<SubtitleCodec, string> = {
431
+ webvtt: 'wvtt',
432
+ };
433
+ return map[trackData.track.source._codec];
434
+ }
435
+ });
436
+
437
+ return buildMatroskaMimeType({
438
+ isWebM: this.format instanceof WebMOutputFormat,
439
+ hasVideo: this.trackDatas.some(x => x.type === 'video'),
440
+ hasAudio: this.trackDatas.some(x => x.type === 'audio'),
441
+ codecStrings,
442
+ });
443
+ }
444
+
445
+ private getVideoTrackData(track: OutputVideoTrack, meta?: EncodedVideoChunkMetadata) {
446
+ const existingTrackData = this.trackDatas.find(x => x.track === track);
447
+ if (existingTrackData) {
448
+ return existingTrackData as MatroskaVideoTrackData;
449
+ }
450
+
451
+ validateVideoChunkMetadata(meta);
452
+
453
+ assert(meta);
454
+ assert(meta.decoderConfig);
455
+ assert(meta.decoderConfig.codedWidth !== undefined);
456
+ assert(meta.decoderConfig.codedHeight !== undefined);
457
+
458
+ const newTrackData: MatroskaVideoTrackData = {
459
+ track,
460
+ type: 'video',
461
+ info: {
462
+ width: meta.decoderConfig.codedWidth,
463
+ height: meta.decoderConfig.codedHeight,
464
+ decoderConfig: meta.decoderConfig,
465
+ },
466
+ chunkQueue: [],
467
+ lastWrittenMsTimestamp: null,
468
+ };
469
+
470
+ if (track.source._codec === 'vp9') {
471
+ // https://www.webmproject.org/docs/container specifies that VP9 "SHOULD" make use of the CodecPrivate
472
+ // field. Since WebCodecs makes no use of the description field for VP9, we need to derive it ourselves:
473
+ newTrackData.info.decoderConfig = {
474
+ ...newTrackData.info.decoderConfig,
475
+ description: new Uint8Array(
476
+ generateVp9CodecConfigurationFromCodecString(newTrackData.info.decoderConfig.codec),
477
+ ),
478
+ };
479
+ } else if (track.source._codec === 'av1') {
480
+ // Per https://github.com/ietf-wg-cellar/matroska-specification/blob/master/codec/av1.md, AV1 requires
481
+ // CodecPrivate to be set, but WebCodecs makes no use of the description field for AV1. Thus, let's derive
482
+ // it ourselves:
483
+ newTrackData.info.decoderConfig = {
484
+ ...newTrackData.info.decoderConfig,
485
+ description: new Uint8Array(
486
+ generateAv1CodecConfigurationFromCodecString(newTrackData.info.decoderConfig.codec),
487
+ ),
488
+ };
489
+ }
490
+
491
+ this.trackDatas.push(newTrackData);
492
+ this.trackDatas.sort((a, b) => a.track.id - b.track.id);
493
+
494
+ if (this.allTracksAreKnown()) {
495
+ this.allTracksKnown.resolve();
496
+ }
497
+
498
+ return newTrackData;
499
+ }
500
+
501
+ private getAudioTrackData(track: OutputAudioTrack, meta?: EncodedAudioChunkMetadata) {
502
+ const existingTrackData = this.trackDatas.find(x => x.track === track);
503
+ if (existingTrackData) {
504
+ return existingTrackData as MatroskaAudioTrackData;
505
+ }
506
+
507
+ validateAudioChunkMetadata(meta);
508
+
509
+ assert(meta);
510
+ assert(meta.decoderConfig);
511
+
512
+ const newTrackData: MatroskaAudioTrackData = {
513
+ track,
514
+ type: 'audio',
515
+ info: {
516
+ numberOfChannels: meta.decoderConfig.numberOfChannels,
517
+ sampleRate: meta.decoderConfig.sampleRate,
518
+ decoderConfig: meta.decoderConfig,
519
+ },
520
+ chunkQueue: [],
521
+ lastWrittenMsTimestamp: null,
522
+ };
523
+
524
+ this.trackDatas.push(newTrackData);
525
+ this.trackDatas.sort((a, b) => a.track.id - b.track.id);
526
+
527
+ if (this.allTracksAreKnown()) {
528
+ this.allTracksKnown.resolve();
529
+ }
530
+
531
+ return newTrackData;
532
+ }
533
+
534
+ private getSubtitleTrackData(track: OutputSubtitleTrack, meta?: SubtitleMetadata) {
535
+ const existingTrackData = this.trackDatas.find(x => x.track === track);
536
+ if (existingTrackData) {
537
+ return existingTrackData as MatroskaAudioTrackData;
538
+ }
539
+
540
+ validateSubtitleMetadata(meta);
541
+
542
+ assert(meta);
543
+ assert(meta.config);
544
+
545
+ const newTrackData: MatroskaSubtitleTrackData = {
546
+ track,
547
+ type: 'subtitle',
548
+ info: {
549
+ config: meta.config,
550
+ },
551
+ chunkQueue: [],
552
+ lastWrittenMsTimestamp: null,
553
+ };
554
+
555
+ this.trackDatas.push(newTrackData);
556
+ this.trackDatas.sort((a, b) => a.track.id - b.track.id);
557
+
558
+ if (this.allTracksAreKnown()) {
559
+ this.allTracksKnown.resolve();
560
+ }
561
+
562
+ return newTrackData;
563
+ }
564
+
565
+ async addEncodedVideoPacket(track: OutputVideoTrack, packet: EncodedPacket, meta?: EncodedVideoChunkMetadata) {
566
+ const release = await this.mutex.acquire();
567
+
568
+ try {
569
+ const trackData = this.getVideoTrackData(track, meta);
570
+
571
+ const isKeyFrame = packet.type === 'key';
572
+ let timestamp = this.validateAndNormalizeTimestamp(trackData.track, packet.timestamp, isKeyFrame);
573
+ let duration = packet.duration;
574
+
575
+ if (track.metadata.frameRate !== undefined) {
576
+ // Constrain the time values to the frame rate
577
+ timestamp = roundToMultiple(timestamp, 1 / track.metadata.frameRate);
578
+ duration = roundToMultiple(duration, 1 / track.metadata.frameRate);
579
+ }
580
+
581
+ const videoChunk = this.createInternalChunk(packet.data, timestamp, duration, packet.type);
582
+ if (track.source._codec === 'vp9') this.fixVP9ColorSpace(trackData, videoChunk);
583
+
584
+ trackData.chunkQueue.push(videoChunk);
585
+ await this.interleaveChunks();
586
+ } finally {
587
+ release();
588
+ }
589
+ }
590
+
591
+ async addEncodedAudioPacket(track: OutputAudioTrack, packet: EncodedPacket, meta?: EncodedAudioChunkMetadata) {
592
+ const release = await this.mutex.acquire();
593
+
594
+ try {
595
+ const trackData = this.getAudioTrackData(track, meta);
596
+
597
+ const isKeyFrame = packet.type === 'key';
598
+ const timestamp = this.validateAndNormalizeTimestamp(trackData.track, packet.timestamp, isKeyFrame);
599
+ const audioChunk = this.createInternalChunk(packet.data, timestamp, packet.duration, packet.type);
600
+
601
+ trackData.chunkQueue.push(audioChunk);
602
+ await this.interleaveChunks();
603
+ } finally {
604
+ release();
605
+ }
606
+ }
607
+
608
+ async addSubtitleCue(track: OutputSubtitleTrack, cue: SubtitleCue, meta?: SubtitleMetadata) {
609
+ const release = await this.mutex.acquire();
610
+
611
+ try {
612
+ const trackData = this.getSubtitleTrackData(track, meta);
613
+
614
+ const timestamp = this.validateAndNormalizeTimestamp(trackData.track, cue.timestamp, true);
615
+
616
+ let bodyText = cue.text;
617
+ const timestampMs = Math.round(timestamp * 1000);
618
+
619
+ // Replace in-body timestamps so that they're relative to the cue start time
620
+ inlineTimestampRegex.lastIndex = 0;
621
+ bodyText = bodyText.replace(inlineTimestampRegex, (match) => {
622
+ const time = parseSubtitleTimestamp(match.slice(1, -1));
623
+ const offsetTime = time - timestampMs;
624
+
625
+ return `<${formatSubtitleTimestamp(offsetTime)}>`;
626
+ });
627
+
628
+ const body = textEncoder.encode(bodyText);
629
+ const additions = `${cue.settings ?? ''}\n${cue.identifier ?? ''}\n${cue.notes ?? ''}`;
630
+
631
+ const subtitleChunk = this.createInternalChunk(
632
+ body,
633
+ timestamp,
634
+ cue.duration,
635
+ 'key',
636
+ additions.trim() ? textEncoder.encode(additions) : null,
637
+ );
638
+
639
+ trackData.chunkQueue.push(subtitleChunk);
640
+ await this.interleaveChunks();
641
+ } finally {
642
+ release();
643
+ }
644
+ }
645
+
646
+ private async interleaveChunks(isFinalCall = false) {
647
+ if (!isFinalCall) {
648
+ if (!this.allTracksAreKnown()) {
649
+ return; // We can't interleave yet as we don't yet know how many tracks we'll truly have
650
+ }
651
+ }
652
+
653
+ outer:
654
+ while (true) {
655
+ let trackWithMinTimestamp: MatroskaTrackData | null = null;
656
+ let minTimestamp = Infinity;
657
+
658
+ for (const trackData of this.trackDatas) {
659
+ if (!isFinalCall && trackData.chunkQueue.length === 0 && !trackData.track.source._closed) {
660
+ break outer;
661
+ }
662
+
663
+ if (trackData.chunkQueue.length > 0 && trackData.chunkQueue[0]!.timestamp < minTimestamp) {
664
+ trackWithMinTimestamp = trackData;
665
+ minTimestamp = trackData.chunkQueue[0]!.timestamp;
666
+ }
667
+ }
668
+
669
+ if (!trackWithMinTimestamp) {
670
+ break;
671
+ }
672
+
673
+ const chunk = trackWithMinTimestamp.chunkQueue.shift()!;
674
+ this.writeBlock(trackWithMinTimestamp, chunk);
675
+ }
676
+
677
+ if (!isFinalCall) {
678
+ await this.writer.flush();
679
+ }
680
+ }
681
+
682
+ /**
683
+ * Due to [a bug in Chromium](https://bugs.chromium.org/p/chromium/issues/detail?id=1377842), VP9 streams often
684
+ * lack color space information. This method patches in that information.
685
+ */
686
+ private fixVP9ColorSpace(
687
+ trackData: MatroskaVideoTrackData,
688
+ chunk: InternalMediaChunk,
689
+ ) {
690
+ // http://downloads.webmproject.org/docs/vp9/vp9-bitstream_superframe-and-uncompressed-header_v1.0.pdf
691
+
692
+ if (chunk.type !== 'key') return;
693
+ if (!trackData.info.decoderConfig.colorSpace || !trackData.info.decoderConfig.colorSpace.matrix) return;
694
+
695
+ const bitstream = new Bitstream(chunk.data);
696
+
697
+ // Check if it's a "superframe"
698
+ if (bitstream.readBits(2) !== 0b10) return;
699
+
700
+ const profileLowBit = bitstream.readBits(1);
701
+ const profileHighBit = bitstream.readBits(1);
702
+ const profile = (profileHighBit << 1) + profileLowBit;
703
+
704
+ if (profile === 3) bitstream.skipBits(1);
705
+
706
+ const showExistingFrame = bitstream.readBits(1);
707
+ if (showExistingFrame) return;
708
+
709
+ const frameType = bitstream.readBits(1);
710
+ if (frameType !== 0) return; // Just to be sure
711
+
712
+ bitstream.skipBits(2);
713
+
714
+ const syncCode = bitstream.readBits(24);
715
+ if (syncCode !== 0x498342) return;
716
+
717
+ if (profile >= 2) bitstream.skipBits(1);
718
+
719
+ const colorSpaceID = {
720
+ rgb: 7,
721
+ bt709: 2,
722
+ bt470bg: 1,
723
+ smpte170m: 3,
724
+ }[trackData.info.decoderConfig.colorSpace.matrix];
725
+
726
+ // The bitstream position is now at the start of the color space bits.
727
+ // We can use the global writeBits function here as requested.
728
+ writeBits(chunk.data, bitstream.pos, bitstream.pos + 3, colorSpaceID);
729
+ }
730
+
731
+ /** Converts a read-only external chunk into an internal one for easier use. */
732
+ private createInternalChunk(
733
+ data: Uint8Array,
734
+ timestamp: number,
735
+ duration: number,
736
+ type: 'key' | 'delta',
737
+ additions: Uint8Array | null = null,
738
+ ) {
739
+ const internalChunk: InternalMediaChunk = {
740
+ data,
741
+ type,
742
+ timestamp,
743
+ duration,
744
+ additions,
745
+ };
746
+
747
+ return internalChunk;
748
+ }
749
+
750
+ /** Writes a block containing media data to the file. */
751
+ private writeBlock(trackData: MatroskaTrackData, chunk: InternalMediaChunk) {
752
+ // Due to the interlacing algorithm, this code will be run once we've seen one chunk from every media track.
753
+ if (!this.segment) {
754
+ this.createTracks();
755
+ this.createSegment();
756
+ }
757
+
758
+ const msTimestamp = Math.round(1000 * chunk.timestamp);
759
+
760
+ // We wanna only finalize this cluster (and begin a new one) if we know that each track will be able to
761
+ // start the new one with a key frame.
762
+ const keyFrameQueuedEverywhere = this.trackDatas.every((otherTrackData) => {
763
+ if (trackData === otherTrackData) {
764
+ return chunk.type === 'key';
765
+ }
766
+
767
+ const firstQueuedSample = otherTrackData.chunkQueue[0];
768
+ if (firstQueuedSample) {
769
+ return firstQueuedSample.type === 'key';
770
+ }
771
+
772
+ return otherTrackData.track.source._closed;
773
+ });
774
+
775
+ let shouldCreateNewCluster = false;
776
+ if (!this.currentCluster) {
777
+ shouldCreateNewCluster = true;
778
+ } else {
779
+ assert(this.currentClusterStartMsTimestamp !== null);
780
+ assert(this.currentClusterMaxMsTimestamp !== null);
781
+
782
+ const relativeTimestamp = msTimestamp - this.currentClusterStartMsTimestamp;
783
+
784
+ shouldCreateNewCluster = (
785
+ keyFrameQueuedEverywhere
786
+ // This check is required because that means there is already a block with this timestamp in the
787
+ // CURRENT chunk, meaning that starting the next cluster at the same timestamp is forbidden (since
788
+ // the already-written block would belong into it instead).
789
+ && msTimestamp > this.currentClusterMaxMsTimestamp
790
+ && relativeTimestamp >= 1000 * (this.format._options.minimumClusterDuration ?? 1)
791
+ )
792
+ // The cluster would exceed its maximum allowed length. This puts us in an unfortunate position and forces
793
+ // us to begin the next cluster with a delta frame. Although this is undesirable, it is not forbidden by the
794
+ // spec and is supported by players.
795
+ || relativeTimestamp > MAX_CLUSTER_TIMESTAMP_MS;
796
+ }
797
+
798
+ if (shouldCreateNewCluster) {
799
+ this.createNewCluster(msTimestamp);
800
+ }
801
+
802
+ const relativeTimestamp = msTimestamp - this.currentClusterStartMsTimestamp!;
803
+ if (relativeTimestamp < MIN_CLUSTER_TIMESTAMP_MS) {
804
+ // The block lies too far in the past, it's not representable within this cluster
805
+ return;
806
+ }
807
+
808
+ const prelude = new Uint8Array(4);
809
+ const view = new DataView(prelude.buffer);
810
+ // 0x80 to indicate it's the last byte of a multi-byte number
811
+ view.setUint8(0, 0x80 | trackData.track.id);
812
+ view.setInt16(1, relativeTimestamp, false);
813
+
814
+ const msDuration = Math.round(1000 * chunk.duration);
815
+
816
+ if (msDuration === 0 && !chunk.additions) {
817
+ // No duration or additions, we can write out a SimpleBlock
818
+ view.setUint8(3, Number(chunk.type === 'key') << 7); // Flags (keyframe flag only present for SimpleBlock)
819
+
820
+ const simpleBlock = { id: EBMLId.SimpleBlock, data: [
821
+ prelude,
822
+ chunk.data,
823
+ ] };
824
+ this.ebmlWriter.writeEBML(simpleBlock);
825
+ } else {
826
+ const blockGroup = { id: EBMLId.BlockGroup, data: [
827
+ { id: EBMLId.Block, data: [
828
+ prelude,
829
+ chunk.data,
830
+ ] },
831
+ chunk.type === 'delta'
832
+ ? {
833
+ id: EBMLId.ReferenceBlock,
834
+ data: new EBMLSignedInt(trackData.lastWrittenMsTimestamp! - msTimestamp),
835
+ }
836
+ : null,
837
+ chunk.additions
838
+ ? { id: EBMLId.BlockAdditions, data: [
839
+ { id: EBMLId.BlockMore, data: [
840
+ { id: EBMLId.BlockAdditional, data: chunk.additions },
841
+ { id: EBMLId.BlockAddID, data: 1 },
842
+ ] },
843
+ ] }
844
+ : null,
845
+ msDuration > 0 ? { id: EBMLId.BlockDuration, data: msDuration } : null,
846
+ ] };
847
+ this.ebmlWriter.writeEBML(blockGroup);
848
+ }
849
+
850
+ this.duration = Math.max(this.duration, msTimestamp + msDuration);
851
+ trackData.lastWrittenMsTimestamp = msTimestamp;
852
+
853
+ if (!this.trackDatasInCurrentCluster.has(trackData)) {
854
+ this.trackDatasInCurrentCluster.set(trackData, {
855
+ firstMsTimestamp: msTimestamp,
856
+ });
857
+ }
858
+ this.currentClusterMaxMsTimestamp = Math.max(this.currentClusterMaxMsTimestamp!, msTimestamp);
859
+ }
860
+
861
+ /** Creates a new Cluster element to contain media chunks. */
862
+ private createNewCluster(msTimestamp: number) {
863
+ if (this.currentCluster) {
864
+ this.finalizeCurrentCluster();
865
+ }
866
+
867
+ if (this.format._options.onCluster) {
868
+ this.writer.startTrackingWrites();
869
+ }
870
+
871
+ this.currentCluster = {
872
+ id: EBMLId.Cluster,
873
+ size: this.format._options.appendOnly ? -1 : CLUSTER_SIZE_BYTES,
874
+ data: [
875
+ { id: EBMLId.Timestamp, data: msTimestamp },
876
+ ],
877
+ };
878
+ this.ebmlWriter.writeEBML(this.currentCluster);
879
+
880
+ this.currentClusterStartMsTimestamp = msTimestamp;
881
+ this.currentClusterMaxMsTimestamp = msTimestamp;
882
+ this.trackDatasInCurrentCluster.clear();
883
+ }
884
+
885
+ private finalizeCurrentCluster() {
886
+ assert(this.currentCluster);
887
+
888
+ if (!this.format._options.appendOnly) {
889
+ const clusterSize = this.writer.getPos() - this.ebmlWriter.dataOffsets.get(this.currentCluster)!;
890
+ const endPos = this.writer.getPos();
891
+
892
+ // Write the size now that we know it
893
+ this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)! + 4);
894
+ this.ebmlWriter.writeVarInt(clusterSize, CLUSTER_SIZE_BYTES);
895
+ this.writer.seek(endPos);
896
+ }
897
+
898
+ if (this.format._options.onCluster) {
899
+ assert(this.currentClusterStartMsTimestamp !== null);
900
+
901
+ const { data, start } = this.writer.stopTrackingWrites();
902
+ this.format._options.onCluster(data, start, this.currentClusterStartMsTimestamp / 1000);
903
+ }
904
+
905
+ const clusterOffsetFromSegment
906
+ = this.ebmlWriter.offsets.get(this.currentCluster)! - this.segmentDataOffset;
907
+
908
+ // Group tracks by their first timestamp and create a CuePoint for each unique timestamp
909
+ const groupedByTimestamp = new Map<number, MatroskaTrackData[]>();
910
+ for (const [trackData, { firstMsTimestamp }] of this.trackDatasInCurrentCluster) {
911
+ if (!groupedByTimestamp.has(firstMsTimestamp)) {
912
+ groupedByTimestamp.set(firstMsTimestamp, []);
913
+ }
914
+ groupedByTimestamp.get(firstMsTimestamp)!.push(trackData);
915
+ }
916
+
917
+ const groupedAndSortedByTimestamp = [...groupedByTimestamp.entries()].sort((a, b) => a[0] - b[0]);
918
+
919
+ // Add CuePoints to the Cues element for better seeking
920
+ for (const [msTimestamp, trackDatas] of groupedAndSortedByTimestamp) {
921
+ assert(this.cues);
922
+ (this.cues.data as EBML[]).push({ id: EBMLId.CuePoint, data: [
923
+ { id: EBMLId.CueTime, data: msTimestamp },
924
+ // Create CueTrackPositions for each track that starts at this timestamp
925
+ ...trackDatas.map((trackData) => {
926
+ return { id: EBMLId.CueTrackPositions, data: [
927
+ { id: EBMLId.CueTrack, data: trackData.track.id },
928
+ { id: EBMLId.CueClusterPosition, data: clusterOffsetFromSegment },
929
+ ] };
930
+ }),
931
+ ] });
932
+ }
933
+ }
934
+
935
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
936
+ override async onTrackClose() {
937
+ const release = await this.mutex.acquire();
938
+
939
+ if (this.allTracksAreKnown()) {
940
+ this.allTracksKnown.resolve();
941
+ }
942
+
943
+ // Since a track is now closed, we may be able to write out chunks that were previously waiting
944
+ await this.interleaveChunks();
945
+
946
+ release();
947
+ }
948
+
949
+ /** Finalizes the file, making it ready for use. Must be called after all media chunks have been added. */
950
+ async finalize() {
951
+ const release = await this.mutex.acquire();
952
+
953
+ this.allTracksKnown.resolve();
954
+
955
+ if (!this.segment) {
956
+ this.createTracks();
957
+ this.createSegment();
958
+ }
959
+
960
+ // Flush any remaining queued chunks to the file
961
+ await this.interleaveChunks(true);
962
+
963
+ if (this.currentCluster) {
964
+ this.finalizeCurrentCluster();
965
+ }
966
+
967
+ assert(this.cues);
968
+ this.ebmlWriter.writeEBML(this.cues);
969
+
970
+ if (!this.format._options.appendOnly) {
971
+ const endPos = this.writer.getPos();
972
+
973
+ // Write the Segment size
974
+ const segmentSize = this.writer.getPos() - this.segmentDataOffset;
975
+ this.writer.seek(this.ebmlWriter.offsets.get(this.segment!)! + 4);
976
+ this.ebmlWriter.writeVarInt(segmentSize, SEGMENT_SIZE_BYTES);
977
+
978
+ // Write the duration of the media to the Segment
979
+ this.segmentDuration!.data = new EBMLFloat64(this.duration);
980
+ this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration!)!);
981
+ this.ebmlWriter.writeEBML(this.segmentDuration);
982
+
983
+ // Fill in SeekHead position data and write it again
984
+ this.seekHead!.data[0]!.data[1]!.data
985
+ = this.ebmlWriter.offsets.get(this.cues)! - this.segmentDataOffset;
986
+ this.seekHead!.data[1]!.data[1]!.data
987
+ = this.ebmlWriter.offsets.get(this.segmentInfo!)! - this.segmentDataOffset;
988
+ this.seekHead!.data[2]!.data[1]!.data
989
+ = this.ebmlWriter.offsets.get(this.tracksElement!)! - this.segmentDataOffset;
990
+
991
+ this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead!)!);
992
+ this.ebmlWriter.writeEBML(this.seekHead);
993
+
994
+ this.writer.seek(endPos);
995
+ }
996
+
997
+ release();
998
+ }
999
+ }