-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
241 lines (207 loc) · 7.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import React, { useEffect, useState, useRef } from 'react';
import Head from 'next/head';
import styles from '../styles/demo.module.css';
const CAMERA_CONSTRAINTS = {
audio: true,
video: true,
};
const getRecorderSettings = () => {
const settings = {};
if (MediaRecorder.isTypeSupported('video/mp4')) {
settings.format = 'mp4';
settings.video = 'h264';
settings.audio = 'aac';
} else {
settings.format = 'webm';
settings.audio = 'opus';
settings.video = MediaRecorder.isTypeSupported('video/webm;codecs=h264') ? 'h264' : 'vp8';
}
return settings;
}
const getRecorderMimeType = () => {
const settings = getRecorderSettings();
const codecs = settings.format === 'webm' ? `;codecs="${settings.video}, ${settings.audio}"` : '';
return `video/${settings.format}${codecs}`;
}
export default () => {
const [connected, setConnected] = useState(false);
const [cameraEnabled, setCameraEnabled] = useState(false);
const [streaming, setStreaming] = useState(false);
const [streamKey, setStreamKey] = useState(null);
const [streamUrl, setStreamUrl] = useState(null);
const [textOverlay, setTextOverlay] = useState('Live from the browser!');
const inputStreamRef = useRef();
const videoRef = useRef();
const canvasRef = useRef();
const wsRef = useRef();
const mediaRecorderRef = useRef();
const requestAnimationRef = useRef();
const nameRef = useRef();
const enableCamera = async () => {
inputStreamRef.current = await navigator.mediaDevices.getUserMedia(
CAMERA_CONSTRAINTS
);
videoRef.current.srcObject = inputStreamRef.current;
await videoRef.current.play();
// We need to set the canvas height/width to match the video element.
canvasRef.current.height = videoRef.current.clientHeight;
canvasRef.current.width = videoRef.current.clientWidth;
requestAnimationRef.current = requestAnimationFrame(updateCanvas);
setCameraEnabled(true);
};
const updateCanvas = () => {
if (videoRef.current.ended || videoRef.current.paused) {
return;
}
const ctx = canvasRef.current.getContext('2d');
ctx.drawImage(
videoRef.current,
0,
0,
videoRef.current.clientWidth,
videoRef.current.clientHeight
);
ctx.fillStyle = '#FB3C4E';
ctx.font = '50px Akkurat';
const date = new Date();
const dateText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}.${date.getMilliseconds().toString().padStart(3, '0')}`;
ctx.fillText(`${nameRef.current}${dateText}`, 10, 50, canvasRef.current.width - 20);
requestAnimationRef.current = requestAnimationFrame(updateCanvas);
};
const stopStreaming = () => {
if (mediaRecorderRef.current.state === 'recording') {
mediaRecorderRef.current.stop();
}
setStreaming(false);
};
const startStreaming = () => {
setStreaming(true);
const settings = getRecorderSettings();
const protocol = window.location.protocol.replace('http', 'ws');
const wsUrl = new URL(`${protocol}//${window.location.host}/rtmp`);
wsUrl.searchParams.set('video', settings.video);
wsUrl.searchParams.set('audio', settings.audio);
if (streamUrl) {
wsUrl.searchParams.set('url', streamUrl);
}
if (streamKey) {
wsUrl.searchParams.set('key', streamKey);
}
wsRef.current = new WebSocket(wsUrl);
wsRef.current.addEventListener('open', function open() {
setConnected(true);
});
wsRef.current.addEventListener('close', () => {
setConnected(false);
stopStreaming();
});
const videoOutputStream = canvasRef.current.captureStream(30); // 30 FPS
// Let's do some extra work to get audio to join the party.
// https://hacks.mozilla.org/2016/04/record-almost-everything-in-the-browser-with-mediarecorder/
const audioStream = new MediaStream();
const audioTracks = inputStreamRef.current.getAudioTracks();
audioTracks.forEach(function (track) {
audioStream.addTrack(track);
});
const outputStream = new MediaStream();
[audioStream, videoOutputStream].forEach(function (s) {
s.getTracks().forEach(function (t) {
outputStream.addTrack(t);
});
});
mediaRecorderRef.current = new MediaRecorder(outputStream, {
mimeType: getRecorderMimeType(),
videoBitsPerSecond: 3000000,
audioBitsPerSecond: 64000,
});
mediaRecorderRef.current.addEventListener('dataavailable', (e) => {
wsRef.current.send(e.data);
});
mediaRecorderRef.current.addEventListener('stop', () => {
stopStreaming();
wsRef.current.close();
});
mediaRecorderRef.current.start(1000);
};
useEffect(() => {
nameRef.current = textOverlay;
}, [textOverlay]);
useEffect(() => {
return () => {
cancelAnimationFrame(requestAnimationRef.current);
};
}, []);
return (
<div className={styles.container}>
<Head>
<title>Wocket</title>
</Head>
<div className={styles.info}>
<h1>Wocket</h1>
<p>
A demo using modern web technologies to broadcast video from a browser
to a server via WebSockets. To learn more, see the <a href="https://github.com/MuxLabs/wocket">Github repo</a> or check out the <a href="https://mux.com/blog/the-state-of-going-live-from-a-browser/">Mux blog post</a> on the topic.
</p>
<p>
This service is provided "as is," with no uptime guarantees, support, or any of the usual stuff people pay for.
</p>
{cameraEnabled &&
(streaming ? (
<div>
<span
className={`${styles.streamStatus} ${
connected ? styles.connected : styles.disconnected
}`}
>
{connected ? 'Connected' : 'Disconnected'}
</span>
<input
placeholder="Text Overlay"
type="text"
value={textOverlay}
onChange={(e) => setTextOverlay(e.target.value)}
/>
<button onClick={stopStreaming}>Stop Streaming</button>
</div>
) : (
<>
<input
placeholder="rtmps://global-live.mux.com/app"
type="text"
onChange={(e) => setStreamUrl(e.target.value)}
/>
<input
placeholder="Stream key"
type="text"
onChange={(e) => setStreamKey(e.target.value)}
/>
<button
className={styles.startButton}
disabled={!streamKey}
onClick={startStreaming}
>
Start Streaming
</button>
</>
))}
</div>
<div
className={`${styles.videoContainer} ${
cameraEnabled && styles.cameraEnabled
}`}
>
{!cameraEnabled && (
<button className={styles.startButton} onClick={enableCamera}>
Enable Camera
</button>
)}
<div className={styles.inputVideo}>
<video ref={videoRef} muted playsInline></video>
</div>
<div className={styles.outputCanvas}>
<canvas ref={canvasRef}></canvas>
</div>
</div>
</div>
);
};