janus-plugin-sfu/client/tiny.js

203 строки
7.0 KiB
JavaScript
Исходник Обычный вид История

const params = new URLSearchParams(location.search.slice(1));
2017-10-24 01:18:40 +03:00
var USER_ID = Math.floor(Math.random() * (1000000001));
2018-04-10 05:06:57 +03:00
const roomId = params.get("room") != null ? params.get("room") : "42";
2017-10-27 23:43:53 +03:00
2017-10-21 03:44:15 +03:00
const PEER_CONNECTION_CONFIG = {
2017-11-02 23:41:27 +03:00
iceServers: [
{ urls: "stun:stun.l.google.com:19302" },
{ urls: "stun:global.stun.twilio.com:3478?transport=udp" }
]
2017-10-21 03:44:15 +03:00
};
2017-10-07 03:10:12 +03:00
// global helper for interactive use
var c = {
2017-11-02 23:41:27 +03:00
session: null,
publisher: null,
subscribers: {}
};
2017-11-15 05:53:13 +03:00
const status = document.getElementById("status");
function showStatus(message) {
status.textContent = message;
}
2017-11-14 03:03:38 +03:00
function isError(signal) {
var isPluginError =
signal.plugindata &&
signal.plugindata.data &&
signal.plugindata.data.success === false;
return isPluginError || Minijanus.JanusSession.prototype.isError(signal);
}
2017-11-14 03:03:38 +03:00
function connect(server) {
document.getElementById("janusServer").value = server;
2017-11-15 05:53:13 +03:00
showStatus(`Connecting to ${server}...`);
var ws = new WebSocket(server, "janus-protocol");
var session = c.session = new Minijanus.JanusSession(ws.send.bind(ws), { verbose: true });
session.isError = isError;
ws.addEventListener("message", ev => session.receive(JSON.parse(ev.data)));
ws.addEventListener("open", _ => {
session.create()
.then(_ => attachPublisher(session))
2018-03-31 05:48:37 +03:00
.then(x => { c.publisher = x; }, err => console.error("Error attaching publisher: ", err));
2017-11-02 23:41:27 +03:00
});
2017-10-21 03:44:15 +03:00
}
2017-10-07 03:10:12 +03:00
document.getElementById("micButton").addEventListener("click", _ => {
var constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints)
.then(m => m.getTracks().forEach(t => c.publisher.conn.addTrack(t, m)))
.catch(e => console.error("Error requesting media: ", e));
});
2017-10-07 03:10:12 +03:00
document.getElementById("screenButton").addEventListener("click", _ => {
var constraints = { video: { mediaSource: "screen" } };
navigator.mediaDevices.getUserMedia(constraints)
.then(m => m.getTracks().forEach(t => c.publisher.conn.addTrack(t, m)))
.catch(e => console.error("Error requesting media: ", e));
});
2017-10-21 11:01:42 +03:00
function addUser(session, userId) {
2017-11-02 23:41:27 +03:00
console.info("Adding user " + userId + ".");
return attachSubscriber(session, userId)
2018-03-31 05:48:37 +03:00
.then(x => { c.subscribers[userId] = x; }, err => console.error("Error attaching subscriber: ", err));
}
function removeUser(session, userId) {
2017-11-02 23:41:27 +03:00
console.info("Removing user " + userId + ".");
2018-03-31 05:48:37 +03:00
document.querySelectorAll('.media-' + userId).forEach(el => el.remove());
2017-11-02 23:41:27 +03:00
var subscriber = c.subscribers[userId];
if (subscriber != null) {
subscriber.handle.detach();
subscriber.conn.close();
delete c.subscribers[userId];
}
}
let messages = [];
2017-11-10 23:19:34 +03:00
const messageCount = document.getElementById("messageCount");
function updateMessageCount() {
messageCount.textContent = messages.length;
}
let firstMessageTime;
function storeMessage(data, reliable) {
if (!firstMessageTime) {
firstMessageTime = performance.now();
}
messages.push({
time: performance.now() - firstMessageTime,
reliable,
message: JSON.parse(data)
});
2017-11-10 23:19:34 +03:00
updateMessageCount();
}
function storeReliableMessage(ev) {
storeMessage(ev.data, true);
}
function storeUnreliableMessage(ev) {
storeMessage(ev.data, false);
}
document.getElementById("saveButton").addEventListener("click", function saveToMessagesFile() {
const file = new File([JSON.stringify(messages)], "messages.json", {type: "text/json"});
saveAs(file);
});
document.getElementById("clearButton").addEventListener("click", function clearMessages() {
messages = [];
2017-11-10 23:19:34 +03:00
updateMessageCount();
});
function waitForEvent(name, handle) {
return new Promise(resolve => handle.on(name, resolve));
}
function associate(conn, handle) {
conn.addEventListener("icecandidate", ev => {
handle.sendTrickle(ev.candidate || null).catch(e => console.error("Error trickling ICE: ", e));
});
conn.addEventListener("negotiationneeded", _ => {
console.info("Sending new offer for handle: ", handle);
var offer = conn.createOffer();
var local = offer.then(o => conn.setLocalDescription(o));
var remote = offer.then(j => handle.sendJsep(j)).then(r => conn.setRemoteDescription(r.jsep));
Promise.all([local, remote]).catch(e => console.error("Error negotiating offer: ", e));
});
handle.on("event", ev => {
if (ev.jsep && ev.jsep.type == "offer") {
console.info("Accepting new offer for handle: ", handle);
var answer = conn.setRemoteDescription(ev.jsep).then(_ => conn.createAnswer());
var local = answer.then(a => conn.setLocalDescription(a));
var remote = answer.then(j => handle.sendJsep(j));
Promise.all([local, remote]).catch(e => console.error("Error negotiating answer: ", e));
}
});
}
2018-03-31 05:48:37 +03:00
async function attachPublisher(session) {
2017-11-02 23:41:27 +03:00
console.info("Attaching publisher for session: ", session);
var conn = new RTCPeerConnection(PEER_CONNECTION_CONFIG);
var handle = new Minijanus.JanusPluginHandle(session);
associate(conn, handle);
// Handle all of the join and leave events.
handle.on("event", ev => {
var data = ev.plugindata.data;
if (data.event == "join" && data.room_id == roomId) {
this.addUser(session, data.user_id);
} else if (data.event == "leave" && data.room_id == roomId) {
this.removeUser(session, data.user_id);
}
});
2018-03-31 05:48:37 +03:00
await handle.attach("janus.plugin.sfu")
showStatus(`Connecting WebRTC...`);
const reliableChannel = conn.createDataChannel("reliable", { ordered: true });
reliableChannel.addEventListener("message", storeReliableMessage);
const unreliableChannel = conn.createDataChannel("unreliable", { ordered: false, maxRetransmits: 0 });
unreliableChannel.addEventListener("message", storeUnreliableMessage);
await waitForEvent("webrtcup", handle);
showStatus(`Joining room ${roomId}...`);
2018-04-10 05:06:57 +03:00
const reply = await handle.sendMessage({
2018-03-31 05:48:37 +03:00
kind: "join",
room_id: roomId,
user_id: USER_ID,
subscribe: { notifications: true, data: true }
2017-11-02 23:41:27 +03:00
});
2018-03-31 05:48:37 +03:00
showStatus(`Subscribing to others in room ${roomId}`);
var occupants = reply.plugindata.data.response.users[roomId] || [];
await Promise.all(occupants.map(userId => addUser(session, userId)));
return { handle, conn, reliableChannel, unreliableChannel };
2017-09-28 13:13:09 +03:00
}
2017-10-07 03:10:12 +03:00
2017-10-21 03:44:15 +03:00
function attachSubscriber(session, otherId) {
2017-11-02 23:41:27 +03:00
console.info("Attaching subscriber to " + otherId + " for session: ", session);
var conn = new RTCPeerConnection(PEER_CONNECTION_CONFIG);
var handle = new Minijanus.JanusPluginHandle(session);
associate(conn, handle);
conn.addEventListener("track", ev => {
2018-01-11 03:16:07 +03:00
console.info("Attaching " + ev.track.kind + " track from " + otherId + " for session: ", session);
var mediaEl = document.createElement(ev.track.kind);
2018-03-31 05:48:37 +03:00
mediaEl.className = 'media-' + otherId;
mediaEl.controls = true;
2018-03-31 05:48:37 +03:00
mediaEl.autoplay = true;
mediaEl.srcObject = ev.streams[0];
2018-03-31 05:48:37 +03:00
document.body.appendChild(mediaEl);
});
2017-10-21 03:44:15 +03:00
2017-11-02 23:41:27 +03:00
return handle.attach("janus.plugin.sfu")
.then(_ => handle.sendMessage({ kind: "join", room_id: roomId, user_id: USER_ID, subscribe: { media: otherId }}))
.then(_ => waitForEvent("webrtcup", handle))
.then(_ => { return { handle: handle, conn: conn }; });
2017-10-07 03:10:12 +03:00
}
2017-10-21 03:44:15 +03:00
connect(params.get("janus") || `ws://localhost:8188`);