mediascale-sdk 1.0.5 → 1.0.7
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/docs/integration.md +100 -19
- package/package.json +1 -1
- package/src/client.js +164 -50
- package/src/index.js +1 -0
- package/src/record-compositor.js +137 -0
- package/src/record-frame-compositor.js +97 -0
- package/src/record-worker.js +89 -0
- package/src/record.js +358 -91
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
let nextRequest = 0;
|
|
2
|
+
|
|
3
|
+
function request(worker, message, transfer = [], timeoutMs = 3000) {
|
|
4
|
+
return new Promise((resolve, reject) => {
|
|
5
|
+
const requestId = ++nextRequest;
|
|
6
|
+
const finish = (failure, data) => {
|
|
7
|
+
clearTimeout(timer);
|
|
8
|
+
worker.removeEventListener("message", receive);
|
|
9
|
+
worker.removeEventListener("error", failed);
|
|
10
|
+
failure ? reject(failure) : resolve(data);
|
|
11
|
+
};
|
|
12
|
+
const receive = ({ data }) => {
|
|
13
|
+
if (data.type === "error") finish(new Error(data.message));
|
|
14
|
+
else if (data.requestId === requestId) finish(null, data);
|
|
15
|
+
};
|
|
16
|
+
const failed = () => finish(new Error("Recording worker could not start"));
|
|
17
|
+
const timer = setTimeout(() => finish(new Error("Recording frame transfer probe timed out")), timeoutMs);
|
|
18
|
+
worker.addEventListener("message", receive);
|
|
19
|
+
worker.addEventListener("error", failed);
|
|
20
|
+
try { worker.postMessage({ ...message, requestId }, transfer); }
|
|
21
|
+
catch (failure) { finish(failure); }
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function bounded(promise, timeoutMs) {
|
|
26
|
+
let timer;
|
|
27
|
+
return Promise.race([promise, new Promise((_, reject) => {
|
|
28
|
+
timer = setTimeout(() => reject(new Error("Recording frame transfer probe timed out")), timeoutMs);
|
|
29
|
+
})]).finally(() => clearTimeout(timer));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Probe real frame transfer before selecting the background-capable compositor. */
|
|
33
|
+
export async function createWorkerCompositor({ width, height, fps, onError = () => {} }) {
|
|
34
|
+
let worker, output, probeInput, probeClone, outputProbe, reader, inputWriter, probeFrame;
|
|
35
|
+
const deadline = Date.now() + 3000;
|
|
36
|
+
const remaining = () => Math.max(1, deadline - Date.now());
|
|
37
|
+
const ask = (message, transfer = []) => request(worker, message, transfer, remaining());
|
|
38
|
+
try {
|
|
39
|
+
if (typeof Worker !== "function" || typeof OffscreenCanvas !== "function" || typeof VideoFrame !== "function") throw new Error("Native recording frame APIs are unavailable");
|
|
40
|
+
worker = new Worker(new URL("./record-worker.js", import.meta.url), { type: "module" });
|
|
41
|
+
const { standard } = await ask({ type: "capabilities" });
|
|
42
|
+
if (standard) {
|
|
43
|
+
const ready = await ask({ type: "init", standard: true, width, height, fps });
|
|
44
|
+
output = ready.track;
|
|
45
|
+
const canvas = document.createElement("canvas");
|
|
46
|
+
canvas.width = canvas.height = 2;
|
|
47
|
+
probeInput = canvas.captureStream(0).getVideoTracks()[0];
|
|
48
|
+
const probing = ask({ type: "probe", track: probeInput }, [probeInput]);
|
|
49
|
+
canvas.getContext("2d").fillRect(0, 0, 2, 2);
|
|
50
|
+
probeInput.requestFrame?.();
|
|
51
|
+
await probing;
|
|
52
|
+
} else {
|
|
53
|
+
if (typeof MediaStreamTrackProcessor !== "function" || typeof MediaStreamTrackGenerator !== "function") throw new Error("Native recording track processor/generator are unavailable");
|
|
54
|
+
output = new MediaStreamTrackGenerator({ kind: "video" });
|
|
55
|
+
await ask({ type: "init", width, height, fps, writable: output.writable }, [output.writable]);
|
|
56
|
+
outputProbe = output.clone();
|
|
57
|
+
reader = new MediaStreamTrackProcessor({ track: outputProbe, maxBufferSize: 1 }).readable.getReader();
|
|
58
|
+
const received = reader.read();
|
|
59
|
+
probeInput = new MediaStreamTrackGenerator({ kind: "video" });
|
|
60
|
+
probeClone = probeInput.clone();
|
|
61
|
+
const readable = new MediaStreamTrackProcessor({ track: probeClone, maxBufferSize: 1 }).readable;
|
|
62
|
+
const probing = ask({ type: "probe", readable }, [readable]);
|
|
63
|
+
// Construction/write failures must still consume the outstanding probe rejection.
|
|
64
|
+
void probing.catch(() => {});
|
|
65
|
+
inputWriter = probeInput.writable.getWriter();
|
|
66
|
+
const surface = new OffscreenCanvas(2, 2);
|
|
67
|
+
surface.getContext("2d").fillRect(0, 0, 2, 2);
|
|
68
|
+
probeFrame = new VideoFrame(surface, { timestamp: 0 });
|
|
69
|
+
await bounded(Promise.all([inputWriter.write(probeFrame), probing]), remaining());
|
|
70
|
+
probeFrame.close();
|
|
71
|
+
probeFrame = null;
|
|
72
|
+
inputWriter.releaseLock();
|
|
73
|
+
inputWriter = null;
|
|
74
|
+
const { value, done } = await bounded(received, remaining());
|
|
75
|
+
if (done || !value?.displayWidth) throw new Error("Recording output frame probe produced no video");
|
|
76
|
+
value.close();
|
|
77
|
+
}
|
|
78
|
+
let active = false, closed = false, sources = [];
|
|
79
|
+
const owned = new Map();
|
|
80
|
+
const release = (entry) => { try { entry.clone.stop(); } catch {} };
|
|
81
|
+
const sync = () => {
|
|
82
|
+
const desired = active ? sources : [];
|
|
83
|
+
const keys = new Set(desired.map((source) => source.key));
|
|
84
|
+
for (const [key, entry] of owned) if (!keys.has(key)) { release(entry); owned.delete(key); }
|
|
85
|
+
const transfer = [];
|
|
86
|
+
const updates = desired.map(({ key, track, rect, crop }) => {
|
|
87
|
+
const previous = owned.get(key);
|
|
88
|
+
if (previous?.original === track) return { key, rect, crop: crop || null };
|
|
89
|
+
if (previous) release(previous);
|
|
90
|
+
const clone = track.clone();
|
|
91
|
+
owned.set(key, { clone, original: track });
|
|
92
|
+
if (standard) { transfer.push(clone); return { key, rect, crop: crop || null, track: clone }; }
|
|
93
|
+
const readable = new MediaStreamTrackProcessor({ track: clone, maxBufferSize: 1 }).readable;
|
|
94
|
+
transfer.push(readable);
|
|
95
|
+
return { key, rect, crop: crop || null, readable };
|
|
96
|
+
});
|
|
97
|
+
worker.postMessage({ type: "sources", sources: updates }, transfer);
|
|
98
|
+
};
|
|
99
|
+
worker.addEventListener("message", ({ data }) => { if (!closed && data.type === "error") onError(new Error(data.message)); });
|
|
100
|
+
worker.addEventListener("error", () => { if (!closed) onError(new Error("Recording worker stopped unexpectedly")); });
|
|
101
|
+
const compositor = {
|
|
102
|
+
track: output,
|
|
103
|
+
setSources(next) {
|
|
104
|
+
if (closed) return;
|
|
105
|
+
sources = next;
|
|
106
|
+
try { sync(); } catch (failure) { onError(failure); }
|
|
107
|
+
},
|
|
108
|
+
setActive(next) {
|
|
109
|
+
if (closed || active === next) return;
|
|
110
|
+
active = next;
|
|
111
|
+
worker.postMessage({ type: "active", active });
|
|
112
|
+
try { sync(); } catch (failure) { onError(failure); }
|
|
113
|
+
},
|
|
114
|
+
close() {
|
|
115
|
+
if (closed) return;
|
|
116
|
+
closed = true;
|
|
117
|
+
for (const entry of owned.values()) release(entry);
|
|
118
|
+
owned.clear();
|
|
119
|
+
// Give the standard worker ownership cleanup before termination.
|
|
120
|
+
worker.postMessage({ type: "close" });
|
|
121
|
+
setTimeout(() => worker.terminate(), 100);
|
|
122
|
+
output.stop();
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
return { compositor, reason: null };
|
|
126
|
+
} catch (failure) {
|
|
127
|
+
worker?.terminate();
|
|
128
|
+
output?.stop();
|
|
129
|
+
return { compositor: null, reason: failure?.message || "Native recording frame transfer is unavailable" };
|
|
130
|
+
} finally {
|
|
131
|
+
probeFrame?.close();
|
|
132
|
+
try { void inputWriter?.abort().catch(() => {}); inputWriter?.releaseLock(); } catch {}
|
|
133
|
+
try { void reader?.cancel().then(() => reader.releaseLock()).catch(() => {}); } catch {}
|
|
134
|
+
outputProbe?.stop();
|
|
135
|
+
try { probeInput?.stop(); probeClone?.stop(); } catch {}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Owns at most one input frame per source and one output write. */
|
|
2
|
+
export class FrameCompositor {
|
|
3
|
+
constructor({ canvas, ctx = canvas.getContext("2d"), writer, fps = 15,
|
|
4
|
+
now = () => performance.now(), makeFrame = (surface, init) => new VideoFrame(surface, init),
|
|
5
|
+
onError = () => {} }) {
|
|
6
|
+
this.canvas = canvas;
|
|
7
|
+
this.ctx = ctx;
|
|
8
|
+
this.writer = writer;
|
|
9
|
+
this.interval = 1000 / fps;
|
|
10
|
+
this.now = now;
|
|
11
|
+
this.makeFrame = makeFrame;
|
|
12
|
+
this.onError = onError;
|
|
13
|
+
this.frames = new Map();
|
|
14
|
+
this.sources = [];
|
|
15
|
+
this.active = false;
|
|
16
|
+
this.writing = false;
|
|
17
|
+
this.lastDraw = -Infinity;
|
|
18
|
+
this.timestamp = -1;
|
|
19
|
+
this.startedAt = now();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
setSources(sources) {
|
|
23
|
+
this.sources = sources;
|
|
24
|
+
const keys = new Set(sources.map((source) => source.key));
|
|
25
|
+
for (const [key, frame] of this.frames) {
|
|
26
|
+
if (!keys.has(key)) { frame.close(); this.frames.delete(key); }
|
|
27
|
+
}
|
|
28
|
+
this.dirty = true;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
setActive(active) {
|
|
32
|
+
this.active = active;
|
|
33
|
+
this.dirty = active;
|
|
34
|
+
if (!active) {
|
|
35
|
+
for (const frame of this.frames.values()) frame.close();
|
|
36
|
+
this.frames.clear();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
frame(key, frame) {
|
|
41
|
+
if (!this.active || !this.sources.some((source) => source.key === key)) {
|
|
42
|
+
frame.close();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
this.frames.get(key)?.close();
|
|
46
|
+
this.frames.set(key, frame);
|
|
47
|
+
this.dirty = true;
|
|
48
|
+
this.flush();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
flush() {
|
|
52
|
+
const now = this.now();
|
|
53
|
+
if (!this.active || !this.dirty || this.writing || now - this.lastDraw < this.interval) return;
|
|
54
|
+
this.ctx.fillStyle = "#000";
|
|
55
|
+
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
|
|
56
|
+
for (const { key, rect, crop } of this.sources) {
|
|
57
|
+
const frame = this.frames.get(key);
|
|
58
|
+
if (!frame) continue;
|
|
59
|
+
const width = frame.displayWidth || frame.codedWidth || rect.w;
|
|
60
|
+
const height = frame.displayHeight || frame.codedHeight || rect.h;
|
|
61
|
+
let sx = 0;
|
|
62
|
+
let sy = 0;
|
|
63
|
+
let sw = width;
|
|
64
|
+
let sh = height;
|
|
65
|
+
const c = crop && crop.w > 0 && crop.h > 0 ? crop : null;
|
|
66
|
+
if (c) {
|
|
67
|
+
sx = c.x * width;
|
|
68
|
+
sy = c.y * height;
|
|
69
|
+
sw = c.w * width;
|
|
70
|
+
sh = c.h * height;
|
|
71
|
+
if (sw <= 1 || sh <= 1) continue;
|
|
72
|
+
}
|
|
73
|
+
// Contain: preserve aspect ratio (letterbox/pillarbox inside the slot).
|
|
74
|
+
const scale = Math.min(rect.w / sw, rect.h / sh);
|
|
75
|
+
const w = sw * scale;
|
|
76
|
+
const h = sh * scale;
|
|
77
|
+
this.ctx.drawImage(frame, sx, sy, sw, sh, rect.x + (rect.w - w) / 2, rect.y + (rect.h - h) / 2, w, h);
|
|
78
|
+
}
|
|
79
|
+
this.timestamp = Math.max(this.timestamp + 1, Math.round((now - this.startedAt) * 1000));
|
|
80
|
+
const frame = this.makeFrame(this.canvas, { timestamp: this.timestamp });
|
|
81
|
+
this.dirty = false;
|
|
82
|
+
this.lastDraw = now;
|
|
83
|
+
this.writing = true;
|
|
84
|
+
let writing;
|
|
85
|
+
try { writing = this.writer.write(frame); }
|
|
86
|
+
catch (failure) { writing = Promise.reject(failure); }
|
|
87
|
+
Promise.resolve(writing).catch(this.onError).finally(() => {
|
|
88
|
+
frame.close();
|
|
89
|
+
this.writing = false;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
close() {
|
|
94
|
+
this.setActive(false);
|
|
95
|
+
this.sources = [];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { FrameCompositor } from "./record-frame-compositor.js";
|
|
2
|
+
|
|
3
|
+
let compositor, writer, tick;
|
|
4
|
+
const readers = new Map();
|
|
5
|
+
const error = (failure) => postMessage({ type: "error", message: failure?.message || String(failure) });
|
|
6
|
+
|
|
7
|
+
function remove(key) {
|
|
8
|
+
const source = readers.get(key);
|
|
9
|
+
if (!source) return;
|
|
10
|
+
readers.delete(key);
|
|
11
|
+
void source.reader.cancel().catch(() => {});
|
|
12
|
+
source.track?.stop();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function consume(source) {
|
|
16
|
+
const track = source.track;
|
|
17
|
+
const readable = source.readable || new MediaStreamTrackProcessor({ track, maxBufferSize: 1 }).readable;
|
|
18
|
+
const reader = readable.getReader();
|
|
19
|
+
const entry = { reader, track };
|
|
20
|
+
readers.set(source.key, entry);
|
|
21
|
+
try {
|
|
22
|
+
while (readers.get(source.key) === entry) {
|
|
23
|
+
const { value, done } = await reader.read();
|
|
24
|
+
if (done) break;
|
|
25
|
+
if (readers.get(source.key) !== entry) { value.close(); break; }
|
|
26
|
+
compositor.frame(source.key, value);
|
|
27
|
+
}
|
|
28
|
+
} catch (failure) {
|
|
29
|
+
if (readers.get(source.key) === entry) error(failure);
|
|
30
|
+
} finally {
|
|
31
|
+
if (readers.get(source.key) === entry) readers.delete(source.key);
|
|
32
|
+
reader.releaseLock();
|
|
33
|
+
track?.stop();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
self.onmessage = async ({ data }) => {
|
|
38
|
+
try {
|
|
39
|
+
if (data.type === "capabilities") {
|
|
40
|
+
postMessage({ requestId: data.requestId, standard: typeof MediaStreamTrackProcessor === "function" && typeof VideoTrackGenerator === "function" });
|
|
41
|
+
} else if (data.type === "init") {
|
|
42
|
+
let track;
|
|
43
|
+
if (data.standard) {
|
|
44
|
+
const generator = new VideoTrackGenerator();
|
|
45
|
+
writer = generator.writable.getWriter();
|
|
46
|
+
track = generator.track;
|
|
47
|
+
} else writer = data.writable.getWriter();
|
|
48
|
+
const canvas = new OffscreenCanvas(data.width, data.height);
|
|
49
|
+
compositor = new FrameCompositor({ canvas, writer, fps: data.fps, onError: error });
|
|
50
|
+
// Native input frames drive rendering. This tick only flushes a final dirty frame.
|
|
51
|
+
tick = setInterval(() => compositor.flush(), Math.round(1000 / data.fps));
|
|
52
|
+
postMessage({ requestId: data.requestId, track }, track ? [track] : []);
|
|
53
|
+
} else if (data.type === "probe") {
|
|
54
|
+
const readable = data.readable || new MediaStreamTrackProcessor({ track: data.track, maxBufferSize: 1 }).readable;
|
|
55
|
+
const reader = readable.getReader();
|
|
56
|
+
const { value, done } = await reader.read();
|
|
57
|
+
if (done) throw new Error("Recording frame probe ended before receiving video");
|
|
58
|
+
try {
|
|
59
|
+
compositor.ctx.drawImage(value, 0, 0, compositor.canvas.width, compositor.canvas.height);
|
|
60
|
+
const frame = new VideoFrame(compositor.canvas, { timestamp: 0 });
|
|
61
|
+
try { await writer.write(frame); } finally { frame.close(); }
|
|
62
|
+
} finally {
|
|
63
|
+
value.close();
|
|
64
|
+
await reader.cancel();
|
|
65
|
+
reader.releaseLock();
|
|
66
|
+
data.track?.stop();
|
|
67
|
+
}
|
|
68
|
+
postMessage({ requestId: data.requestId });
|
|
69
|
+
} else if (data.type === "sources") {
|
|
70
|
+
const keys = new Set(data.sources.map((source) => source.key));
|
|
71
|
+
for (const key of readers.keys()) if (!keys.has(key)) remove(key);
|
|
72
|
+
compositor.setSources(data.sources.map(({ key, rect, crop }) => ({ key, rect, crop: crop || null })));
|
|
73
|
+
for (const source of data.sources) {
|
|
74
|
+
if (!source.readable && !source.track) continue;
|
|
75
|
+
remove(source.key);
|
|
76
|
+
void consume(source);
|
|
77
|
+
}
|
|
78
|
+
} else if (data.type === "active") {
|
|
79
|
+
compositor.setActive(data.active);
|
|
80
|
+
if (!data.active) for (const key of [...readers.keys()]) remove(key);
|
|
81
|
+
} else if (data.type === "close") {
|
|
82
|
+
clearInterval(tick);
|
|
83
|
+
compositor.close();
|
|
84
|
+
for (const key of [...readers.keys()]) remove(key);
|
|
85
|
+
await writer.close();
|
|
86
|
+
self.close();
|
|
87
|
+
}
|
|
88
|
+
} catch (failure) { error(failure); }
|
|
89
|
+
};
|