mediascale-sdk 0.0.0-stage → 1.0.0
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 +157 -0
- package/package.json +15 -4
- package/src/client.js +454 -0
- package/src/index.js +1 -0
- package/src/record.js +576 -0
- package/README.md +0 -3
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Use the SDK in Next.js
|
|
2
|
+
|
|
3
|
+
One address talks to Mediascale. The default is `http://localhost:8080`.
|
|
4
|
+
|
|
5
|
+
A person joins a session, turns on camera and microphone, hears the others, and leaves. If `recording` is true and that person is the host, recording starts by itself. Anyone else can call `startRecording()` if the host leaves and the recording should continue.
|
|
6
|
+
|
|
7
|
+
The secret that signs tokens stays on your server. The browser only receives a short-lived token.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
From your Next.js app:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install mediascale-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Add this `next.config.js` so Next.js compiles the SDK:
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
/** @type {import('next').NextConfig} */
|
|
21
|
+
const nextConfig = {
|
|
22
|
+
transpilePackages: ["mediascale-sdk"],
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
module.exports = nextConfig;
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 1. Create a token on your server
|
|
29
|
+
|
|
30
|
+
Add `SDK_SECRET` to the server environment. Use the same value that Mediascale was started with. Do not put it in a `NEXT_PUBLIC_` variable.
|
|
31
|
+
|
|
32
|
+
`app/api/token/route.js`
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import crypto from "crypto";
|
|
36
|
+
|
|
37
|
+
export async function POST(request) {
|
|
38
|
+
const secret = process.env.SDK_SECRET || "";
|
|
39
|
+
if (!secret) return Response.json({ error: "SDK_SECRET is not set" }, { status: 500 });
|
|
40
|
+
|
|
41
|
+
const body = await request.json();
|
|
42
|
+
const sessionId = String(body.sessionId || "").trim();
|
|
43
|
+
const role = body.role === "host" ? "host" : "audience";
|
|
44
|
+
const name = String(body.name || "Guest").slice(0, 40);
|
|
45
|
+
if (!sessionId) return Response.json({ error: "sessionId is required" }, { status: 400 });
|
|
46
|
+
|
|
47
|
+
const payload = { sessionId, role, name, exp: Date.now() + 2 * 60 * 60 * 1000 };
|
|
48
|
+
const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
49
|
+
const signature = crypto.createHmac("sha256", secret).update(encoded).digest("base64url");
|
|
50
|
+
return Response.json({ token: `${encoded}.${signature}` });
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`role` is `host` or `audience`. Both can publish. Only the host records automatically.
|
|
55
|
+
|
|
56
|
+
## 2. Copy the room page
|
|
57
|
+
|
|
58
|
+
Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file are the steps.
|
|
59
|
+
|
|
60
|
+
1. **Join** asks your server for a token, then calls `connect()` and `subscribe()`. The camera, microphone, and screen stay off.
|
|
61
|
+
2. **Camera** calls `startCamera()` or `stopCamera()`.
|
|
62
|
+
3. **Mic** calls `startMicrophone()` or `stopMicrophone()`.
|
|
63
|
+
4. **Screen** calls `startScreenShare()` or `stopScreenShare()`.
|
|
64
|
+
5. **Start recording** is optional. Use it when the host has left and someone else should continue.
|
|
65
|
+
6. **End** leaves the session.
|
|
66
|
+
|
|
67
|
+
Host is unchecked. Tick it only for the person who should record. When it is ticked, `recording` is true and recording starts on `connect()`.
|
|
68
|
+
|
|
69
|
+
The room must run in the browser. `app/page.js`
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
"use client";
|
|
73
|
+
|
|
74
|
+
import dynamic from "next/dynamic";
|
|
75
|
+
|
|
76
|
+
const Room = dynamic(() => import("./room"), { ssr: false });
|
|
77
|
+
|
|
78
|
+
export default function Page() {
|
|
79
|
+
return <Room />;
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Show your own camera from the value `startCamera()` returns:
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
const camera = await client.startCamera();
|
|
87
|
+
cameraVideo.srcObject = camera.stream;
|
|
88
|
+
await client.stopCamera();
|
|
89
|
+
|
|
90
|
+
await client.startMicrophone();
|
|
91
|
+
await client.stopMicrophone();
|
|
92
|
+
|
|
93
|
+
const screen = await client.startScreenShare();
|
|
94
|
+
screenVideo.srcObject = screen.stream;
|
|
95
|
+
await client.stopScreenShare();
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`startCamera()` uses the default camera at 1280×720. `startMicrophone()` uses the default microphone. Pass ids from `listDevices()` when the user should pick a device:
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
await client.startCamera({ cameraId: "device-id", resolution: "720p" });
|
|
102
|
+
await client.startMicrophone({ micId: "device-id" });
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`resolution` can be `"480p"`, `"720p"`, `"1080p"`, or `{ width: 1280, height: 720 }`.
|
|
106
|
+
|
|
107
|
+
## Functions
|
|
108
|
+
|
|
109
|
+
| Function | What it does |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `createClient({ endpoint, sessionId, token, recording, iceServers, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to false. |
|
|
112
|
+
| `connect()` | Checks the token and joins the session. If `recording` is true and the token role is `host`, recording starts. |
|
|
113
|
+
| `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
|
|
114
|
+
| `startCamera({ cameraId, resolution })` | Publishes the camera. Both arguments are optional. |
|
|
115
|
+
| `stopCamera()` | Stops the camera. The person stays in the session. |
|
|
116
|
+
| `startMicrophone({ micId })` | Publishes the microphone. `micId` is optional. |
|
|
117
|
+
| `stopMicrophone()` | Stops the microphone. |
|
|
118
|
+
| `startScreenShare()` | Shares the screen. Anyone in the session can call this. |
|
|
119
|
+
| `stopScreenShare()` | Stops the screen share. |
|
|
120
|
+
| `publish({ cameraId, micId, resolution })` | Turns on the camera and the microphone together. |
|
|
121
|
+
| `stop()` | Turns off the camera and the microphone. The screen share stays on. |
|
|
122
|
+
| `startRecording()` | Starts recording for this person. Call it when the host has left and someone else should keep the same recording going. |
|
|
123
|
+
| `end()` | Leaves the session. If this person is the one recording, the recording is saved. |
|
|
124
|
+
| `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
|
|
125
|
+
|
|
126
|
+
Call `connect`, then `subscribe`. Call `startCamera`, `startMicrophone`, or `startScreenShare` only when that button is pressed. Call the matching stop function to turn that input off. Call `end` when the person leaves.
|
|
127
|
+
|
|
128
|
+
## Callbacks
|
|
129
|
+
|
|
130
|
+
Pass these to `createClient`.
|
|
131
|
+
|
|
132
|
+
| Callback | When it runs |
|
|
133
|
+
| --- | --- |
|
|
134
|
+
| `onTrack({ producerId, peerId, source, kind, displayName, stream })` | Another person's camera, microphone, or screen is ready. Set `srcObject` on a `<video>` or `<audio>` element. `source` is `webcam`, `mic`, or `screen`. |
|
|
135
|
+
| `onTrackEnded({ producerId })` | That media stopped. Remove the element. |
|
|
136
|
+
| `onStatus(text)` | `Joining`, `Ready`, `Live`, `Network unstable`, `Ended`, or an error message. |
|
|
137
|
+
| `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
|
|
138
|
+
| `onRecording(state)` | `recording` when this browser is recording. `stopped` when it stops or hands the recording to someone else. |
|
|
139
|
+
|
|
140
|
+
## Recording
|
|
141
|
+
|
|
142
|
+
- Set `recording: true` only for the host. `connect()` then records without an extra call. The red `[ rec ]` label shows while that recording is active. If recording does not start, the label stays hidden and the person can still publish.
|
|
143
|
+
- The file keeps going when another person calls `startRecording()`. Ask them to start before the host calls `end()`.
|
|
144
|
+
- `end()` saves the file only for the person who is recording at that moment.
|
|
145
|
+
- If everybody leaves, the recording is still saved after a few minutes of silence.
|
|
146
|
+
|
|
147
|
+
## Run the sample
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
cd sdk/react-sdk/sample
|
|
151
|
+
npm install
|
|
152
|
+
npm run dev
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Open http://localhost:3200. The page asks your Next.js server for a token, then joins http://localhost:8080.
|
|
156
|
+
|
|
157
|
+
Set `SDK_SECRET` in the environment before `npm run dev`. `MEDASCALE_ENDPOINT` is optional. The sample uses it when it is set, and otherwise uses `http://localhost:8080`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mediascale-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Mediascale React/browser SDK for live sessions, WebRTC publish/subscribe, and recording",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": ["src", "docs"],
|
|
11
|
+
"license": "UNLICENSED",
|
|
12
|
+
"keywords": ["mediascale", "webrtc", "mediasoup", "live", "sdk"],
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"mediasoup-client": "^3.7.17",
|
|
15
|
+
"socket.io-client": "^4.8.1"
|
|
16
|
+
}
|
|
17
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import { Device } from "mediasoup-client";
|
|
2
|
+
import { io } from "socket.io-client";
|
|
3
|
+
import { CanvasRecorder, recordingWebinarId, tracksFromTiles } from "./record.js";
|
|
4
|
+
|
|
5
|
+
const SIZES = {
|
|
6
|
+
"480p": { width: 854, height: 480 },
|
|
7
|
+
"720p": { width: 1280, height: 720 },
|
|
8
|
+
"1080p": { width: 1920, height: 1080 },
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
function readToken(token) {
|
|
12
|
+
const body = String(token || "").split(".")[0];
|
|
13
|
+
if (!body) throw new Error("token is required");
|
|
14
|
+
const pad = body.length % 4 === 0 ? "" : "=".repeat(4 - (body.length % 4));
|
|
15
|
+
const json = JSON.parse(atob(body.replace(/-/g, "+").replace(/_/g, "/") + pad));
|
|
16
|
+
if (!json.sessionId) throw new Error("token is missing a session");
|
|
17
|
+
if (!json.exp || json.exp < Date.now()) throw new Error("token has expired");
|
|
18
|
+
if (json.role !== "host" && json.role !== "audience") throw new Error("token role is invalid");
|
|
19
|
+
return json;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function recordingIdFor(sessionId) {
|
|
23
|
+
const data = new TextEncoder().encode(`mediascale-recording:${sessionId}`);
|
|
24
|
+
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
25
|
+
const bytes = new Uint8Array(digest).slice(0, 16);
|
|
26
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x50;
|
|
27
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
28
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
29
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function emit(socket, event, data, timeoutMs = 8000) {
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const timer = setTimeout(() => reject(new Error("The server did not answer")), timeoutMs);
|
|
35
|
+
socket.emit(event, data, (response) => {
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
if (!response || response.error) {
|
|
38
|
+
if (response?.peer && typeof document !== "undefined") {
|
|
39
|
+
document.cookie = `ms_portal=${encodeURIComponent(response.peer)}; Path=/; Max-Age=86400; SameSite=Lax`;
|
|
40
|
+
}
|
|
41
|
+
reject(new Error(response?.error || "Request failed"));
|
|
42
|
+
} else resolve(response);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function videoConstraint(cameraId, resolution) {
|
|
48
|
+
const size = resolution && typeof resolution === "object" ? resolution : (SIZES[resolution] || SIZES["720p"]);
|
|
49
|
+
const video = { width: { ideal: size.width }, height: { ideal: size.height } };
|
|
50
|
+
if (cameraId) video.deviceId = { exact: cameraId };
|
|
51
|
+
return video;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function createClient(options = {}) {
|
|
55
|
+
const endpoint = String(options.endpoint || "http://localhost:8080").replace(/\/+$/, "");
|
|
56
|
+
const sessionId = String(options.sessionId || "").trim();
|
|
57
|
+
const token = String(options.token || "").trim();
|
|
58
|
+
const recording = options.recording === true;
|
|
59
|
+
const iceOverride = Array.isArray(options.iceServers) ? options.iceServers : null;
|
|
60
|
+
const onTrack = options.onTrack || (() => {});
|
|
61
|
+
const onTrackEnded = options.onTrackEnded || (() => {});
|
|
62
|
+
const onStatus = options.onStatus || (() => {});
|
|
63
|
+
const onError = options.onError || (() => {});
|
|
64
|
+
const onRecording = options.onRecording || (() => {});
|
|
65
|
+
|
|
66
|
+
if (!sessionId) throw new Error("sessionId is required");
|
|
67
|
+
if (!token) throw new Error("token is required");
|
|
68
|
+
const claims = readToken(token);
|
|
69
|
+
if (claims.sessionId !== sessionId) throw new Error("token is for a different session");
|
|
70
|
+
|
|
71
|
+
const displayName = String(claims.name || "Guest").slice(0, 40);
|
|
72
|
+
let socket = null;
|
|
73
|
+
let device = null;
|
|
74
|
+
let sendTransport = null;
|
|
75
|
+
let recvTransport = null;
|
|
76
|
+
let iceServers = iceOverride || [];
|
|
77
|
+
let closed = false;
|
|
78
|
+
let subscribed = false;
|
|
79
|
+
let recorder = null;
|
|
80
|
+
const locals = new Map();
|
|
81
|
+
const tiles = new Map();
|
|
82
|
+
const pending = [];
|
|
83
|
+
let readyPromise = null;
|
|
84
|
+
let settleReady = null;
|
|
85
|
+
|
|
86
|
+
function syncRecording() {
|
|
87
|
+
recorder?.sync(tracksFromTiles([...tiles.values()]));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function consume(params) {
|
|
91
|
+
const consumer = await recvTransport.consume({
|
|
92
|
+
id: params.id,
|
|
93
|
+
producerId: params.producerId,
|
|
94
|
+
kind: params.kind,
|
|
95
|
+
rtpParameters: params.rtpParameters,
|
|
96
|
+
});
|
|
97
|
+
await emit(socket, "resume", { consumerId: consumer.id });
|
|
98
|
+
const stream = new MediaStream([consumer.track]);
|
|
99
|
+
tiles.set(params.producerId, {
|
|
100
|
+
producerId: params.producerId,
|
|
101
|
+
publisherId: params.publisherId,
|
|
102
|
+
source: params.source,
|
|
103
|
+
kind: params.kind,
|
|
104
|
+
displayName: params.displayName,
|
|
105
|
+
stream,
|
|
106
|
+
local: false,
|
|
107
|
+
});
|
|
108
|
+
syncRecording();
|
|
109
|
+
onTrack({
|
|
110
|
+
producerId: params.producerId,
|
|
111
|
+
peerId: params.publisherId,
|
|
112
|
+
source: params.source,
|
|
113
|
+
kind: params.kind,
|
|
114
|
+
displayName: params.displayName,
|
|
115
|
+
stream,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function play(params) {
|
|
120
|
+
if (!subscribed || !recvTransport) {
|
|
121
|
+
pending.push(params);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
await consume(params);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function flush() {
|
|
128
|
+
while (subscribed && recvTransport && pending.length) {
|
|
129
|
+
await consume(pending.shift());
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function unpublish(producerId) {
|
|
134
|
+
const entry = locals.get(producerId);
|
|
135
|
+
if (!entry) return;
|
|
136
|
+
locals.delete(producerId);
|
|
137
|
+
tiles.delete(producerId);
|
|
138
|
+
entry.track.stop();
|
|
139
|
+
entry.producer.close();
|
|
140
|
+
syncRecording();
|
|
141
|
+
onTrackEnded({ producerId, local: true, source: entry.source });
|
|
142
|
+
if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function produce(source, track) {
|
|
146
|
+
const producer = await sendTransport.produce({ track, appData: { source } });
|
|
147
|
+
const stream = new MediaStream([track]);
|
|
148
|
+
locals.set(producer.id, { producer, track, source });
|
|
149
|
+
tiles.set(producer.id, {
|
|
150
|
+
producerId: producer.id,
|
|
151
|
+
publisherId: "local",
|
|
152
|
+
source,
|
|
153
|
+
kind: track.kind,
|
|
154
|
+
displayName,
|
|
155
|
+
stream,
|
|
156
|
+
local: true,
|
|
157
|
+
});
|
|
158
|
+
track.onended = () => {
|
|
159
|
+
if (source === "screen") stopScreenShare().catch(() => {});
|
|
160
|
+
else unpublish(producer.id).catch(() => {});
|
|
161
|
+
};
|
|
162
|
+
syncRecording();
|
|
163
|
+
return { producerId: producer.id, stream, source };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function ensurePortalAffinity() {
|
|
167
|
+
try {
|
|
168
|
+
const response = await fetch(`${endpoint}/portal/api/v1/affinity?channelId=${encodeURIComponent(sessionId)}`, {
|
|
169
|
+
credentials: "include",
|
|
170
|
+
});
|
|
171
|
+
if (!response.ok) return;
|
|
172
|
+
const body = await response.json().catch(() => null);
|
|
173
|
+
if (body?.peer && typeof document !== "undefined") {
|
|
174
|
+
document.cookie = `ms_portal=${encodeURIComponent(body.peer)}; Path=/; Max-Age=86400; SameSite=Lax`;
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
/* gateway may still route to the seed portal */
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function connect() {
|
|
182
|
+
if (readyPromise) return readyPromise;
|
|
183
|
+
readyPromise = (async () => {
|
|
184
|
+
await ensurePortalAffinity();
|
|
185
|
+
return new Promise((resolve, reject) => {
|
|
186
|
+
settleReady = (error) => {
|
|
187
|
+
settleReady = null;
|
|
188
|
+
if (error) reject(error);
|
|
189
|
+
else resolve();
|
|
190
|
+
};
|
|
191
|
+
socket = io(endpoint, {
|
|
192
|
+
transports: ["websocket"],
|
|
193
|
+
withCredentials: true,
|
|
194
|
+
auth: { token, client: "mediascale-sdk" },
|
|
195
|
+
});
|
|
196
|
+
socket.on("connect_error", () => {
|
|
197
|
+
if (!closed) onStatus("Network unstable");
|
|
198
|
+
});
|
|
199
|
+
socket.on("sessionEnded", () => {
|
|
200
|
+
end().catch((error) => onError(error));
|
|
201
|
+
});
|
|
202
|
+
socket.on("releaseRecording", () => {
|
|
203
|
+
const current = recorder;
|
|
204
|
+
recorder = null;
|
|
205
|
+
if (!current) return;
|
|
206
|
+
current.handoff()
|
|
207
|
+
.then(() => onRecording("stopped"))
|
|
208
|
+
.catch((error) => onError(error));
|
|
209
|
+
});
|
|
210
|
+
socket.on("connect", async () => {
|
|
211
|
+
try {
|
|
212
|
+
if (closed) return;
|
|
213
|
+
onStatus("Joining");
|
|
214
|
+
const joined = await emit(socket, "join", {
|
|
215
|
+
channelId: sessionId,
|
|
216
|
+
role: "publisher",
|
|
217
|
+
displayName,
|
|
218
|
+
});
|
|
219
|
+
iceServers = iceOverride || joined.iceServers || [];
|
|
220
|
+
device = new Device();
|
|
221
|
+
await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
|
|
222
|
+
|
|
223
|
+
const sendParams = await emit(socket, "createTransport", { direction: "send" });
|
|
224
|
+
sendTransport = device.createSendTransport({ ...sendParams, iceServers });
|
|
225
|
+
sendTransport.on("connect", ({ dtlsParameters }, callback, errback) => {
|
|
226
|
+
emit(socket, "connectTransport", { transportId: sendTransport.id, dtlsParameters }).then(() => callback()).catch(errback);
|
|
227
|
+
});
|
|
228
|
+
sendTransport.on("produce", ({ kind, rtpParameters, appData }, callback, errback) => {
|
|
229
|
+
emit(socket, "produce", {
|
|
230
|
+
transportId: sendTransport.id,
|
|
231
|
+
kind,
|
|
232
|
+
rtpParameters,
|
|
233
|
+
source: appData.source,
|
|
234
|
+
}).then((result) => callback({ id: result.id })).catch(errback);
|
|
235
|
+
});
|
|
236
|
+
sendTransport.on("connectionstatechange", (state) => {
|
|
237
|
+
if (state === "failed" || state === "disconnected") onStatus("Network unstable");
|
|
238
|
+
else if (state === "connected") onStatus("Live");
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const recvParams = await emit(socket, "createTransport", { direction: "recv" });
|
|
242
|
+
recvTransport = device.createRecvTransport({ ...recvParams, iceServers });
|
|
243
|
+
recvTransport.on("connect", ({ dtlsParameters }, callback, errback) => {
|
|
244
|
+
emit(socket, "connectTransport", { transportId: recvTransport.id, dtlsParameters }).then(() => callback()).catch(errback);
|
|
245
|
+
});
|
|
246
|
+
socket.on("newConsumer", (params) => {
|
|
247
|
+
play(params).catch((error) => onError(error));
|
|
248
|
+
});
|
|
249
|
+
socket.on("producerClosed", ({ producerId }) => {
|
|
250
|
+
for (let i = pending.length - 1; i >= 0; i -= 1) {
|
|
251
|
+
if (pending[i].producerId === producerId) pending.splice(i, 1);
|
|
252
|
+
}
|
|
253
|
+
if (tiles.delete(producerId)) syncRecording();
|
|
254
|
+
onTrackEnded({ producerId });
|
|
255
|
+
});
|
|
256
|
+
const started = await emit(socket, "ready", { rtpCapabilities: device.rtpCapabilities });
|
|
257
|
+
for (const params of started.consumers || []) await play(params);
|
|
258
|
+
if (joined.waiting) onStatus("Please wait, we will connect you soon");
|
|
259
|
+
else onStatus("Ready");
|
|
260
|
+
if (closed) return;
|
|
261
|
+
if (recording && claims.role === "host") await startRecording();
|
|
262
|
+
if (closed) return;
|
|
263
|
+
settleReady?.();
|
|
264
|
+
} catch (error) {
|
|
265
|
+
onStatus(error.message);
|
|
266
|
+
settleReady?.(error);
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
})();
|
|
271
|
+
return readyPromise;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function startCamera({ cameraId, resolution } = {}) {
|
|
275
|
+
await connect();
|
|
276
|
+
if (!sendTransport) throw new Error("The session is not ready");
|
|
277
|
+
await stopCamera();
|
|
278
|
+
const stream = await navigator.mediaDevices.getUserMedia({
|
|
279
|
+
video: videoConstraint(cameraId, resolution),
|
|
280
|
+
audio: false,
|
|
281
|
+
});
|
|
282
|
+
const track = stream.getVideoTracks()[0];
|
|
283
|
+
if (!track) throw new Error("No camera was found");
|
|
284
|
+
try {
|
|
285
|
+
return await produce("webcam", track);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
track.stop();
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function stopCamera() {
|
|
293
|
+
for (const [id, entry] of [...locals]) {
|
|
294
|
+
if (entry.source === "webcam") await unpublish(id);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function startMicrophone({ micId } = {}) {
|
|
299
|
+
await connect();
|
|
300
|
+
if (!sendTransport) throw new Error("The session is not ready");
|
|
301
|
+
await stopMicrophone();
|
|
302
|
+
const audio = { echoCancellation: true, noiseSuppression: true };
|
|
303
|
+
if (micId) audio.deviceId = { exact: micId };
|
|
304
|
+
const stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
|
305
|
+
const track = stream.getAudioTracks()[0];
|
|
306
|
+
if (!track) throw new Error("No microphone was found");
|
|
307
|
+
try {
|
|
308
|
+
return await produce("mic", track);
|
|
309
|
+
} catch (error) {
|
|
310
|
+
track.stop();
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function stopMicrophone() {
|
|
316
|
+
for (const [id, entry] of [...locals]) {
|
|
317
|
+
if (entry.source === "mic") await unpublish(id);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function publish({ cameraId, micId, resolution } = {}) {
|
|
322
|
+
const camera = await startCamera({ cameraId, resolution });
|
|
323
|
+
try {
|
|
324
|
+
const microphone = await startMicrophone({ micId });
|
|
325
|
+
return { camera, microphone };
|
|
326
|
+
} catch (error) {
|
|
327
|
+
await stopCamera();
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function stop() {
|
|
333
|
+
await stopCamera();
|
|
334
|
+
await stopMicrophone();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function startScreenShare() {
|
|
338
|
+
await connect();
|
|
339
|
+
if (!sendTransport) throw new Error("The session is not ready");
|
|
340
|
+
await stopScreenShare();
|
|
341
|
+
let stream;
|
|
342
|
+
try {
|
|
343
|
+
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true });
|
|
344
|
+
} catch (error) {
|
|
345
|
+
if (error?.name === "NotAllowedError" || error?.name === "AbortError") throw error;
|
|
346
|
+
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
|
|
347
|
+
}
|
|
348
|
+
const videoTrack = stream.getVideoTracks()[0];
|
|
349
|
+
if (!videoTrack) {
|
|
350
|
+
stream.getTracks().forEach((track) => track.stop());
|
|
351
|
+
throw new Error("No screen was selected");
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
const screen = await produce("screen", videoTrack);
|
|
355
|
+
const audioTrack = stream.getAudioTracks()[0];
|
|
356
|
+
if (audioTrack) await produce("screen", audioTrack);
|
|
357
|
+
return screen;
|
|
358
|
+
} catch (error) {
|
|
359
|
+
stream.getTracks().forEach((track) => track.stop());
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function stopScreenShare() {
|
|
365
|
+
for (const [id, entry] of [...locals]) {
|
|
366
|
+
if (entry.source === "screen") await unpublish(id);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async function subscribe() {
|
|
371
|
+
await connect();
|
|
372
|
+
subscribed = true;
|
|
373
|
+
await flush();
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async function startRecording() {
|
|
377
|
+
if (closed) throw new Error("The session has ended");
|
|
378
|
+
if (!sendTransport) await connect();
|
|
379
|
+
if (closed || recorder) return;
|
|
380
|
+
await emit(socket, "claimRecording", {});
|
|
381
|
+
const next = new CanvasRecorder({
|
|
382
|
+
webinarId: recordingWebinarId(sessionId),
|
|
383
|
+
webinarName: sessionId,
|
|
384
|
+
recordingId: await recordingIdFor(sessionId),
|
|
385
|
+
endpoint,
|
|
386
|
+
token,
|
|
387
|
+
});
|
|
388
|
+
recorder = next;
|
|
389
|
+
next.sync(tracksFromTiles([...tiles.values()]));
|
|
390
|
+
try {
|
|
391
|
+
await next.start();
|
|
392
|
+
} catch {
|
|
393
|
+
if (recorder === next) recorder = null;
|
|
394
|
+
onRecording("stopped");
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (recorder !== next) return;
|
|
398
|
+
onRecording("recording");
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function end() {
|
|
402
|
+
if (closed) return;
|
|
403
|
+
closed = true;
|
|
404
|
+
settleReady?.(new Error("Ended"));
|
|
405
|
+
const current = recorder;
|
|
406
|
+
recorder = null;
|
|
407
|
+
if (current) {
|
|
408
|
+
await current.finish();
|
|
409
|
+
onRecording("stopped");
|
|
410
|
+
}
|
|
411
|
+
for (const entry of locals.values()) entry.track.stop();
|
|
412
|
+
locals.clear();
|
|
413
|
+
sendTransport?.close();
|
|
414
|
+
recvTransport?.close();
|
|
415
|
+
socket?.close();
|
|
416
|
+
onStatus("Ended");
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function listDevices() {
|
|
420
|
+
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
421
|
+
const info = (device) => ({ id: device.deviceId, label: device.label || device.kind });
|
|
422
|
+
return {
|
|
423
|
+
cameras: devices.filter((device) => device.kind === "videoinput").map(info),
|
|
424
|
+
microphones: devices.filter((device) => device.kind === "audioinput").map(info),
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function guard(fn) {
|
|
429
|
+
return async (...args) => {
|
|
430
|
+
try {
|
|
431
|
+
return await fn(...args);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
onError(error);
|
|
434
|
+
throw error;
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
return {
|
|
440
|
+
connect: guard(connect),
|
|
441
|
+
publish: guard(publish),
|
|
442
|
+
stop: guard(stop),
|
|
443
|
+
startCamera: guard(startCamera),
|
|
444
|
+
stopCamera: guard(stopCamera),
|
|
445
|
+
startMicrophone: guard(startMicrophone),
|
|
446
|
+
stopMicrophone: guard(stopMicrophone),
|
|
447
|
+
startScreenShare: guard(startScreenShare),
|
|
448
|
+
stopScreenShare: guard(stopScreenShare),
|
|
449
|
+
subscribe: guard(subscribe),
|
|
450
|
+
startRecording: guard(startRecording),
|
|
451
|
+
end: guard(end),
|
|
452
|
+
listDevices: guard(listDevices),
|
|
453
|
+
};
|
|
454
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createClient } from "./client.js";
|
package/src/record.js
ADDED
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
const W = 1280;
|
|
2
|
+
const H = 720;
|
|
3
|
+
const COL = 240;
|
|
4
|
+
const PAD = 8;
|
|
5
|
+
const GAP = 8;
|
|
6
|
+
const FPS = 15;
|
|
7
|
+
const SLICE_MS = 5000;
|
|
8
|
+
const BITRATE = 2_000_000;
|
|
9
|
+
const mime = "video/webm;codecs=vp8,opus";
|
|
10
|
+
|
|
11
|
+
/** Channel ids become a single path segment. The original text stays the webinar name. */
|
|
12
|
+
export function recordingWebinarId(channelId) {
|
|
13
|
+
const cleaned = String(channelId || "").trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 128);
|
|
14
|
+
return cleaned || "webinar";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Equal tiles, or one screenshare with cameras stacked in a 240px column. Up to four cameras. */
|
|
18
|
+
export function layoutSlots(cameras, screen) {
|
|
19
|
+
if (screen) {
|
|
20
|
+
const mainW = W - COL - PAD * 2 - GAP;
|
|
21
|
+
const mainH = H - PAD * 2;
|
|
22
|
+
const n = Math.max(cameras, 1);
|
|
23
|
+
const cellH = Math.floor((mainH - GAP * (n - 1)) / n);
|
|
24
|
+
return {
|
|
25
|
+
screen: { x: PAD, y: PAD, w: mainW, h: mainH },
|
|
26
|
+
cameras: Array.from({ length: cameras }, (_, i) => ({
|
|
27
|
+
x: PAD + mainW + GAP,
|
|
28
|
+
y: PAD + i * (cellH + GAP),
|
|
29
|
+
w: COL,
|
|
30
|
+
h: cellH,
|
|
31
|
+
})),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const cols = cameras <= 1 ? 1 : 2;
|
|
35
|
+
const rows = cameras <= 2 ? 1 : 2;
|
|
36
|
+
const cellW = Math.floor((W - PAD * 2 - GAP * (cols - 1)) / cols);
|
|
37
|
+
const cellH = Math.floor((H - PAD * 2 - GAP * (rows - 1)) / rows);
|
|
38
|
+
return {
|
|
39
|
+
cameras: Array.from({ length: cameras }, (_, i) => ({
|
|
40
|
+
x: PAD + (i % cols) * (cellW + GAP),
|
|
41
|
+
y: PAD + Math.floor(i / cols) * (cellH + GAP),
|
|
42
|
+
w: cellW,
|
|
43
|
+
h: cellH,
|
|
44
|
+
})),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One entry per mediasoup track the stage is showing. */
|
|
49
|
+
export function tracksFromTiles(tiles) {
|
|
50
|
+
const out = [];
|
|
51
|
+
for (const item of tiles) {
|
|
52
|
+
if (!item?.stream) continue;
|
|
53
|
+
const participantKey = item.local ? "local" : (item.publisherId || item.displayName || item.producerId);
|
|
54
|
+
for (const track of item.stream.getTracks()) {
|
|
55
|
+
if (track.readyState === "ended") continue;
|
|
56
|
+
const source = item.source === "screen" && track.kind === "audio" ? "screen-audio" : item.source;
|
|
57
|
+
out.push({
|
|
58
|
+
participantKey: String(participantKey),
|
|
59
|
+
source,
|
|
60
|
+
kind: track.kind,
|
|
61
|
+
isLocal: Boolean(item.local),
|
|
62
|
+
track,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class CanvasRecorder {
|
|
70
|
+
static supported() {
|
|
71
|
+
return typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mime);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
constructor({ webinarId, webinarName, recordingId, endpoint, token }) {
|
|
75
|
+
this.webinarId = webinarId;
|
|
76
|
+
this.webinarName = webinarName || webinarId;
|
|
77
|
+
this.recordingId = recordingId;
|
|
78
|
+
this.endpoint = String(endpoint || "").replace(/\/+$/, "");
|
|
79
|
+
this.token = token || "";
|
|
80
|
+
this.segment = 0;
|
|
81
|
+
this.seq = 0;
|
|
82
|
+
this.startedAt = 0;
|
|
83
|
+
this.tracks = [];
|
|
84
|
+
this.slots = [];
|
|
85
|
+
this.orders = new Map();
|
|
86
|
+
this.nextOrder = 1;
|
|
87
|
+
this.videos = new Map();
|
|
88
|
+
this.audioNodes = new Map();
|
|
89
|
+
this.tries = new Map();
|
|
90
|
+
this.chain = Promise.resolve();
|
|
91
|
+
this.finishing = false;
|
|
92
|
+
this.untilStop = new Promise((resolve) => {
|
|
93
|
+
this.release = resolve;
|
|
94
|
+
});
|
|
95
|
+
this.onPageHide = (event) => {
|
|
96
|
+
event.preventDefault();
|
|
97
|
+
event.returnValue = "";
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async start(audio) {
|
|
102
|
+
this.audio = audio;
|
|
103
|
+
if (!CanvasRecorder.supported()) {
|
|
104
|
+
this.teardown();
|
|
105
|
+
throw new Error("This browser cannot record. Use Chrome, Edge, or Firefox.");
|
|
106
|
+
}
|
|
107
|
+
const running = new Promise((resolve, reject) => {
|
|
108
|
+
this.ready = resolve;
|
|
109
|
+
this.failed = reject;
|
|
110
|
+
});
|
|
111
|
+
const run = async () => {
|
|
112
|
+
try {
|
|
113
|
+
await this.open(this.audio);
|
|
114
|
+
this.ready();
|
|
115
|
+
if (this.finishing) return;
|
|
116
|
+
await this.untilStop;
|
|
117
|
+
} catch (err) {
|
|
118
|
+
this.failed(err instanceof Error ? err : new Error(String(err)));
|
|
119
|
+
this.release?.();
|
|
120
|
+
} finally {
|
|
121
|
+
this.teardown();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
if (navigator.locks) {
|
|
125
|
+
void navigator.locks.request(`webinar-rec-${this.recordingId}`, { ifAvailable: true }, async (lock) => {
|
|
126
|
+
if (!lock) {
|
|
127
|
+
this.failed(new Error("Recording is already running in another tab"));
|
|
128
|
+
this.teardown();
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
await run();
|
|
132
|
+
});
|
|
133
|
+
} else {
|
|
134
|
+
void run();
|
|
135
|
+
}
|
|
136
|
+
await running;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
sync(tracks) {
|
|
140
|
+
this.tracks = tracks || [];
|
|
141
|
+
if (this.dest) this.retile();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async finish(options = {}) {
|
|
145
|
+
if (this.finishing) return;
|
|
146
|
+
this.finishing = true;
|
|
147
|
+
const rec = this.recorder;
|
|
148
|
+
if (rec && rec.state !== "inactive") {
|
|
149
|
+
const last = new Promise((resolve) => {
|
|
150
|
+
rec.addEventListener("dataavailable", () => resolve(), { once: true });
|
|
151
|
+
rec.addEventListener("stop", () => resolve(), { once: true });
|
|
152
|
+
});
|
|
153
|
+
if (rec.state === "recording") rec.requestData();
|
|
154
|
+
rec.stop();
|
|
155
|
+
await Promise.race([last, sleep(3000)]);
|
|
156
|
+
}
|
|
157
|
+
await this.pump();
|
|
158
|
+
if (options.finalize !== false) await this.finalize();
|
|
159
|
+
this.release?.();
|
|
160
|
+
this.release = undefined;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async handoff() {
|
|
164
|
+
await this.finish({ finalize: false });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
url(path) {
|
|
168
|
+
return `${this.endpoint}${path}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
authHeaders(extra = {}) {
|
|
172
|
+
return {
|
|
173
|
+
...(this.token ? { authorization: `Bearer ${this.token}` } : {}),
|
|
174
|
+
...extra,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async api(method, path, body) {
|
|
179
|
+
const res = await fetch(this.url(path), {
|
|
180
|
+
method,
|
|
181
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
182
|
+
body: body === undefined ? "{}" : JSON.stringify(body),
|
|
183
|
+
});
|
|
184
|
+
const data = await res.json().catch(() => ({}));
|
|
185
|
+
if (!res.ok) throw new Error(data.error ?? "recording upload failed");
|
|
186
|
+
return data;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async open(audio) {
|
|
190
|
+
if (this.finishing) return;
|
|
191
|
+
this.audio = audio ?? new AudioContext();
|
|
192
|
+
await this.audio.resume();
|
|
193
|
+
if (this.audio.state !== "running") throw new Error("Click the page to continue this recording");
|
|
194
|
+
if (this.finishing) return;
|
|
195
|
+
await this.dropOtherWebinars();
|
|
196
|
+
this.canvas = document.createElement("canvas");
|
|
197
|
+
this.canvas.width = W;
|
|
198
|
+
this.canvas.height = H;
|
|
199
|
+
this.ctx = this.canvas.getContext("2d");
|
|
200
|
+
this.canvas.setAttribute("aria-hidden", "true");
|
|
201
|
+
this.canvas.style.cssText = "position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none";
|
|
202
|
+
document.body.appendChild(this.canvas);
|
|
203
|
+
await this.flushStored();
|
|
204
|
+
if (this.finishing) return;
|
|
205
|
+
const opened = await this.api("POST", `/api/chunks/${this.recordingId}/segment`, {
|
|
206
|
+
webinarId: this.webinarId,
|
|
207
|
+
webinarName: this.webinarName,
|
|
208
|
+
next: true,
|
|
209
|
+
});
|
|
210
|
+
this.segment = opened.segment;
|
|
211
|
+
this.seq = 0;
|
|
212
|
+
this.startedAt = Date.now();
|
|
213
|
+
this.dest = this.audio.createMediaStreamDestination();
|
|
214
|
+
const silence = this.audio.createGain();
|
|
215
|
+
silence.gain.value = 0;
|
|
216
|
+
this.clock = this.audio.createOscillator();
|
|
217
|
+
this.clock.connect(silence);
|
|
218
|
+
silence.connect(this.dest);
|
|
219
|
+
this.clock.start();
|
|
220
|
+
this.retile();
|
|
221
|
+
this.ctx.fillStyle = "#000";
|
|
222
|
+
this.ctx.fillRect(0, 0, W, H);
|
|
223
|
+
const worker = new Worker(URL.createObjectURL(new Blob([`setInterval(() => postMessage(0), ${Math.round(1000 / FPS)})`], { type: "text/javascript" })));
|
|
224
|
+
worker.onmessage = () => this.draw();
|
|
225
|
+
this.stopDraw = () => worker.terminate();
|
|
226
|
+
const video = this.canvas.captureStream(FPS).getVideoTracks()[0];
|
|
227
|
+
this.capture = video;
|
|
228
|
+
const stream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
|
|
229
|
+
this.recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: BITRATE, audioBitsPerSecond: 128_000 });
|
|
230
|
+
this.recorder.ondataavailable = (event) => {
|
|
231
|
+
if (event.data.size < 32 || !this.segment) return;
|
|
232
|
+
const seq = ++this.seq;
|
|
233
|
+
void this.store(seq, event.data).then(() => this.pump()).catch(() => undefined);
|
|
234
|
+
};
|
|
235
|
+
this.recorder.onerror = () => {
|
|
236
|
+
void this.finish();
|
|
237
|
+
};
|
|
238
|
+
if (this.finishing) return;
|
|
239
|
+
this.recorder.start(SLICE_MS);
|
|
240
|
+
window.addEventListener("beforeunload", this.onPageHide);
|
|
241
|
+
try {
|
|
242
|
+
this.wake = await navigator.wakeLock?.request("screen");
|
|
243
|
+
} catch {
|
|
244
|
+
// the tab can still record without a wake lock
|
|
245
|
+
}
|
|
246
|
+
this.heartbeat = setInterval(() => {
|
|
247
|
+
this.api("POST", `/api/chunks/${this.recordingId}/heartbeat`).catch(() => undefined);
|
|
248
|
+
}, 15_000);
|
|
249
|
+
this.sweep = setInterval(() => {
|
|
250
|
+
this.tries.clear();
|
|
251
|
+
void this.pump();
|
|
252
|
+
}, 30_000);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
retile() {
|
|
256
|
+
const cameras = new Map();
|
|
257
|
+
const screens = new Map();
|
|
258
|
+
const mics = new Map();
|
|
259
|
+
const screenAudio = new Map();
|
|
260
|
+
for (const item of this.tracks) {
|
|
261
|
+
const off = !item.track.enabled || item.track.muted;
|
|
262
|
+
if (item.source === "mic") {
|
|
263
|
+
if (!off) mics.set(item.isLocal ? "local-mic" : `${item.participantKey}|mic`, item.track);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (item.source === "screen-audio") {
|
|
267
|
+
if (!off) screenAudio.set(item.participantKey, item.track);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (item.kind !== "video") continue;
|
|
271
|
+
if (item.source !== "webcam" && item.source !== "screen") continue;
|
|
272
|
+
if (item.source === "screen" && off) continue;
|
|
273
|
+
if (!item.isLocal && off) continue;
|
|
274
|
+
const kind = item.source === "screen" ? "screen" : "camera";
|
|
275
|
+
const key = `${item.participantKey}|${kind}`;
|
|
276
|
+
const slot = {
|
|
277
|
+
key,
|
|
278
|
+
kind,
|
|
279
|
+
isLocal: item.isLocal,
|
|
280
|
+
participantKey: item.participantKey,
|
|
281
|
+
order: this.orderOf(key),
|
|
282
|
+
video: off ? null : this.videoFor(key, item.track),
|
|
283
|
+
};
|
|
284
|
+
(kind === "screen" ? screens : cameras).set(key, slot);
|
|
285
|
+
}
|
|
286
|
+
if (![...cameras.values()].some((slot) => slot.isLocal)) {
|
|
287
|
+
cameras.set("local|camera", {
|
|
288
|
+
key: "local|camera",
|
|
289
|
+
kind: "camera",
|
|
290
|
+
isLocal: true,
|
|
291
|
+
participantKey: "local",
|
|
292
|
+
order: 0,
|
|
293
|
+
video: null,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
const host = [...cameras.values()].find((slot) => slot.isLocal);
|
|
297
|
+
const others = [...cameras.values()].filter((slot) => !slot.isLocal).sort((a, b) => a.order - b.order).slice(0, 3);
|
|
298
|
+
const chosen = [host, ...others];
|
|
299
|
+
const screen = [...screens.values()].find((slot) => slot.isLocal)
|
|
300
|
+
?? [...screens.values()].sort((a, b) => a.order - b.order)[0];
|
|
301
|
+
this.slots = screen ? [screen, ...chosen] : chosen;
|
|
302
|
+
this.mixAudio(chosen, screen, mics, screenAudio);
|
|
303
|
+
for (const key of [...this.videos.keys()]) {
|
|
304
|
+
if (!this.slots.some((slot) => slot.key === key && slot.video)) {
|
|
305
|
+
const el = this.videos.get(key);
|
|
306
|
+
el?.pause();
|
|
307
|
+
if (el) el.srcObject = null;
|
|
308
|
+
this.videos.delete(key);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
orderOf(key) {
|
|
314
|
+
let n = this.orders.get(key);
|
|
315
|
+
if (!n) {
|
|
316
|
+
n = this.nextOrder;
|
|
317
|
+
this.nextOrder += 1;
|
|
318
|
+
this.orders.set(key, n);
|
|
319
|
+
}
|
|
320
|
+
return n;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
videoFor(key, track) {
|
|
324
|
+
let el = this.videos.get(key);
|
|
325
|
+
const current = el?.srcObject?.getVideoTracks?.()[0];
|
|
326
|
+
if (!el || current !== track) {
|
|
327
|
+
el?.pause();
|
|
328
|
+
el = document.createElement("video");
|
|
329
|
+
el.muted = true;
|
|
330
|
+
el.playsInline = true;
|
|
331
|
+
el.srcObject = new MediaStream([track]);
|
|
332
|
+
void el.play().catch(() => undefined);
|
|
333
|
+
this.videos.set(key, el);
|
|
334
|
+
}
|
|
335
|
+
return el;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
mixAudio(cameras, screen, mics, screenAudio) {
|
|
339
|
+
if (!this.audio || !this.dest) return;
|
|
340
|
+
const wanted = new Map();
|
|
341
|
+
const localMic = mics.get("local-mic");
|
|
342
|
+
if (localMic) wanted.set("local-mic", localMic);
|
|
343
|
+
for (const cam of cameras) {
|
|
344
|
+
if (cam.isLocal) continue;
|
|
345
|
+
const mic = mics.get(`${cam.participantKey}|mic`);
|
|
346
|
+
if (mic) wanted.set(cam.key, mic);
|
|
347
|
+
}
|
|
348
|
+
if (screen) {
|
|
349
|
+
const audio = screenAudio.get(screen.participantKey);
|
|
350
|
+
if (audio) wanted.set(`${screen.key}|audio`, audio);
|
|
351
|
+
}
|
|
352
|
+
for (const [key, node] of this.audioNodes) {
|
|
353
|
+
const track = wanted.get(key);
|
|
354
|
+
if (track && node.mediaStream.getAudioTracks()[0] === track) {
|
|
355
|
+
wanted.delete(key);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
node.disconnect();
|
|
359
|
+
this.audioNodes.delete(key);
|
|
360
|
+
}
|
|
361
|
+
for (const [key, track] of wanted) {
|
|
362
|
+
const node = this.audio.createMediaStreamSource(new MediaStream([track]));
|
|
363
|
+
node.connect(this.dest);
|
|
364
|
+
this.audioNodes.set(key, node);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
draw() {
|
|
369
|
+
if (!this.ctx) return;
|
|
370
|
+
const cameras = this.slots.filter((slot) => slot.kind === "camera");
|
|
371
|
+
const screen = this.slots.find((slot) => slot.kind === "screen");
|
|
372
|
+
const layout = layoutSlots(cameras.length, Boolean(screen));
|
|
373
|
+
this.ctx.fillStyle = "#000";
|
|
374
|
+
this.ctx.fillRect(0, 0, W, H);
|
|
375
|
+
if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen);
|
|
376
|
+
cameras.forEach((slot, index) => {
|
|
377
|
+
const rect = layout.cameras[index];
|
|
378
|
+
if (rect) paint(this.ctx, slot.video, rect);
|
|
379
|
+
});
|
|
380
|
+
this.capture?.requestFrame();
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async dropOtherWebinars() {
|
|
384
|
+
const db = await dbOpen();
|
|
385
|
+
await idbClearOthers(db, this.webinarId, this.recordingId);
|
|
386
|
+
db.close();
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async store(seq, blob) {
|
|
390
|
+
const row = { webinarId: this.webinarId, recordingId: this.recordingId, segment: this.segment, seq, blob };
|
|
391
|
+
const db = await dbOpen();
|
|
392
|
+
await idbPut(db, row);
|
|
393
|
+
db.close();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async flushStored() {
|
|
397
|
+
const db = await dbOpen();
|
|
398
|
+
const rows = await idbAll(db, this.recordingId);
|
|
399
|
+
db.close();
|
|
400
|
+
for (const row of rows) await this.upload(row);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
pump() {
|
|
404
|
+
const run = this.chain.then(() => this.pumpOnce());
|
|
405
|
+
this.chain = run.catch(() => undefined);
|
|
406
|
+
return run;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async pumpOnce() {
|
|
410
|
+
const db = await dbOpen();
|
|
411
|
+
const rows = (await idbAll(db, this.recordingId)).sort((a, b) => a.segment - b.segment || a.seq - b.seq);
|
|
412
|
+
db.close();
|
|
413
|
+
for (const row of rows) {
|
|
414
|
+
const key = `${row.segment}:${row.seq}`;
|
|
415
|
+
const tries = this.tries.get(key) ?? 0;
|
|
416
|
+
if (row.seq !== 1 && tries >= 3) continue;
|
|
417
|
+
const ok = await this.upload(row).catch(() => false);
|
|
418
|
+
this.tries.set(key, tries + 1);
|
|
419
|
+
if (!ok && row.seq === 1) await sleep(1000);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async upload(row) {
|
|
424
|
+
const checksum = await sha256(row.blob);
|
|
425
|
+
const res = await fetch(this.url(`/api/chunks/${this.recordingId}/${row.segment}/${row.seq}`), {
|
|
426
|
+
method: "PUT",
|
|
427
|
+
headers: this.authHeaders({ "content-type": "application/octet-stream", "x-checksum": checksum }),
|
|
428
|
+
body: row.blob,
|
|
429
|
+
});
|
|
430
|
+
if (!res.ok) return false;
|
|
431
|
+
const db = await dbOpen();
|
|
432
|
+
await idbDel(db, row);
|
|
433
|
+
db.close();
|
|
434
|
+
return true;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async finalize() {
|
|
438
|
+
const durationMs = this.startedAt ? Date.now() - this.startedAt : 0;
|
|
439
|
+
for (let round = 0; round < 3; round += 1) {
|
|
440
|
+
const res = await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
|
|
441
|
+
method: "POST",
|
|
442
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
443
|
+
body: JSON.stringify({ durationMs }),
|
|
444
|
+
});
|
|
445
|
+
if (res.ok) return;
|
|
446
|
+
if (res.status !== 409) {
|
|
447
|
+
const data = await res.json().catch(() => ({}));
|
|
448
|
+
throw new Error(data.error || "could not finish the recording");
|
|
449
|
+
}
|
|
450
|
+
const body = await res.json().catch(() => ({}));
|
|
451
|
+
const missing = body.missingChunks ?? [];
|
|
452
|
+
if (!missing.length) return;
|
|
453
|
+
await this.pump();
|
|
454
|
+
const still = await this.hasAny(missing);
|
|
455
|
+
if (!still) {
|
|
456
|
+
await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
|
|
457
|
+
method: "POST",
|
|
458
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
459
|
+
body: JSON.stringify({ durationMs, force: true }),
|
|
460
|
+
});
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
await fetch(this.url(`/api/chunks/${this.recordingId}/finalize`), {
|
|
465
|
+
method: "POST",
|
|
466
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
467
|
+
body: JSON.stringify({ durationMs, force: true }),
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async hasAny(missing) {
|
|
472
|
+
const db = await dbOpen();
|
|
473
|
+
const rows = await idbAll(db, this.recordingId);
|
|
474
|
+
db.close();
|
|
475
|
+
return missing.some((item) => rows.some((row) => row.segment === item.segment && row.seq === item.seq));
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
teardown() {
|
|
479
|
+
this.canvas?.remove();
|
|
480
|
+
window.removeEventListener("beforeunload", this.onPageHide);
|
|
481
|
+
if (this.heartbeat) clearInterval(this.heartbeat);
|
|
482
|
+
if (this.sweep) clearInterval(this.sweep);
|
|
483
|
+
this.stopDraw?.();
|
|
484
|
+
if (this.recorder && this.recorder.state !== "inactive") this.recorder.stop();
|
|
485
|
+
this.videos.forEach((el) => {
|
|
486
|
+
el.pause();
|
|
487
|
+
el.srcObject = null;
|
|
488
|
+
});
|
|
489
|
+
this.videos.clear();
|
|
490
|
+
try {
|
|
491
|
+
this.clock?.stop();
|
|
492
|
+
} catch {
|
|
493
|
+
// already stopped
|
|
494
|
+
}
|
|
495
|
+
this.audioNodes.forEach((node) => node.disconnect());
|
|
496
|
+
this.audioNodes.clear();
|
|
497
|
+
void this.audio?.close();
|
|
498
|
+
void this.wake?.release();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function paint(ctx, video, rect) {
|
|
503
|
+
ctx.fillStyle = "#000";
|
|
504
|
+
ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
|
|
505
|
+
if (!video || video.readyState < 2 || !video.videoWidth) return;
|
|
506
|
+
const scale = Math.min(rect.w / video.videoWidth, rect.h / video.videoHeight);
|
|
507
|
+
const dw = video.videoWidth * scale;
|
|
508
|
+
const dh = video.videoHeight * scale;
|
|
509
|
+
ctx.drawImage(video, rect.x + (rect.w - dw) / 2, rect.y + (rect.h - dh) / 2, dw, dh);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function sleep(ms) {
|
|
513
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async function sha256(blob) {
|
|
517
|
+
const buf = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer());
|
|
518
|
+
return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function dbOpen() {
|
|
522
|
+
return new Promise((resolve, reject) => {
|
|
523
|
+
const req = indexedDB.open("webinar-chunks", 1);
|
|
524
|
+
req.onupgradeneeded = () => {
|
|
525
|
+
const db = req.result;
|
|
526
|
+
if (!db.objectStoreNames.contains("chunks")) db.createObjectStore("chunks", { keyPath: ["recordingId", "segment", "seq"] });
|
|
527
|
+
};
|
|
528
|
+
req.onsuccess = () => resolve(req.result);
|
|
529
|
+
req.onerror = () => reject(req.error);
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function idbPut(db, row) {
|
|
534
|
+
return new Promise((resolve, reject) => {
|
|
535
|
+
const tx = db.transaction("chunks", "readwrite");
|
|
536
|
+
tx.objectStore("chunks").put(row);
|
|
537
|
+
tx.oncomplete = () => resolve();
|
|
538
|
+
tx.onerror = () => reject(tx.error);
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function idbDel(db, row) {
|
|
543
|
+
return new Promise((resolve, reject) => {
|
|
544
|
+
const tx = db.transaction("chunks", "readwrite");
|
|
545
|
+
tx.objectStore("chunks").delete([row.recordingId, row.segment, row.seq]);
|
|
546
|
+
tx.oncomplete = () => resolve();
|
|
547
|
+
tx.onerror = () => reject(tx.error);
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function idbClearOthers(db, webinarId, recordingId) {
|
|
552
|
+
return new Promise((resolve, reject) => {
|
|
553
|
+
const tx = db.transaction("chunks", "readwrite");
|
|
554
|
+
const req = tx.objectStore("chunks").openCursor();
|
|
555
|
+
req.onsuccess = () => {
|
|
556
|
+
const cursor = req.result;
|
|
557
|
+
if (!cursor) return;
|
|
558
|
+
const row = cursor.value;
|
|
559
|
+
const otherWebinar = row.webinarId ? row.webinarId !== webinarId : row.recordingId !== recordingId;
|
|
560
|
+
if (otherWebinar || row.recordingId !== recordingId) cursor.delete();
|
|
561
|
+
cursor.continue();
|
|
562
|
+
};
|
|
563
|
+
req.onerror = () => reject(req.error);
|
|
564
|
+
tx.oncomplete = () => resolve();
|
|
565
|
+
tx.onerror = () => reject(tx.error);
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function idbAll(db, recordingId) {
|
|
570
|
+
return new Promise((resolve, reject) => {
|
|
571
|
+
const tx = db.transaction("chunks", "readonly");
|
|
572
|
+
const req = tx.objectStore("chunks").getAll();
|
|
573
|
+
req.onsuccess = () => resolve(req.result.filter((row) => row.recordingId === recordingId));
|
|
574
|
+
req.onerror = () => reject(req.error);
|
|
575
|
+
});
|
|
576
|
+
}
|
package/README.md
DELETED