mediascale-sdk 1.0.5 → 1.0.6

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.
@@ -0,0 +1,83 @@
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 } 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
+ const scale = Math.min(rect.w / width, rect.h / height);
62
+ const w = width * scale, h = height * scale;
63
+ this.ctx.drawImage(frame, rect.x + (rect.w - w) / 2, rect.y + (rect.h - h) / 2, w, h);
64
+ }
65
+ this.timestamp = Math.max(this.timestamp + 1, Math.round((now - this.startedAt) * 1000));
66
+ const frame = this.makeFrame(this.canvas, { timestamp: this.timestamp });
67
+ this.dirty = false;
68
+ this.lastDraw = now;
69
+ this.writing = true;
70
+ let writing;
71
+ try { writing = this.writer.write(frame); }
72
+ catch (failure) { writing = Promise.reject(failure); }
73
+ Promise.resolve(writing).catch(this.onError).finally(() => {
74
+ frame.close();
75
+ this.writing = false;
76
+ });
77
+ }
78
+
79
+ close() {
80
+ this.setActive(false);
81
+ this.sources = [];
82
+ }
83
+ }
@@ -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 }) => ({ key, rect })));
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
+ };