@remotion/media-parser 4.0.191

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 (143) hide show
  1. package/.eslintrc +8 -0
  2. package/LICENSE.md +49 -0
  3. package/README.md +18 -0
  4. package/dist/boxes/iso-base-media/base-type.d.ts +4 -0
  5. package/dist/boxes/iso-base-media/base-type.js +2 -0
  6. package/dist/boxes/iso-base-media/ftyp.d.ts +13 -0
  7. package/dist/boxes/iso-base-media/ftyp.js +22 -0
  8. package/dist/boxes/iso-base-media/moov/moov.d.ts +12 -0
  9. package/dist/boxes/iso-base-media/moov/moov.js +22 -0
  10. package/dist/boxes/iso-base-media/mvhd.d.ts +30 -0
  11. package/dist/boxes/iso-base-media/mvhd.js +59 -0
  12. package/dist/boxes/iso-base-media/process-box.d.ts +8 -0
  13. package/dist/boxes/iso-base-media/process-box.js +174 -0
  14. package/dist/boxes/iso-base-media/stsd/keys.d.ts +5 -0
  15. package/dist/boxes/iso-base-media/stsd/keys.js +21 -0
  16. package/dist/boxes/iso-base-media/stsd/mebx.d.ts +14 -0
  17. package/dist/boxes/iso-base-media/stsd/mebx.js +27 -0
  18. package/dist/boxes/iso-base-media/stsd/samples.d.ts +48 -0
  19. package/dist/boxes/iso-base-media/stsd/samples.js +215 -0
  20. package/dist/boxes/iso-base-media/stsd/stsd.d.ts +13 -0
  21. package/dist/boxes/iso-base-media/stsd/stsd.js +26 -0
  22. package/dist/boxes/iso-base-media/stts/stts.d.ts +15 -0
  23. package/dist/boxes/iso-base-media/stts/stts.js +35 -0
  24. package/dist/boxes/iso-base-media/tkhd.d.ts +22 -0
  25. package/dist/boxes/iso-base-media/tkhd.js +63 -0
  26. package/dist/boxes/iso-base-media/to-date.d.ts +1 -0
  27. package/dist/boxes/iso-base-media/to-date.js +11 -0
  28. package/dist/boxes/iso-base-media/trak/trak.d.ts +12 -0
  29. package/dist/boxes/iso-base-media/trak/trak.js +22 -0
  30. package/dist/boxes/webm/parse-webm-header.d.ts +3 -0
  31. package/dist/boxes/webm/parse-webm-header.js +16 -0
  32. package/dist/boxes/webm/segments/duration.d.ts +6 -0
  33. package/dist/boxes/webm/segments/duration.js +15 -0
  34. package/dist/boxes/webm/segments/info.d.ts +8 -0
  35. package/dist/boxes/webm/segments/info.js +14 -0
  36. package/dist/boxes/webm/segments/main.d.ts +7 -0
  37. package/dist/boxes/webm/segments/main.js +13 -0
  38. package/dist/boxes/webm/segments/muxing.d.ts +6 -0
  39. package/dist/boxes/webm/segments/muxing.js +12 -0
  40. package/dist/boxes/webm/segments/parse-children.d.ts +3 -0
  41. package/dist/boxes/webm/segments/parse-children.js +17 -0
  42. package/dist/boxes/webm/segments/seek-head.d.ts +8 -0
  43. package/dist/boxes/webm/segments/seek-head.js +13 -0
  44. package/dist/boxes/webm/segments/seek-position.d.ts +6 -0
  45. package/dist/boxes/webm/segments/seek-position.js +12 -0
  46. package/dist/boxes/webm/segments/seek.d.ts +8 -0
  47. package/dist/boxes/webm/segments/seek.js +16 -0
  48. package/dist/boxes/webm/segments/timestamp-scale.d.ts +6 -0
  49. package/dist/boxes/webm/segments/timestamp-scale.js +11 -0
  50. package/dist/boxes/webm/segments/track-entry.d.ts +71 -0
  51. package/dist/boxes/webm/segments/track-entry.js +175 -0
  52. package/dist/boxes/webm/segments/tracks.d.ts +7 -0
  53. package/dist/boxes/webm/segments/tracks.js +13 -0
  54. package/dist/boxes/webm/segments/unknown.d.ts +6 -0
  55. package/dist/boxes/webm/segments/unknown.js +11 -0
  56. package/dist/boxes/webm/segments/void.d.ts +6 -0
  57. package/dist/boxes/webm/segments/void.js +12 -0
  58. package/dist/boxes/webm/segments/writing.d.ts +6 -0
  59. package/dist/boxes/webm/segments/writing.js +12 -0
  60. package/dist/boxes/webm/segments.d.ts +16 -0
  61. package/dist/boxes/webm/segments.js +106 -0
  62. package/dist/buffer-iterator.d.ts +36 -0
  63. package/dist/buffer-iterator.js +263 -0
  64. package/dist/from-node.d.ts +2 -0
  65. package/dist/from-node.js +19 -0
  66. package/dist/from-web.d.ts +2 -0
  67. package/dist/from-web.js +40 -0
  68. package/dist/get-dimensions.d.ts +7 -0
  69. package/dist/get-dimensions.js +104 -0
  70. package/dist/get-duration.d.ts +3 -0
  71. package/dist/get-duration.js +61 -0
  72. package/dist/get-fps.d.ts +3 -0
  73. package/dist/get-fps.js +70 -0
  74. package/dist/has-all-info.d.ts +3 -0
  75. package/dist/has-all-info.js +27 -0
  76. package/dist/index.d.ts +1 -0
  77. package/dist/index.js +5 -0
  78. package/dist/options.d.ts +19 -0
  79. package/dist/options.js +2 -0
  80. package/dist/parse-media.d.ts +2 -0
  81. package/dist/parse-media.js +44 -0
  82. package/dist/parse-result.d.ts +29 -0
  83. package/dist/parse-result.js +2 -0
  84. package/dist/parse-video.d.ts +10 -0
  85. package/dist/parse-video.js +29 -0
  86. package/dist/reader.d.ts +7 -0
  87. package/dist/reader.js +2 -0
  88. package/package.json +47 -0
  89. package/src/boxes/iso-base-media/base-type.ts +4 -0
  90. package/src/boxes/iso-base-media/ftyp.ts +39 -0
  91. package/src/boxes/iso-base-media/moov/moov.ts +37 -0
  92. package/src/boxes/iso-base-media/mvhd.ts +107 -0
  93. package/src/boxes/iso-base-media/process-box.ts +236 -0
  94. package/src/boxes/iso-base-media/stsd/keys.ts +25 -0
  95. package/src/boxes/iso-base-media/stsd/mebx.ts +46 -0
  96. package/src/boxes/iso-base-media/stsd/samples.ts +298 -0
  97. package/src/boxes/iso-base-media/stsd/stsd.ts +48 -0
  98. package/src/boxes/iso-base-media/stts/stts.ts +62 -0
  99. package/src/boxes/iso-base-media/tkhd.ts +105 -0
  100. package/src/boxes/iso-base-media/to-date.ts +9 -0
  101. package/src/boxes/iso-base-media/trak/trak.ts +37 -0
  102. package/src/boxes/webm/parse-webm-header.ts +18 -0
  103. package/src/boxes/webm/segments/duration.ts +22 -0
  104. package/src/boxes/webm/segments/info.ts +20 -0
  105. package/src/boxes/webm/segments/main.ts +19 -0
  106. package/src/boxes/webm/segments/muxing.ts +18 -0
  107. package/src/boxes/webm/segments/parse-children.ts +21 -0
  108. package/src/boxes/webm/segments/seek-head.ts +21 -0
  109. package/src/boxes/webm/segments/seek-position.ts +19 -0
  110. package/src/boxes/webm/segments/seek.ts +23 -0
  111. package/src/boxes/webm/segments/timestamp-scale.ts +17 -0
  112. package/src/boxes/webm/segments/track-entry.ts +295 -0
  113. package/src/boxes/webm/segments/tracks.ts +22 -0
  114. package/src/boxes/webm/segments/unknown.ts +19 -0
  115. package/src/boxes/webm/segments/void.ts +16 -0
  116. package/src/boxes/webm/segments/writing.ts +18 -0
  117. package/src/boxes/webm/segments.ts +206 -0
  118. package/src/buffer-iterator.ts +305 -0
  119. package/src/from-node.ts +22 -0
  120. package/src/from-web.ts +53 -0
  121. package/src/get-dimensions.ts +147 -0
  122. package/src/get-duration.ts +73 -0
  123. package/src/get-fps.ts +92 -0
  124. package/src/has-all-info.ts +34 -0
  125. package/src/index.ts +1 -0
  126. package/src/options.ts +38 -0
  127. package/src/parse-media.ts +57 -0
  128. package/src/parse-result.ts +44 -0
  129. package/src/parse-video.ts +41 -0
  130. package/src/reader.ts +10 -0
  131. package/src/test/duration.test.ts +34 -0
  132. package/src/test/keys.test.ts +47 -0
  133. package/src/test/matroska.test.ts +163 -0
  134. package/src/test/mvhd.test.ts +89 -0
  135. package/src/test/parse-stts.test.ts +38 -0
  136. package/src/test/parse-video.test.ts +113 -0
  137. package/src/test/parse-webm.test.ts +15 -0
  138. package/src/test/stream-local.test.ts +105 -0
  139. package/src/test/stream-remote.test.ts +12 -0
  140. package/src/test/stsd.test.ts +162 -0
  141. package/src/test/tkhd.test.ts +84 -0
  142. package/tsconfig.json +10 -0
  143. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,305 @@
1
+ export class OffsetCounter {
2
+ #offset: number;
3
+ #discardedBytes: number;
4
+ constructor(initial: number) {
5
+ this.#offset = initial;
6
+ this.#discardedBytes = 0;
7
+ }
8
+
9
+ increment(amount: number) {
10
+ if (amount < 0) {
11
+ throw new Error('Cannot increment by a negative amount: ' + amount);
12
+ }
13
+
14
+ this.#offset += amount;
15
+ }
16
+
17
+ getOffset(): number {
18
+ return this.#offset;
19
+ }
20
+
21
+ getDiscardedOffset(): number {
22
+ return this.#offset - this.#discardedBytes;
23
+ }
24
+
25
+ discardBytes(amount: number) {
26
+ this.#discardedBytes += amount;
27
+ }
28
+
29
+ decrement(amount: number) {
30
+ if (amount < 0) {
31
+ throw new Error('Cannot decrement by a negative amount');
32
+ }
33
+
34
+ this.#offset -= amount;
35
+ }
36
+ }
37
+
38
+ const isoBaseMediaMp4Pattern = new TextEncoder().encode('ftyp');
39
+ const webmPattern = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]);
40
+
41
+ const matchesPattern = (pattern: Uint8Array) => {
42
+ return (data: Uint8Array) => {
43
+ return pattern.every((value, index) => data[index] === value);
44
+ };
45
+ };
46
+
47
+ const makeOffsetCounter = (): OffsetCounter => {
48
+ return new OffsetCounter(0);
49
+ };
50
+
51
+ export const getArrayBufferIterator = (initialData: Uint8Array) => {
52
+ let data = initialData;
53
+ let view = new DataView(data.buffer);
54
+ const counter = makeOffsetCounter();
55
+
56
+ const getSlice = (amount: number) => {
57
+ const value = data.slice(
58
+ counter.getDiscardedOffset(),
59
+ counter.getDiscardedOffset() + amount,
60
+ );
61
+ counter.increment(amount);
62
+
63
+ return value;
64
+ };
65
+
66
+ const getUint8 = () => {
67
+ const val = view.getUint8(counter.getDiscardedOffset());
68
+ counter.increment(1);
69
+
70
+ return val;
71
+ };
72
+
73
+ const getFourByteNumber = () => {
74
+ return (
75
+ (getUint8() << 24) | (getUint8() << 16) | (getUint8() << 8) | getUint8()
76
+ );
77
+ };
78
+
79
+ const getUint32 = () => {
80
+ const val = view.getUint32(counter.getDiscardedOffset());
81
+ counter.increment(4);
82
+ return val;
83
+ };
84
+
85
+ const addData = (newData: Uint8Array) => {
86
+ const newArray = new Uint8Array(
87
+ data.buffer.byteLength + newData.byteLength,
88
+ );
89
+ newArray.set(data);
90
+ newArray.set(new Uint8Array(newData), data.byteLength);
91
+ data = newArray;
92
+ view = new DataView(data.buffer);
93
+ };
94
+
95
+ const byteLength = () => {
96
+ return data.byteLength;
97
+ };
98
+
99
+ const bytesRemaining = () => {
100
+ return data.byteLength - counter.getDiscardedOffset();
101
+ };
102
+
103
+ const isIsoBaseMedia = () => {
104
+ return matchesPattern(isoBaseMediaMp4Pattern)(data.subarray(4, 8));
105
+ };
106
+
107
+ const isWebm = () => {
108
+ return matchesPattern(webmPattern)(data.subarray(0, 4));
109
+ };
110
+
111
+ const removeBytesRead = () => {
112
+ const bytesToRemove = counter.getDiscardedOffset();
113
+ counter.discardBytes(bytesToRemove);
114
+ const newArray = new Uint8Array(data.buffer.byteLength - bytesToRemove);
115
+ newArray.set(data.slice(bytesToRemove));
116
+ data = newArray;
117
+ view = new DataView(data.buffer);
118
+ };
119
+
120
+ return {
121
+ addData,
122
+ counter,
123
+ byteLength,
124
+ bytesRemaining,
125
+ isIsoBaseMedia,
126
+ discardFirstBytes: removeBytesRead,
127
+ isWebm,
128
+ discard: (length: number) => {
129
+ counter.increment(length);
130
+ },
131
+ getFourByteNumber,
132
+ getSlice,
133
+ getAtom: () => {
134
+ const atom = getSlice(4);
135
+ return new TextDecoder().decode(atom);
136
+ },
137
+ getMatroskaSegmentId: () => {
138
+ const first = getSlice(1);
139
+ const firstOneString = `0x${Array.from(new Uint8Array(first))
140
+ .map((b) => {
141
+ return b.toString(16).padStart(2, '0');
142
+ })
143
+ .join('')}`;
144
+
145
+ // Catch void block
146
+ // https://www.matroska.org/technical/elements.html
147
+ const knownIdsWithOneLength = [
148
+ '0xec',
149
+ '0xae',
150
+ '0xd7',
151
+ '0x9c',
152
+ '0x86',
153
+ '0x83',
154
+ '0xe0',
155
+ '0xb0',
156
+ '0xba',
157
+ ];
158
+ if (knownIdsWithOneLength.includes(firstOneString)) {
159
+ return firstOneString;
160
+ }
161
+
162
+ const firstTwo = getSlice(1);
163
+
164
+ const knownIdsWithTwoLength = [
165
+ '0x4dbb',
166
+ '0x53ac',
167
+ '0xec01',
168
+ '0x73c5',
169
+ '0x53c0',
170
+ '0x4d80',
171
+ '0x5741',
172
+ '0x4489',
173
+ '0x55ee',
174
+ '0x55b0',
175
+ ];
176
+
177
+ const firstTwoString = `${firstOneString}${Array.from(
178
+ new Uint8Array(firstTwo),
179
+ )
180
+ .map((b) => {
181
+ return b.toString(16).padStart(2, '0');
182
+ })
183
+ .join('')}`;
184
+
185
+ if (knownIdsWithTwoLength.includes(firstTwoString)) {
186
+ return firstTwoString;
187
+ }
188
+
189
+ const knownIdsWithThreeLength = [
190
+ '0x4d808c',
191
+ '0x57418c',
192
+ '0x448988',
193
+ '0x22b59c',
194
+ '0x23e383',
195
+ ];
196
+
197
+ const firstThree = getSlice(1);
198
+
199
+ const firstThreeString = `${firstTwoString}${Array.from(
200
+ new Uint8Array(firstThree),
201
+ )
202
+ .map((b) => {
203
+ return b.toString(16).padStart(2, '0');
204
+ })
205
+ .join('')}`;
206
+
207
+ if (knownIdsWithThreeLength.includes(firstThreeString)) {
208
+ return firstThreeString;
209
+ }
210
+
211
+ const segmentId = getSlice(1);
212
+
213
+ return `${firstThreeString}${Array.from(new Uint8Array(segmentId))
214
+ .map((b) => {
215
+ return b.toString(16).padStart(2, '0');
216
+ })
217
+ .join('')}`;
218
+ },
219
+ getVint: () => {
220
+ const firstByte = getUint8();
221
+ const totalLength = firstByte;
222
+
223
+ if (totalLength === 0) {
224
+ return 0;
225
+ }
226
+
227
+ // Calculate the actual length of the data based on the first set bit
228
+ let actualLength = 0;
229
+ while (((totalLength >> (7 - actualLength)) & 0x01) === 0) {
230
+ actualLength++;
231
+ }
232
+
233
+ const slice = getSlice(actualLength);
234
+ const d = [firstByte, ...Array.from(new Uint8Array(slice))];
235
+
236
+ actualLength += 1; // Include the first byte set as 1
237
+ // Combine the numbers to form the integer value
238
+ let value = 0;
239
+
240
+ // Mask the first byte properly then start combining
241
+ value = totalLength & (0xff >> actualLength);
242
+ for (let i = 1; i < actualLength; i++) {
243
+ value = (value << 8) | d[i];
244
+ }
245
+
246
+ return value;
247
+ },
248
+ getUint8,
249
+ getEBML: () => {
250
+ const val = getUint8();
251
+
252
+ // https://darkcoding.net/software/reading-mediarecorders-webm-opus-output/#:~:text=The%20first%20four%20bytes%20(%201A,%E2%80%93%20read%20on%20for%20why).
253
+ // You drop the initial 0 bits and the first 1 bit to get the value. 0x81 is 0b10000001, so there are zero inital 0 bits, meaning length one byte, and the value is 1. The 0x9F value for length of the EBML header we saw earlier is 0b10011111, still one byte, value is 0b0011111, which is 31 (the python repl is very helpful for these conversions).
254
+ const actualValue = val & 0x7f; // 0x7F is binary 01111111, which masks out the first bit
255
+
256
+ return actualValue;
257
+ },
258
+ getInt8: () => {
259
+ const val = view.getInt8(counter.getDiscardedOffset());
260
+ counter.increment(1);
261
+ return val;
262
+ },
263
+ getUint16: () => {
264
+ const val = view.getUint16(counter.getDiscardedOffset());
265
+ counter.increment(2);
266
+ return val;
267
+ },
268
+ getInt16: () => {
269
+ const val = view.getInt16(counter.getDiscardedOffset());
270
+ counter.increment(2);
271
+ return val;
272
+ },
273
+ getUint32,
274
+ // https://developer.apple.com/documentation/quicktime-file-format/sound_sample_description_version_1
275
+ // A 32-bit unsigned fixed-point number (16.16) that indicates the rate at which the sound samples were obtained.
276
+ getFixedPoint1616Number: () => {
277
+ const val = getUint32();
278
+ return val / 2 ** 16;
279
+ },
280
+ getPascalString: () => {
281
+ const val = getSlice(32);
282
+ return [...Array.from(new Uint8Array(val))];
283
+ },
284
+ getDecimalBytes(length: number): number {
285
+ const bytes = getSlice(length);
286
+ const numbers = [...Array.from(new Uint8Array(bytes))];
287
+ return numbers.reduce(
288
+ (acc, byte, index) =>
289
+ acc + (byte << (8 * (numbers.length - index - 1))),
290
+ 0,
291
+ );
292
+ },
293
+ getByteString(length: number): string {
294
+ const bytes = getSlice(length);
295
+ return new TextDecoder().decode(bytes).trim();
296
+ },
297
+ getFloat64: () => {
298
+ const val = view.getFloat64(counter.getDiscardedOffset());
299
+ counter.increment(8);
300
+ return val;
301
+ },
302
+ };
303
+ };
304
+
305
+ export type BufferIterator = ReturnType<typeof getArrayBufferIterator>;
@@ -0,0 +1,22 @@
1
+ import {createReadStream} from 'fs';
2
+ import {stat} from 'node:fs/promises';
3
+ import {Readable} from 'stream';
4
+ import type {ReaderInterface} from './reader';
5
+
6
+ export const nodeReader: ReaderInterface = {
7
+ read: (src, range) => {
8
+ const stream = createReadStream(src, {
9
+ start: range === null ? 0 : range[0],
10
+ end: range === null ? Infinity : range[1],
11
+ });
12
+ return Promise.resolve(
13
+ Readable.toWeb(
14
+ stream,
15
+ ).getReader() as ReadableStreamDefaultReader<Uint8Array>,
16
+ );
17
+ },
18
+ getLength: async (src) => {
19
+ const stats = await stat(src);
20
+ return stats.size;
21
+ },
22
+ };
@@ -0,0 +1,53 @@
1
+ import type {ReaderInterface} from './reader';
2
+
3
+ export const webReader: ReaderInterface = {
4
+ read: async (src, range) => {
5
+ const resolvedUrl =
6
+ typeof window !== 'undefined' && typeof window.location !== 'undefined'
7
+ ? new URL(src, window.location.origin).toString()
8
+ : src;
9
+
10
+ if (
11
+ !resolvedUrl.startsWith('https://') &&
12
+ !resolvedUrl.startsWith('http://')
13
+ ) {
14
+ return Promise.reject(
15
+ new Error(
16
+ resolvedUrl +
17
+ ' is not a URL - needs to start with http:// or https://. If you want to read a local file, pass `nodeReader` to parseMedia().',
18
+ ),
19
+ );
20
+ }
21
+
22
+ const res = await fetch(resolvedUrl, {
23
+ headers:
24
+ range === null
25
+ ? {}
26
+ : {
27
+ Range: `bytes=${`${range[0]}-${range[1]}`}`,
28
+ },
29
+ });
30
+ if (!res.body) {
31
+ throw new Error('No body');
32
+ }
33
+
34
+ const reader = res.body.getReader();
35
+
36
+ return reader;
37
+ },
38
+ getLength: async (src) => {
39
+ const res = await fetch(src, {
40
+ method: 'HEAD',
41
+ });
42
+ if (!res.body) {
43
+ throw new Error('No body');
44
+ }
45
+
46
+ const length = res.headers.get('content-length');
47
+ if (!length) {
48
+ throw new Error('No content-length');
49
+ }
50
+
51
+ return parseInt(length, 10);
52
+ },
53
+ };
@@ -0,0 +1,147 @@
1
+ import type {MainSegment} from './boxes/webm/segments/main';
2
+ import type {AnySegment} from './parse-result';
3
+
4
+ export type Dimensions = {
5
+ width: number;
6
+ height: number;
7
+ };
8
+
9
+ const getDimensionsFromMatroska = (segments: MainSegment): Dimensions => {
10
+ const tracksSegment = segments.children.find(
11
+ (b) => b.type === 'tracks-segment',
12
+ );
13
+ if (!tracksSegment || tracksSegment.type !== 'tracks-segment') {
14
+ throw new Error('No tracks segment');
15
+ }
16
+
17
+ // TODO: What if there are multiple video tracks, or audio track is first?
18
+ const trackEntrySegment = tracksSegment.children.find(
19
+ (b) => b.type === 'track-entry-segment',
20
+ );
21
+ if (!trackEntrySegment || trackEntrySegment.type !== 'track-entry-segment') {
22
+ throw new Error('No track entry segment');
23
+ }
24
+
25
+ const videoSegment = trackEntrySegment.children.find(
26
+ (b) => b.type === 'video-segment',
27
+ );
28
+ if (!videoSegment || videoSegment.type !== 'video-segment') {
29
+ throw new Error('No video segment');
30
+ }
31
+
32
+ const widthSegment = videoSegment.children.find(
33
+ (b) => b.type === 'width-segment',
34
+ );
35
+ if (!widthSegment || widthSegment.type !== 'width-segment') {
36
+ throw new Error('No width segment');
37
+ }
38
+
39
+ const heightSegment = videoSegment.children.find(
40
+ (b) => b.type === 'height-segment',
41
+ );
42
+ if (!heightSegment || heightSegment.type !== 'height-segment') {
43
+ throw new Error('No height segment');
44
+ }
45
+
46
+ return {
47
+ width: widthSegment.width,
48
+ height: heightSegment.height,
49
+ };
50
+ };
51
+
52
+ export const getDimensions = (boxes: AnySegment[]): Dimensions => {
53
+ const matroskaBox = boxes.find((b) => b.type === 'main-segment');
54
+ if (matroskaBox && matroskaBox.type === 'main-segment') {
55
+ return getDimensionsFromMatroska(matroskaBox);
56
+ }
57
+
58
+ const moovBox = boxes.find((b) => b.type === 'moov-box');
59
+ if (!moovBox || moovBox.type !== 'moov-box') {
60
+ throw new Error('Expected moov box');
61
+ }
62
+
63
+ const {children} = moovBox;
64
+ if (!children) {
65
+ throw new Error('Expected moov box children');
66
+ }
67
+
68
+ const t = children.find((b) => b.type === 'trak-box');
69
+
70
+ if (!t || t.type !== 'trak-box') {
71
+ throw new Error('Expected trak box');
72
+ }
73
+
74
+ const mdiaBox = t.children.find(
75
+ (c) => c.type === 'regular-box' && c.boxType === 'mdia',
76
+ );
77
+ const tkhdBox = t.children.find((c) => c.type === 'tkhd-box');
78
+ if (tkhdBox && tkhdBox.type === 'tkhd-box') {
79
+ return {
80
+ width: tkhdBox.width,
81
+ height: tkhdBox.height,
82
+ };
83
+ }
84
+
85
+ if (!mdiaBox) {
86
+ throw new Error('Expected mdia box');
87
+ }
88
+
89
+ if (mdiaBox.type !== 'regular-box') {
90
+ throw new Error('Expected mdia box');
91
+ }
92
+
93
+ const minfBox = mdiaBox.children.find(
94
+ (c) => c.type === 'regular-box' && c.boxType === 'minf',
95
+ );
96
+ if (!minfBox) {
97
+ throw new Error('Expected minf box');
98
+ }
99
+
100
+ if (minfBox.type !== 'regular-box') {
101
+ throw new Error('Expected minf box');
102
+ }
103
+
104
+ const stblBox = minfBox.children.find(
105
+ (c) => c.type === 'regular-box' && c.boxType === 'stbl',
106
+ );
107
+
108
+ if (!stblBox) {
109
+ throw new Error('Expected stbl box');
110
+ }
111
+
112
+ if (stblBox.type !== 'regular-box') {
113
+ throw new Error('Expected stbl box');
114
+ }
115
+
116
+ const stsdBox = stblBox.children.find((c) => c.type === 'stsd-box');
117
+
118
+ if (!stsdBox) {
119
+ throw new Error('Expected stsd box');
120
+ }
121
+
122
+ if (stsdBox.type !== 'stsd-box') {
123
+ throw new Error('Expected stsd box');
124
+ }
125
+
126
+ const videoSamples = stsdBox.samples.filter((s) => s.type === 'video');
127
+ if (videoSamples.length === 0) {
128
+ throw new Error('Has no video stream');
129
+ }
130
+
131
+ const [firstTrack] = videoSamples;
132
+ if (firstTrack.type !== 'video') {
133
+ throw new Error('Expected video track');
134
+ }
135
+
136
+ return {width: firstTrack.width, height: firstTrack.height};
137
+ };
138
+
139
+ // TODO: An audio track should return 'hasDimensions' = true on an audio file
140
+ // and stop parsing
141
+ export const hasDimensions = (boxes: AnySegment[]): boolean => {
142
+ try {
143
+ return getDimensions(boxes) !== null;
144
+ } catch (err) {
145
+ return false;
146
+ }
147
+ };
@@ -0,0 +1,73 @@
1
+ import type {AnySegment} from './parse-result';
2
+
3
+ const getDurationFromMatroska = (segments: AnySegment[]): number | null => {
4
+ const mainSegment = segments.find((s) => s.type === 'main-segment');
5
+ if (!mainSegment || mainSegment.type !== 'main-segment') {
6
+ return null;
7
+ }
8
+
9
+ const {children} = mainSegment;
10
+ if (!children) {
11
+ return null;
12
+ }
13
+
14
+ const infoSegment = children.find((s) => s.type === 'info-segment');
15
+
16
+ const relevantBoxes = [
17
+ ...mainSegment.children,
18
+ ...(infoSegment && infoSegment.type === 'info-segment'
19
+ ? infoSegment.children
20
+ : []),
21
+ ];
22
+
23
+ const timestampScale = relevantBoxes.find(
24
+ (s) => s.type === 'timestamp-scale-segment',
25
+ );
26
+ if (!timestampScale || timestampScale.type !== 'timestamp-scale-segment') {
27
+ return null;
28
+ }
29
+
30
+ const duration = relevantBoxes.find((s) => s.type === 'duration-segment');
31
+ if (!duration || duration.type !== 'duration-segment') {
32
+ return null;
33
+ }
34
+
35
+ return (duration.duration / timestampScale.timestampScale) * 1000;
36
+ };
37
+
38
+ export const getDuration = (boxes: AnySegment[]): number | null => {
39
+ const matroskaBox = boxes.find((b) => b.type === 'main-segment');
40
+ if (matroskaBox) {
41
+ return getDurationFromMatroska(boxes);
42
+ }
43
+
44
+ const moovBox = boxes.find((b) => b.type === 'moov-box');
45
+ if (!moovBox || moovBox.type !== 'moov-box') {
46
+ return null;
47
+ }
48
+
49
+ const {children} = moovBox;
50
+ if (!children) {
51
+ return null;
52
+ }
53
+
54
+ const mvhdBox = children.find((b) => b.type === 'mvhd-box');
55
+
56
+ if (!mvhdBox) {
57
+ return null;
58
+ }
59
+
60
+ if (mvhdBox.type !== 'mvhd-box') {
61
+ throw new Error('Expected mvhd-box');
62
+ }
63
+
64
+ return mvhdBox.durationInSeconds;
65
+ };
66
+
67
+ export const hasDuration = (boxes: AnySegment[]): boolean => {
68
+ try {
69
+ return getDuration(boxes) !== null;
70
+ } catch (err) {
71
+ return false;
72
+ }
73
+ };
package/src/get-fps.ts ADDED
@@ -0,0 +1,92 @@
1
+ import type {SttsBox} from './boxes/iso-base-media/stts/stts';
2
+ import type {AnySegment} from './parse-result';
3
+
4
+ const calculateFps = (sttsBox: SttsBox, timeScale: number) => {
5
+ let sum = 0;
6
+ let totalSamples = 0;
7
+ for (const sample of sttsBox.sampleDistribution) {
8
+ sum += sample.sampleCount * sample.sampleDelta;
9
+ totalSamples += sample.sampleCount;
10
+ }
11
+
12
+ return timeScale / (sum / totalSamples);
13
+ };
14
+
15
+ export const getFps = (segments: AnySegment[]) => {
16
+ const moovBox = segments.find((s) => s.type === 'moov-box');
17
+ if (!moovBox || moovBox.type !== 'moov-box') {
18
+ return null;
19
+ }
20
+
21
+ const mvhdBox = moovBox.children.find((c) => c.type === 'mvhd-box');
22
+ if (!mvhdBox || mvhdBox.type !== 'mvhd-box') {
23
+ return null;
24
+ }
25
+
26
+ const {timeScale} = mvhdBox;
27
+
28
+ const {children} = moovBox;
29
+ const trackBoxes = children.filter((c) => c.type === 'trak-box');
30
+ if (!trackBoxes || trackBoxes.length === 0) {
31
+ return null;
32
+ }
33
+
34
+ // TODO: What if the video track is not the first track?
35
+ const trackBox = trackBoxes[0];
36
+ if (!trackBox || trackBox.type !== 'trak-box') {
37
+ return null;
38
+ }
39
+
40
+ const trackBoxChildren = trackBox.children;
41
+ if (!trackBoxChildren || trackBoxChildren.length === 0) {
42
+ return null;
43
+ }
44
+
45
+ const mdiaBox = trackBoxChildren.find(
46
+ (c) => c.type === 'regular-box' && c.boxType === 'mdia',
47
+ );
48
+ if (
49
+ !mdiaBox ||
50
+ mdiaBox.type !== 'regular-box' ||
51
+ mdiaBox.boxType !== 'mdia'
52
+ ) {
53
+ return null;
54
+ }
55
+
56
+ const minfBox = mdiaBox.children.find(
57
+ (c) => c.type === 'regular-box' && c.boxType === 'minf',
58
+ );
59
+ if (
60
+ !minfBox ||
61
+ minfBox.type !== 'regular-box' ||
62
+ minfBox.boxType !== 'minf'
63
+ ) {
64
+ return null;
65
+ }
66
+
67
+ const stblBox = minfBox.children.find(
68
+ (c) => c.type === 'regular-box' && c.boxType === 'stbl',
69
+ );
70
+ if (
71
+ !stblBox ||
72
+ stblBox.type !== 'regular-box' ||
73
+ stblBox.boxType !== 'stbl'
74
+ ) {
75
+ return null;
76
+ }
77
+
78
+ const sttsBox = stblBox.children.find((c) => c.type === 'stts-box');
79
+ if (!sttsBox || sttsBox.type !== 'stts-box') {
80
+ return null;
81
+ }
82
+
83
+ return calculateFps(sttsBox, timeScale);
84
+ };
85
+
86
+ export const hasFps = (boxes: AnySegment[]): boolean => {
87
+ try {
88
+ return getFps(boxes) !== null;
89
+ } catch (err) {
90
+ return false;
91
+ }
92
+ };