forked from hydra-synth/hydra-synth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·468 lines (424 loc) · 13.3 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
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
const Output = require('./src/output.js')
const loop = require('raf-loop')
const Source = require('./src/hydra-source.js')
const GeneratorFactory = require('./src/GeneratorFactory.js')
const getUserMedia = require('getusermedia')
const mouse = require('mouse-change')()
const Audio = require('./src/audio.js')
const VidRecorder = require('./src/video-recorder.js')
// to do: add ability to pass in certain uniforms and transforms
class HydraSynth {
constructor ({
pb = null,
width = 1280,
height = 720,
numSources = 4,
numOutputs = 4,
makeGlobal = true,
autoLoop = true,
detectAudio = true,
enableStreamCapture = true,
canvas
} = {}) {
this.bpm = 60
this.pb = pb
this.width = width
this.height = height
this.time = 0
this.makeGlobal = makeGlobal
this.renderAll = false
this.detectAudio = detectAudio
// boolean to store when to save screenshot
this.saveFrame = false
// boolean to store when to send frame via websocket
this.sendFrame = false
// boolean to store if webrtc is setup
this.webrtcsetup = false
// if stream capture is enabled, this object contains the capture stream
this.captureStream = null
this._initCanvas(canvas)
this._initRegl()
this._initOutputs(numOutputs)
this._initSources(numSources)
this._generateGlslTransforms()
window.screencap = () => {
this.saveFrame = true
}
window.wssend = () => {
this.sendFrame = !this.sendFrame
}
// websocket begin
let peerConn = null;
/*window.socket = new WebSocket('ws://127.0.0.1:8088');
window.socket.onmessage = function(evt) {
var messageData = JSON.parse(evt.data);
if (messageData.sdp) {
console.log('Received SDP from remote peer');
peerConn.setRemoteDescription(new RTCSessionDescription(messageData.sdp));
} else if (messageData.candidate) {
console.log('Received ICECandidate from remote peer ' + messageData.candidate);
} else {
console.log('Received from remote peer ' + evt.data);
}
}; */
window.ws = (function (uri) {
console.log('ws init')
ws = new WebSocket(uri);
ws.onmessage = function(evt) {
var messageData = JSON.parse(evt.data);
if (messageData.sdp) {
console.log('Received SDP from remote peer');
peerConn.setRemoteDescription(new RTCSessionDescription(messageData.sdp));
} else if (messageData.candidate) {
console.log('Received ICECandidate from remote peer ' + messageData.candidate);
} else if (messageData.hydra) {
console.log('Received hydramsg from remote peer ' + messageData.hydra);
} else if (messageData.editortext) {
console.log('Received editortext from remote peer ' + messageData.editortext);
var editorEvt = new CustomEvent(messageData.event);
editorEvt.data = messageData.message;
if (window.editor && window.editor.cm ) {
window.editor.cm.setValue(messageData.message)
}
ws.dispatchEvent(editorEvt);
} else {
console.log('Received from remote peer ' + evt.data);
}
//var customEvt = new CustomEvent(messageData.event);
//customEvt.data = messageData.message;
//ws.dispatchEvent(customEvt);
};
this.emit = function(evt, data) {
ws.send(JSON.stringify({event:evt, message: data}));
};
this.send = function(data) {
console.log('ws readyState' + ws.readyState);
/*
CONNECTING 0
OPEN 1
CLOSING 2
CLOSED 3
*/
if (ws.readyState == 1) ws.send(data);
};
this.on = function(evt, func) {
ws.addEventListener(evt, func);
};
ws.onerror = function(e) {console.log('error: ' + e)};
ws.onopen = function(evt) {console.log('Socket opened')};
ws.onclose = function(evt) {console.log('Socket closed')};
});
//window.socket = new ws('ws://turbulens.fr/ws/');
window.socket = new ws('ws://127.0.0.1:8088');
// websocket end
// webrtc begin
function onIceCandidateHandler(pc, event) {
if (window.socket) window.socket.send(JSON.stringify({ 'candidate': event.candidate }));
console.log(`ICE candidate: ${event.candidate ? event.candidate.candidate : '(null)'}`);
}
window.webrtcsend = () => {
if (this.webrtcsetup) {
console.log("webrtc is setup")
this.captureStream = this.canvas.captureStream(25)
peerConn.addStream(this.captureStream);
}
else {
console.log("webrtc setup")
// check duplicate of enableStreamCapture for window.vidRecorder
this.captureStream = this.canvas.captureStream(25)
console.log('Starting call');
const videoTracks = this.captureStream.getVideoTracks();
if (videoTracks.length > 0) {
console.log(`Using video device: ${videoTracks[0].label}`);
}
const servers = {
'iceServers': [{ 'urls': 'stun:stun.l.google.com:19302' }]
};
peerConn = new RTCPeerConnection(servers);
console.log('Created local peer connection object peerConn, ' + peerConn.signalingState);
//peerConn.onicecandidate = e => onIceCandidateHandler(peerConn, e);
peerConn.addStream(this.captureStream);
console.log('Added local captureStream to peerConn');
console.log('peerConn createOffer start');
peerConn.createOffer(
function (offer) {
let off = new RTCSessionDescription(offer);
peerConn.setLocalDescription(new RTCSessionDescription(off),
function () {
window.socket.send(JSON.stringify({ 'sdp': off }));
},
function (error) { console.log('createAndSendOffer:' + error); }
);
},
function (error) { console.log('createAndSendOffer:' + error); }
);
peerConn.onicecandidate = e => onIceCandidateHandler(peerConn, e);
this.webrtcsetup = true
}
}
// webrtc end
if (enableStreamCapture) {
this.captureStream = this.canvas.captureStream(25)
// to do: enable capture stream of specific sources and outputs
window.vidRecorder = new VidRecorder(this.captureStream)
}
if(detectAudio) this._initAudio()
//if(makeGlobal) {
window.mouse = mouse
window.time = this.time
window['render'] = this.render.bind(this)
// window.bpm = this.bpm
window.bpm = this._setBpm.bind(this)
// }
if(autoLoop) loop(this.tick.bind(this)).start()
}
getScreenImage(callback) {
this.imageCallback = callback
this.saveFrame = true
}
canvasToImage (callback) {
const a = document.createElement('a')
a.style.display = 'none'
let d = new Date()
a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.png`
document.body.appendChild(a)
var self = this
this.canvas.toBlob( (blob) => {
// var url = window.URL.createObjectURL(blob)
if(self.imageCallback){
self.imageCallback(blob)
delete self.imageCallback
} else {
a.href = URL.createObjectURL(blob)
console.log(a.href)
a.click()
}
}, 'image/png')
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(a.href);
}, 300);
}
canvasToWs (callback) {
var base64Str = this.canvas.toDataURL('image/jpeg');
console.log('canvasToWs:' + window.socket);
if (window.socket) window.socket.emit('canvas', base64Str);
}
_initAudio () {
this.audio = new Audio({
numBins: 4
})
if(this.makeGlobal) window.a = this.audio
}
// create main output canvas and add to screen
_initCanvas (canvas) {
if (canvas) {
this.canvas = canvas
this.width = canvas.width
this.height = canvas.height
} else {
this.canvas = document.createElement('canvas')
this.canvas.width = this.width
this.canvas.height = this.height
this.canvas.style.width = '100%'
this.canvas.style.height = '100%'
document.body.appendChild(this.canvas)
}
}
_initRegl () {
this.regl = require('regl')({
canvas: this.canvas,
pixelRatio: 1,
extensions: [
'oes_texture_half_float',
'oes_texture_half_float_linear'
],
optionalExtensions: [
'oes_texture_float',
'oes_texture_float_linear'
]})
// This clears the color buffer to black and the depth buffer to 1
this.regl.clear({
color: [0, 0, 0, 1]
})
this.renderAll = this.regl({
frag: `
precision mediump float;
varying vec2 uv;
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D tex3;
void main () {
vec2 st = vec2(1.0 - uv.x, uv.y);
st*= vec2(2);
vec2 q = floor(st).xy*(vec2(2.0, 1.0));
int quad = int(q.x) + int(q.y);
st.x += step(1., mod(st.y,2.0));
st.y += step(1., mod(st.x,2.0));
st = fract(st);
if(quad==0){
gl_FragColor = texture2D(tex0, st);
} else if(quad==1){
gl_FragColor = texture2D(tex1, st);
} else if (quad==2){
gl_FragColor = texture2D(tex2, st);
} else {
gl_FragColor = texture2D(tex3, st);
}
}
`,
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
}`,
attributes: {
position: [
[-2, 0],
[0, -2],
[2, 2]
]
},
uniforms: {
tex0: this.regl.prop('tex0'),
tex1: this.regl.prop('tex1'),
tex2: this.regl.prop('tex2'),
tex3: this.regl.prop('tex3')
},
count: 3,
depth: { enable: false }
})
this.renderFbo = this.regl({
frag: `
precision mediump float;
varying vec2 uv;
uniform vec2 resolution;
uniform sampler2D tex0;
void main () {
gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y));
}
`,
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
}`,
attributes: {
position: [
[-2, 0],
[0, -2],
[2, 2]
]
},
uniforms: {
tex0: this.regl.prop('tex0'),
resolution: this.regl.prop('resolution')
},
count: 3,
depth: { enable: false }
})
}
_initOutputs (numOutputs) {
const self = this
this.o = (Array(numOutputs)).fill().map((el, index) => {
var o = new Output({regl: this.regl, width: this.width, height: this.height})
o.render()
o.id = index
if (self.makeGlobal) window['o' + index] = o
return o
})
// set default output
this.output = this.o[0]
}
_initSources (numSources) {
this.s = []
for(var i = 0; i < numSources; i++) {
this.createSource()
}
}
_setBpm(bpm) {
this.bpm = bpm
}
createSource () {
let s = new Source({regl: this.regl, pb: this.pb, width: this.width, height: this.height})
if(this.makeGlobal) {
window['s' + this.s.length] = s
}
this.s.push(s)
return s
}
_generateGlslTransforms () {
const self = this
const gen = new GeneratorFactory(this.o[0])
window.generator = gen
Object.keys(gen.functions).forEach((key)=>{
self[key] = gen.functions[key]
if(self.makeGlobal === true) {
window[key] = gen.functions[key]
}
})
}
render (output) {
if (output) {
this.output = output
this.isRenderingAll = false
} else {
this.isRenderingAll = true
}
}
tick (dt, uniforms) {
// if(self.detectAudio === true) self.fft = self.audio.frequencies()
// this.regl.frame(function () {
this.time += dt * 0.001
// console.log(this.time)
// this.regl.clear({
// color: [0, 0, 0, 1]
// })
window.time = this.time
if(this.detectAudio === true) this.audio.tick()
for (let i = 0; i < this.s.length; i++) {
this.s[i].tick(this.time)
}
for (let i = 0; i < this.o.length; i++) {
// console.log('WIDTH', this.canvas.width, this.o[0].getCurrent())
this.o[i].tick({
time: this.time,
mouse: mouse,
bpm: this.bpm,
resolution: [this.canvas.width, this.canvas.height]
})
}
// console.log("looping", self.o[0].fbo)
if (this.isRenderingAll) {
this.renderAll({
tex0: this.o[0].getCurrent(),
tex1: this.o[1].getCurrent(),
tex2: this.o[2].getCurrent(),
tex3: this.o[3].getCurrent(),
resolution: [this.canvas.width, this.canvas.height]
})
} else {
// console.log('out', self.output.id)
this.renderFbo({
tex0: this.output.getCurrent(),
resolution: [this.canvas.width, this.canvas.height]
})
}
if(this.saveFrame === true) {
this.canvasToImage()
this.saveFrame = false
}
if(this.sendFrame === true) {
this.canvasToWs()
//this.sendFrame = false
}
}
}
module.exports = HydraSynth