@editframe/assets 0.11.0-beta.9 → 0.12.0-beta.10

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.
package/dist/MP4File.d.ts CHANGED
@@ -10,7 +10,6 @@ export declare class MP4File extends MP4Box.ISOFile {
10
10
  track: number;
11
11
  segment: "init";
12
12
  data: ArrayBuffer;
13
- complete: false;
14
13
  cts?: undefined;
15
14
  dts?: undefined;
16
15
  duration?: undefined;
@@ -18,7 +17,6 @@ export declare class MP4File extends MP4Box.ISOFile {
18
17
  track: number;
19
18
  segment: number;
20
19
  data: ArrayBuffer;
21
- complete: boolean;
22
20
  cts: number;
23
21
  dts: number;
24
22
  duration: number;
package/dist/MP4File.js CHANGED
@@ -40,13 +40,13 @@ class MP4File extends MP4Box.ISOFile {
40
40
  await this.readyPromise;
41
41
  const trackInfo = {};
42
42
  for (const videoTrack of this.getInfo().videoTracks) {
43
- trackInfo[videoTrack.id] = { index: 0, complete: false };
43
+ trackInfo[videoTrack.id] = { index: 0 };
44
44
  this.setSegmentOptions(videoTrack.id, null, {
45
45
  rapAlignement: true
46
46
  });
47
47
  }
48
48
  for (const audioTrack of this.getInfo().audioTracks) {
49
- trackInfo[audioTrack.id] = { index: 0, complete: false };
49
+ trackInfo[audioTrack.id] = { index: 0 };
50
50
  const sampleRate = audioTrack.audio.sample_rate;
51
51
  const probablePacketSize = 1024;
52
52
  const probableFourSecondsOfSamples = Math.ceil(
@@ -61,21 +61,12 @@ class MP4File extends MP4Box.ISOFile {
61
61
  yield {
62
62
  track: initSegment.id,
63
63
  segment: "init",
64
- data: initSegment.buffer,
65
- complete: false
64
+ data: initSegment.buffer
66
65
  };
67
66
  }
68
67
  const fragmentStartSamples = {};
69
68
  let finishedReading = false;
70
- const allTracksFinished = () => {
71
- for (const fragmentedTrack of this.fragmentedTracks) {
72
- if (!trackInfo[fragmentedTrack.id]?.complete) {
73
- return false;
74
- }
75
- }
76
- return true;
77
- };
78
- while (!(finishedReading && allTracksFinished())) {
69
+ do {
79
70
  for (const fragTrak of this.fragmentedTracks) {
80
71
  const trak = fragTrak.trak;
81
72
  if (trak.nextSample === void 0) {
@@ -84,6 +75,8 @@ class MP4File extends MP4Box.ISOFile {
84
75
  if (trak.samples === void 0) {
85
76
  throw new Error("trak.samples is undefined");
86
77
  }
78
+ log("trak.nextSample", fragTrak.id, trak.nextSample);
79
+ log("trak.samples.length", fragTrak.id, trak.samples.length);
87
80
  while (trak.nextSample < trak.samples.length) {
88
81
  let result = void 0;
89
82
  const fragTrakNextSample = trak.samples[trak.nextSample];
@@ -120,22 +113,20 @@ class MP4File extends MP4Box.ISOFile {
120
113
  if (!trackInfoForFrag) {
121
114
  throw new Error("trackInfoForFrag is undefined");
122
115
  }
123
- if (trak.nextSample >= trak.samples.length) {
124
- trackInfoForFrag.complete = true;
125
- }
126
- log(
127
- `Yielding fragment #${trackInfoForFrag.index} for track=${fragTrak.id}`
128
- );
129
116
  const startSample = fragmentStartSamples[fragTrak.id];
130
117
  const endSample = trak.samples[trak.nextSample - 1];
131
118
  if (!startSample || !endSample) {
132
119
  throw new Error("startSample or endSample is undefined");
133
120
  }
121
+ log(
122
+ `Yielding fragment #${trackInfoForFrag.index} for track=${fragTrak.id}`,
123
+ `startTime=${startSample.cts}`,
124
+ `endTime=${endSample.cts + endSample.duration}`
125
+ );
134
126
  yield {
135
127
  track: fragTrak.id,
136
128
  segment: trackInfoForFrag.index,
137
129
  data: fragTrak.segmentStream.buffer,
138
- complete: trackInfoForFrag.complete,
139
130
  cts: startSample.cts,
140
131
  dts: startSample.dts,
141
132
  duration: endSample.cts - startSample.cts + endSample.duration
@@ -147,6 +138,68 @@ class MP4File extends MP4Box.ISOFile {
147
138
  }
148
139
  }
149
140
  finishedReading = await this.waitForMoreSamples();
141
+ } while (!finishedReading);
142
+ for (const fragTrak of this.fragmentedTracks) {
143
+ const trak = fragTrak.trak;
144
+ if (trak.nextSample === void 0) {
145
+ throw new Error("trak.nextSample is undefined");
146
+ }
147
+ if (trak.samples === void 0) {
148
+ throw new Error("trak.samples is undefined");
149
+ }
150
+ while (trak.nextSample < trak.samples.length) {
151
+ let result = void 0;
152
+ try {
153
+ result = this.createFragment(
154
+ fragTrak.id,
155
+ trak.nextSample,
156
+ fragTrak.segmentStream
157
+ );
158
+ } catch (error) {
159
+ console.error("Failed to createFragment", error);
160
+ }
161
+ if (result) {
162
+ fragTrak.segmentStream = result;
163
+ trak.nextSample++;
164
+ } else {
165
+ finishedReading = await this.waitForMoreSamples();
166
+ break;
167
+ }
168
+ const nextSample = trak.samples[trak.nextSample];
169
+ const emitSegment = (
170
+ // if rapAlignement is true, we emit a fragment when we have a rap sample coming up next
171
+ fragTrak.rapAlignement === true && nextSample?.is_sync || // if rapAlignement is false, we emit a fragment when we have the required number of samples
172
+ !fragTrak.rapAlignement && trak.nextSample % fragTrak.nb_samples === 0 || // if we have more samples than the number of samples requested, we emit the fragment
173
+ trak.nextSample >= trak.samples.length
174
+ );
175
+ if (emitSegment) {
176
+ const trackInfoForFrag = trackInfo[fragTrak.id];
177
+ if (!trackInfoForFrag) {
178
+ throw new Error("trackInfoForFrag is undefined");
179
+ }
180
+ const startSample = fragmentStartSamples[fragTrak.id];
181
+ const endSample = trak.samples[trak.nextSample - 1];
182
+ if (!startSample || !endSample) {
183
+ throw new Error("startSample or endSample is undefined");
184
+ }
185
+ log(
186
+ `Yielding fragment #${trackInfoForFrag.index} for track=${fragTrak.id}`,
187
+ `startTime=${startSample.cts}`,
188
+ `endTime=${endSample.cts + endSample.duration}`
189
+ );
190
+ yield {
191
+ track: fragTrak.id,
192
+ segment: trackInfoForFrag.index,
193
+ data: fragTrak.segmentStream.buffer,
194
+ cts: startSample.cts,
195
+ dts: startSample.dts,
196
+ duration: endSample.cts - startSample.cts + endSample.duration
197
+ };
198
+ trackInfoForFrag.index += 1;
199
+ fragTrak.segmentStream = null;
200
+ delete fragmentStartSamples[fragTrak.id];
201
+ }
202
+ }
150
203
  }
151
204
  }
152
205
  waitForMoreSamples() {
package/dist/Probe.js CHANGED
@@ -84,8 +84,6 @@ class Probe {
84
84
  return new Probe(absolutePath, json);
85
85
  }
86
86
  static async probeStream(stream) {
87
- const probeCommand = "ffprobe -i pipe:0 -v error -show_format -show_streams -of json";
88
- log("Probing", probeCommand);
89
87
  const probe = spawn(
90
88
  "ffprobe",
91
89
  [
@@ -98,35 +96,52 @@ class Probe {
98
96
  "-of",
99
97
  "json"
100
98
  ],
101
- {
102
- stdio: ["pipe", "pipe", "pipe"]
103
- }
99
+ { stdio: ["pipe", "pipe", "pipe"] }
104
100
  );
105
101
  const chunks = [];
102
+ const processExit = new Promise((_, reject) => {
103
+ probe.on("exit", (code) => {
104
+ if (code !== 0) {
105
+ reject(new Error(`ffprobe exited with code ${code}`));
106
+ }
107
+ });
108
+ probe.on("error", (err) => reject(err));
109
+ });
106
110
  probe.stderr.on("data", (data) => {
107
111
  log(data.toString());
108
112
  });
109
113
  probe.stdout.on("data", (data) => {
110
114
  chunks.push(data);
111
115
  });
112
- stream.pipe(probe.stdin);
113
116
  probe.stdin.on("error", (error) => {
117
+ if (error.code === "EPIPE") {
118
+ log("ffprobe closed input pipe");
119
+ return;
120
+ }
114
121
  log("ffprobe stdin error", error);
115
122
  });
116
- const json = await new Promise((resolve, reject) => {
117
- probe.stdout.on("end", () => {
118
- stream.unpipe(probe.stdin);
119
- stream.destroy();
120
- try {
121
- const buffer = Buffer.concat(chunks).toString("utf8");
122
- log("Got probe from stream", buffer);
123
- resolve(JSON.parse(buffer));
124
- } catch (error) {
125
- reject(error);
126
- }
127
- });
128
- });
129
- return new Probe("pipe:0", json);
123
+ stream.pipe(probe.stdin);
124
+ try {
125
+ const json = await Promise.race([
126
+ new Promise((resolve, reject) => {
127
+ probe.stdout.on("end", () => {
128
+ try {
129
+ const buffer = Buffer.concat(chunks).toString("utf8");
130
+ log("Got probe from stream", buffer);
131
+ resolve(JSON.parse(buffer));
132
+ } catch (error) {
133
+ reject(error);
134
+ }
135
+ });
136
+ }),
137
+ processExit
138
+ ]);
139
+ return new Probe("pipe:0", json);
140
+ } finally {
141
+ stream.unpipe(probe.stdin);
142
+ probe.stdin.end();
143
+ stream.destroy();
144
+ }
130
145
  }
131
146
  get audioStreams() {
132
147
  return this.data.streams.filter(
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { AudioStreamSchema, VideoStreamSchema, Probe } from './Probe.ts';
2
- export type { StreamSchema, TrackSegment, TrackFragmentIndex, AudioTrackFragmentIndex, VideoTrackFragmentIndex, } from './Probe.ts';
1
+ export type { StreamSchema, AudioStreamSchema, VideoStreamSchema, TrackSegment, TrackFragmentIndex, AudioTrackFragmentIndex, VideoTrackFragmentIndex, } from './Probe.ts';
2
+ export { Probe } from './Probe.ts';
3
3
  export { md5FilePath, md5Directory, md5ReadStream, md5Buffer } from './md5.ts';
4
4
  export { generateTrackFragmentIndex, generateTrackFragmentIndexFromPath, } from './tasks/generateTrackFragmentIndex.ts';
5
5
  export { generateTrack, generateTrackFromPath } from './tasks/generateTrack.ts';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AudioStreamSchema, Probe, VideoStreamSchema } from "./Probe.js";
1
+ import { Probe } from "./Probe.js";
2
2
  import { md5Buffer, md5Directory, md5FilePath, md5ReadStream } from "./md5.js";
3
3
  import { generateTrackFragmentIndex, generateTrackFragmentIndexFromPath } from "./tasks/generateTrackFragmentIndex.js";
4
4
  import { generateTrack, generateTrackFromPath } from "./tasks/generateTrack.js";
@@ -6,10 +6,8 @@ import { findOrCreateCaptions, generateCaptionDataFromPath } from "./tasks/findO
6
6
  import { cacheImage } from "./tasks/cacheImage.js";
7
7
  import { VideoRenderOptions } from "./VideoRenderOptions.js";
8
8
  export {
9
- AudioStreamSchema,
10
9
  Probe,
11
10
  VideoRenderOptions,
12
- VideoStreamSchema,
13
11
  cacheImage,
14
12
  findOrCreateCaptions,
15
13
  generateCaptionDataFromPath,
@@ -10,20 +10,37 @@ const generateTrackFromPath = async (absolutePath, trackId) => {
10
10
  const probe = await Probe.probePath(absolutePath);
11
11
  const readStream = probe.createConformingReadstream();
12
12
  const mp4File = new MP4File();
13
+ const trackStream = new PassThrough();
13
14
  log(`Generating track for ${absolutePath}`);
14
15
  readStream.pipe(mp4FileWritable(mp4File));
15
- await new Promise((resolve, reject) => {
16
- readStream.on("end", resolve);
17
- readStream.on("error", reject);
18
- });
19
- const trackStream = new PassThrough();
20
- for await (const fragment of mp4File.fragmentIterator()) {
21
- if (fragment.track !== trackId) {
22
- continue;
16
+ (async () => {
17
+ try {
18
+ let bytesWritten = 0;
19
+ for await (const fragment of mp4File.fragmentIterator()) {
20
+ log("Writing fragment", fragment);
21
+ if (fragment.track === trackId) {
22
+ const written = trackStream.write(
23
+ Buffer.from(fragment.data),
24
+ "binary"
25
+ );
26
+ if (!written) {
27
+ log(`Waiting for drain for track ${trackId}`);
28
+ await new Promise((resolve) => trackStream.once("drain", resolve));
29
+ }
30
+ bytesWritten += fragment.data.byteLength;
31
+ }
32
+ if (!readStream.readableEnded) {
33
+ await Promise.race([
34
+ new Promise((resolve) => readStream.once("end", resolve)),
35
+ new Promise((resolve) => readStream.once("data", resolve))
36
+ ]);
37
+ }
38
+ }
39
+ trackStream.end();
40
+ } catch (error) {
41
+ trackStream.destroy(error);
23
42
  }
24
- trackStream.write(Buffer.from(fragment.data), "binary");
25
- }
26
- trackStream.end();
43
+ })();
27
44
  return trackStream;
28
45
  };
29
46
  const generateTrackTask = idempotentTask({
@@ -33,9 +50,9 @@ const generateTrackTask = idempotentTask({
33
50
  });
34
51
  const generateTrack = async (cacheRoot, absolutePath, url) => {
35
52
  try {
36
- const trackId = new URL(
37
- `http://localhost${url}` ?? "bad-url"
38
- ).searchParams.get("trackId");
53
+ const trackId = new URL(`http://localhost${url}`).searchParams.get(
54
+ "trackId"
55
+ );
39
56
  if (trackId === null) {
40
57
  throw new Error(
41
58
  "No trackId provided. IT must be specified in the query string: ?trackId=0"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@editframe/assets",
3
- "version": "0.11.0-beta.9",
3
+ "version": "0.12.0-beta.10",
4
4
  "description": "",
5
5
  "exports": {
6
6
  ".": {
@@ -14,24 +14,46 @@ export const generateTrackFromPath = async (
14
14
  const probe = await Probe.probePath(absolutePath);
15
15
  const readStream = probe.createConformingReadstream();
16
16
  const mp4File = new MP4File();
17
+ const trackStream = new PassThrough();
17
18
 
18
19
  log(`Generating track for ${absolutePath}`);
20
+
21
+ // Set up pipe and processing of fragments
19
22
  readStream.pipe(mp4FileWritable(mp4File));
20
23
 
21
- await new Promise((resolve, reject) => {
22
- readStream.on("end", resolve);
23
- readStream.on("error", reject);
24
- });
24
+ // Process fragments as they become available
25
+ (async () => {
26
+ try {
27
+ let bytesWritten = 0;
28
+ for await (const fragment of mp4File.fragmentIterator()) {
29
+ log("Writing fragment", fragment);
30
+ if (fragment.track === trackId) {
31
+ const written = trackStream.write(
32
+ Buffer.from(fragment.data),
33
+ "binary",
34
+ );
35
+ if (!written) {
36
+ log(`Waiting for drain for track ${trackId}`);
37
+ await new Promise((resolve) => trackStream.once("drain", resolve));
38
+ }
39
+ bytesWritten += fragment.data.byteLength;
40
+ }
41
+ // There is a race condition where the mp4file writable doesn't correctly wait for the whole readSTream
42
+ // Waiting for data/end events seems to fix it
43
+ // FIXME: This is a hack, we should fix the root issue in MP4File
44
+ if (!readStream.readableEnded) {
45
+ await Promise.race([
46
+ new Promise((resolve) => readStream.once("end", resolve)),
47
+ new Promise((resolve) => readStream.once("data", resolve)),
48
+ ]);
49
+ }
50
+ }
25
51
 
26
- const trackStream = new PassThrough();
27
-
28
- for await (const fragment of mp4File.fragmentIterator()) {
29
- if (fragment.track !== trackId) {
30
- continue;
52
+ trackStream.end();
53
+ } catch (error) {
54
+ trackStream.destroy(error as Error);
31
55
  }
32
- trackStream.write(Buffer.from(fragment.data), "binary");
33
- }
34
- trackStream.end();
56
+ })();
35
57
 
36
58
  return trackStream;
37
59
  };
@@ -49,9 +71,9 @@ export const generateTrack = async (
49
71
  url: string,
50
72
  ) => {
51
73
  try {
52
- const trackId = new URL(
53
- `http://localhost${url}` ?? "bad-url",
54
- ).searchParams.get("trackId");
74
+ const trackId = new URL(`http://localhost${url}`).searchParams.get(
75
+ "trackId",
76
+ );
55
77
  if (trackId === null) {
56
78
  throw new Error(
57
79
  "No trackId provided. IT must be specified in the query string: ?trackId=0",