-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDMXWebRTC.js
578 lines (533 loc) · 13.2 KB
/
DMXWebRTC.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
'use strict'
const EventEmitter = require('events').EventEmitter
const Ws = require("ws")
const Dgram = require("dgram");
const {
networkInterfaces
} = require("os");
const WebRTC = require("@cubicleai/wrtc");
/**
* Dgram socket options
*
* @constant {Object} UDP_OPT
* @global
*/
const UDP_OPT = {
type: "udp4",
reuseAddr: true,
}
/**
* List of handled WabRTC messages
*
* @constant {Object} WS_MSG_TYPES
* @global
*/
const WS_MSG_TYPES = {
WebRTC_OFFER: "__WRTC_OFR",
WebRTC_ANSWER: "__WRTC_ANS",
WebRTC_STATE: "__WRTC_STA",
WebRTC_END: "__WRTC_END",
}
/**
* List of ArtNet OPCODES
*
* @constant {Object} ARTNET_OPCODES
* @global
*/
const ARTNET_OPCODES = {
//Device Discovery Packets
OpPoll: 0x2000,
OpPollReply: 0x2100,
//Device Configuration Packets
OpAddress: 0x6000,
OpInput: 0x7000,
OpIpProg: 0xF800,
OpIpProgReply: 0xF900,
OpCOmmand: 0x2400,
//Streaming Control Packets
OpDmx: 0x5000,
OpNzs: 0x5100,
OpSync: 0x5200,
//RDM Packets
OpTodRequest: 0x8000,
OpTodData: 0x8100,
OpTodControl: 0x8200,
OpRdm: 0x8300,
OpRdmSub: 0x8400,
//Time-Keeping Packets
OpTimeCode: 0x9700,
OpTimeSync: 0x9800,
//Triggering Packets
OpTrigger: 9900,
//Diagnostics Packets
OpDiagData: 0x2300
}
/**
* ArtNet protocol version
*
* @constant {Object} ARTNET_PROTOCOL_VERSION
* @global
*/
const ARTNET_PROTOCOL_VERSION = {
HI: 0,
LO: 14
}
/**
* ArtDMX packet SubUni slot byte offset
*
* @constant {Number} ARTNET_PACKET_UNIVERSE_LOW_OFFSET
* @global
*/
const ARTNET_PACKET_UNIVERSE_LOW_OFFSET = 14;
/**
* ArtDMX packet Net slot byte offset
*
* @constant {Number} ARTNET_PACKET_UNIVERSE_HI_OFFSET
* @global
*/
const ARTNET_PACKET_UNIVERSE_HI_OFFSET = 15;
/**
* ArtDMX packet Data slot byte offset
*
* @constant {Number} ARTNET_PACKET_UNIVERSE_HI_OFFSET
* @global
*/
const ARTNET_PACKET_DATA_OFFSET = 18;
/**
* DataChannel identifier to be incremented at each new DataChannel instanciation.
*
* @var {Number} channelId
* @global
*/
var channelId = 0;
/**
* ArtNet packet sequence to be incremented on each packet forwarding (limit to 255).
*
* @var {Number} channelId
* @global
*/
var sequence = 0;
/**
* ArtNet Streaming packet model.
*
* @class ArtNetStreamingPacket
*/
class ArtNetStreamingPacket {
/**
* ArtNetStreamingPacket contructructor
*
* @constructs ArtNetStreamingPacket
* @param {Object} data
* @param {Number} data.opCode ArtNet packet packet opcode
* @param {Number} data.universe ArtNet packet universe
* @param {Array<Number>} data.data ArtNet packet data
*/
constructor(data) {
this._opCodeLo = 0;
this._opCodeHi = 0;
this._protVerHi = ARTNET_PROTOCOL_VERSION.HI;
this._protVerLo = ARTNET_PROTOCOL_VERSION.LO;
this._sequence = sequence++ % 255;
this._physical = 0;
this._subUni = 0;
this._net = 0;
this._lengthHi = 0;
this._lengthLo = 0;
this._data = [];
this.id = "Art-Net";
this.opCode = data.opCode;
this.universe = data.universe;
this.length = 0;
this.data = data.data;
}
/**
* ArtNet packet universe ID
*
* @property {Number} universe
*/
set universe(universe) {
this._subUni = ArtNetStreamingPacket.getLo(universe);
this._net = ArtNetStreamingPacket.getHi(universe);
}
/**
* ArtNet packet universe opCode
*
* @property {Number} opCode
*/
set opCode(opCode) {
this._opCodeLo = ArtNetStreamingPacket.getLo(opCode);
this._opCodeHi = ArtNetStreamingPacket.getHi(opCode);
}
/**
* ArtNet packet data
*
* @property {Number} data
*/
set data(data) {
this._data = data;
this._lengthLo = ArtNetStreamingPacket.getLo(data.length);
this._lengthHi = ArtNetStreamingPacket.getHi(data.length);
}
/**
* ArtNet packet data
*
* @property {Number} final
* @returns {Array<Number>} raw ArtNet packet
*/
get final() {
return [
this.id.split('').map(c => c.charCodeAt(0)).concat(0x00),
this._opCodeLo,
this._opCodeHi,
this._protVerHi,
this._protVerLo,
this._sequence,
this._physical,
this._subUni,
this._net,
this._lengthHi,
this._lengthLo,
this._data
].flat()
}
/**
* ArtNet packet buffer
*
* @property {Number} buffer
* @returns {Array<Number>} bufferized ArtNet packet
*/
get buffer() {
return Buffer.from(this.final)
}
/**
* Returns an integer's Low byte
*
* @method getLo
* @param {Number} bytes Integer to be parsed
* @returns {Number} Value's Low byte
*/
static getLo(bytes) {
return bytes & 0xFF;
}
/**
* Returns an integer's High byte
*
* @method getLo
* @param {Number} bytes Integer to be parsed
* @returns {Number} Value's High byte
*/
static getHi(bytes) {
return (bytes >> 8) & 0xFF
}
}
/**
* ArtDMX Streaming packet model.
*
* @class ArtDmxPacket
* @extends ArtNetStreamingPacket
*/
class ArtDmxPacket extends ArtNetStreamingPacket {
/**
* ArtDmxPacket constructor
*
* @constructs ArtDmxPacket
* @param {Number} universe
* @param {Array<Number>} data
*/
constructor(universe, data) {
super({
opCode: ARTNET_OPCODES.OpDmx,
universe: universe,
data: data
})
}
}
/**
* WebRTC Data channel overlayer
*
* @class
* @extends EventEmitter
*/
class DataChannel extends EventEmitter {
/**
* DataChannel constructor
*
* @constructs DataChannel
* @param {Object} handle handle to a WebRTC data channel object
*/
constructor(handle) {
super();
this.id = channelId++;
this.handle = handle;
this.handle.addEventListener("message", this.handleMsg.bind(this));
this.handle.addEventListener("close", this.handleClose.bind(this));
}
/**
* Handle channel closure
*
* @method handleClose
* @public
*/
handleClose() {
this.emit("close", this.id);
}
/**
* Handle channel message
*
* @method handleMsg
* @param {Object} data WebRTC sata channel message
* @public
*/
handleMsg(data) {
this.emit("message", data);
}
/**
* Send data over the channel
*
* @method send
* @param {String} data A stringified message
* @public
*/
send(data) {
if (this.handle.readyState === 'open') {
this.handle.send(data);
}
}
}
/**
* DMXWebRTC model
*
* @class
* @singleton
* @extends EventEmitter
*/
class DMXWebRTC {
/**
* Constructs DMXWebRTC
* @constructs DMXWebRTC
*/
constructor() {
if (!DMXWebRTCInstance) {
this.dataChannels = [];
this.outputs = [];
DMXWebRTCInstance = this;
}
return DMXWebRTCInstance;
}
/**
* Print ASLS watermark
*
* @method printWatermark
* @public
*/
printWatermark() {
console.log(` ___ ___ ___ ___
/ /\\ / /\\ / /\\ / /\\
/ /::\\ / /::\\ / /:/ / /::\\
/ /:/\\:\\ /__/:/\\:\\ / /:/ /__/:/\\:\\
/ /::\\ \\:\\ _\\_ \\:\\ \\:\\ / /:/ _\\_ \\:\\ \\:\\
/__/:/\\:\\_\\:\\ /__/\\ \\:\\ \\:\\ /__/:/ /__/\\ \\:\\ \\:\\
\\__\\/ \\:\\/:/ \\ \\:\\ \\:\\_\\/ \\ \\:\\ \\ \\:\\ \\:\\_\\/
\\__\\::/ \\ \\:\\_\\:\\ \\ \\:\\ \\ \\:\\_\\:\\
/ /:/ \\ \\:\\/:/ \\ \\:\\ \\ \\:\\/:/
/__/:/ \\ \\::/ \\ \\:\\ \\ \\::/
\\__\\/ \\__\\/ \\__\\/ \\__\\/
`);
}
/**
* Print GPL notice
*
* @method printGPLNotice
* @public
*/
printGPLNotice() {
console.log(`DMXWebRTC_Server Copyright (C) ${new Date().getFullYear()} Timé Kadel.
This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it
under certain conditions;\n\n`)
}
/**
* Initialise DMXWebRTC singleton instance
*
* @method init
* @public
* @param {Number} wsPort websocket port over which signaling will be done
* @param {Number} udpPort Artnet server port over which packet transactions will be made
*/
init(wsPort = 5214, udpPort = 6454) {
this.printWatermark();
this.printGPLNotice();
this.wsPort = wsPort;
this.udpPort = udpPort;
console.log('Initialising DMWXWebRTC Server Instance...')
console.log(`Websocket signaling through port ${this.wsPort}`);
console.log(`Intercepting and forwarding ArtDMX packets on port ${this.udpPort}\n`);
this.wss = new Ws.Server({
port: wsPort
})
this.ws = null;
this.artnetSocket = Dgram.createSocket(UDP_OPT);
this.artnetSocket.bind(udpPort, undefined, () => {
this.artnetSocket.setBroadcast(true)
});
this.prepareWebRTCPeer();
this.prepareWSListeners();
}
/**
* Prepares web socket listeners
*
* @method prepareWSListeners
* @public
*/
prepareWSListeners() {
this.wss.on('connection', (ws) => {
this.ws = ws;
ws.on("message", async (jsonMsg) => {
let msg = JSON.parse(jsonMsg);
switch (msg.type) {
case WS_MSG_TYPES.WebRTC_OFFER:
console.log(`Websocket offer from: ${ws._socket.remoteAddress}`);
ws.send(JSON.stringify({
type: WS_MSG_TYPES.WebRTC_OFFER,
data: this.peer.localDescription
}));
break;
case WS_MSG_TYPES.WebRTC_ANSWER:
this.bindWRTCDatachannel(msg.data)
break;
}
})
})
}
prepareWebRTCPeer(){
this.peer = new WebRTC.RTCPeerConnection();
this.peer.ondatachannel = this.dataChannelHandler.bind(this);
}
/**
* Handles client offer and prepares peer connection and data channel
*
* @method bindWRTCDatachannel
* @public
* @param {String} sdp WebRTC Session Description Protocol
*/
async bindWRTCDatachannel(sdp) {
await this.peer.setRemoteDescription(new WebRTC.RTCSessionDescription({ type: 'offer', sdp }));
console.log(`Preparing answer`);
await this.peer.setLocalDescription(await this.peer.createAnswer());
console.log(`Waiting fo data channel..\n`);
this.peer.localDescription;
this.ws.send(JSON.stringify({
type: WS_MSG_TYPES.WebRTC_ANSWER,
data: this.peer.localDescription.sdp,
}));
}
/**
* Handles DAtaChannel instance creation and lifecycle
*
* @method dataChannelHandler
* @param {Object} channel WebRTC data channel instance
* @public
*/
dataChannelHandler({
channel
}) {
console.log(`Creating new DMX data channel`);
let dataChannel = new DataChannel(channel)
this.dataChannels.push(dataChannel);
dataChannel.on("message", this.forwardDMXData.bind(this))
dataChannel.on("connect", () => {
console.log("Data channel connected.")
})
dataChannel.on("close", (id) => {
console.log(`Data channel closed`);
let dcIndex = this.dataChannels.findIndex(dc => dc.id === id);
if (dcIndex > 1) {
this.dataChannels.splice(dcIndex, 1);
}
})
}
/**
* Forwards ArtDMX packet to artnet to artnet server
*
* @method forwardDMXData
* @param {Object} data raw DMX universe data
* @public
*/
forwardDMXData({
data
}) {
let artnetPacket = new ArtDmxPacket(0, data);
console.log(artnetPacket)
this.artnetSocket.send(artnetPacket.buffer, 0, artnetPacket.buffer.length, this.udpPort, '127.0.0.1')
}
/**
* Parses ArtDMX packets incoming from artnet server
*
* @method parseARTNetData
* @public
* @param {Buffer} artnetFrame ArtDMX packet
* @return {Object} parsed DMX data
*/
static parseARTNetData(artnetFrame) {
var DMXData = artnetFrame.slice(ARTNET_PACKET_DATA_OFFSET);
let lo_uni_byte = artnetFrame[ARTNET_PACKET_UNIVERSE_LOW_OFFSET];
let hi_uni_byte = artnetFrame[ARTNET_PACKET_UNIVERSE_HI_OFFSET];
let universe_id = ((hi_uni_byte << 8) + (lo_uni_byte & 0xFF))
return {
universe: universe_id,
DMX512Buffer: DMXData
}
}
/**
* Computes broadcast address from cidr
*
* @method _getBroadcastFromCidr
* @static
* @param {String} address ip address string
* @param {String} netmask netmask string
* @return {String} Interface's broadcast address
*/
static _getBroadcast(address, netmask) {
const ip = DMXWebRTC._IPToInt(address);
const mask = DMXWebRTC._IPToInt(netmask);
const min = (ip & mask) >>> 0;
const max = (min | ~mask) >>> 0;
return DMXWebRTC._intToIP(max);
}
/**
* Converts ip address string to unsigned 32bit integer
*
* @method _IPToInt
* @static
* @param {String} ipStr ip address string
* @returns {Number} ip address converted to unsigned 32bit integer
*/
static _IPToInt(ipStr) {
console.log(ipStr)
const chunks = ipStr.split(".");
let ip = 0;
chunks.forEach(chunk => {
ip <<= 8;
ip += parseInt(chunk);
})
return ip >>> 0;
}
/**
* Converts unsigned 32bit integer to ip address string
*
* @method _intToIP
* @static
* @param {Number} intVal unsigned 32bit integer
* @return {String} unsigned 32bit integer ip address converted to string
*/
static _intToIP(intVal) {
let ip = []
for (let i = 4; i > 0; i--) {
ip.unshift((intVal & 0x000000FF) >>> 0)
intVal = intVal >> 8
}
return ip.join(".")
}
}
var DMXWebRTCInstance = new DMXWebRTC();
module.exports = DMXWebRTCInstance;