-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
535 lines (456 loc) · 15.7 KB
/
app.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
(function() {
"use strict";
var base = window.base || {};
var app = window.app || {};
var api = window.api || {};
app.server = "https://lainon.life/radio/";
app.thumbmode = false;
// Set up WebAudio, bind events and intervals
app.load = function() {
app.mount = "/mpd-cyberia.ogg";
app.effect = {};
// Parse server from search query if possible
var sserver = document.location.search.substr(1);
if (sserver != "") {
app.server = decodeURIComponent(sserver);
if (window.history && window.history.pushState)
window.history.pushState({}, "",
document.location.origin + document.location.pathname);
else
document.location.search = "";
}
// Initialize WebAudio
app.context = new AudioContext();
app.analyser = app.context.createAnalyser();
app.analyser.fftSize = 1024;
app.analyser.connect(app.context.destination);
app.player = new Audio();
app.player.crossOrigin = "anonymous";
app.source = app.context.createMediaElementSource(app.player);
app.source.connect(app.analyser);
// Update the hash
app.updateHash();
setInterval(app.updateHash, 300);
// Update the metadata and station selection
app.updateData();
setInterval(app.updateData, 5000);
// Load a random effect
api.load();
app.loadEffect();
// Toggle the menu things
$("#meta").on("click", app.toggleMenu);
$("#effects-toggle").on("click", app.toggleEffects);
$("#screen").on("click", function() {
app.toggleMenu(false);
});
// Server edit box
$("#server-edit").on("click", app.toggleServerEdit);
$("#server-edit-box").on("change", app.toggleServerEdit);
if (app.thumbmode) {
var w = 115, h = 65;
clearTimeout(base.resizeid);
base.canvas.width = w;
base.canvas.height = h;
$("#screen").css({width: w, height: h});
if (app.resize)
app.resize(w, h);
}
};
// Set the station mount if the hash was modified
app.updateHash = function() {
var hmount = window.location.hash.substr(1);
if (hmount == "" && app.mount != "")
app.setMount();
else if (app.mount != hmount)
app.setMount(hmount);
$("#server-host").attr("href",
document.location.origin + document.location.pathname
+ "?" + encodeURIComponent(app.server) + "#" + hmount);
};
// Show or hide the menu with the effect and station selectors
app.toggleMenu = function(state) {
if (state != false && state != true) {
state = !$("#menu").is(":visible");
}
if (state) {
$("#menu").focus();
$({
"alpha": 0,
"width": $("#meta-inner").width() + 10
}).animate({
"alpha": 1,
"width": 600
}, {
step: function() {
$("#meta").css({
"border-color": "rgba(255,255,255," + this.alpha + ")",
"width": this.width
});
},
complete: function() {
$("#meta").css({
"border-color": "rgba(255,255,255,1)",
"width": 600
});
$("#menu").slideDown();
}
});
} else if (app.mount != "") {
$("#menu").blur();
$("#menu").slideUp(function() {
$("#meta").animateAuto("width", function() {
$(this).css("width", "auto");
});
$({
"alpha": 1,
}).animate({
"alpha": 0,
}, {
step: function() {
$("#meta").css({
"border-color": "rgba(255,255,255," + this.alpha + ")",
});
},
complete: function() {
$("#meta").css("border-color", "rgba(255,255,255,0)");
}
});
});
}
}
// Show or hide the effect selector which replaces the stations
app.toggleEffects = function(state) {
if (state != false && state != true) {
state = !$("#effects").is(":visible");
}
if (state) {
for (var k in app.effects) {
if (app.effects.hasOwnProperty(k)) {
var v = app.effects[k];
var el = $(".effect.template")
.clone()
.removeClass("template")
.attr("id", k)
.appendTo("#effects")
.on("click", function(e) {
e.preventDefault();
$(".effect.current").removeClass("current");
$(this).addClass("current");
app.loadEffect(app.effects[$(this).attr("id")]);
});
if (v.name == app.effect.name)
el.addClass("current");
el.find(".effect-name").text(v.name);
el.find(".effect-author").text(v.author);
el.find(".effect-thumbnail").attr("src", "thumbnails/" + k + ".png");
}
}
$("#stations").slideUp();
$("#effects").slideDown();
$("#effects-toggle").addClass("current");
} else {
$("#stations").slideDown();
$("#effects").slideUp(function() {
$(".effect:not(.template)").remove();
});
$("#effects-toggle").removeClass("current");
}
}
app.toggleServerEdit = function(state) {
if (state != false && state != true) {
state = !$("#server-edit-box").is(":visible");
}
if (state) {
$("#server-host").hide();
$("#server-edit-box").val(app.server).show();
$("#server-edit").addClass("current");
} else {
var server = $("#server-edit-box").val();
// Make sure stuff is correct
if (server.indexOf("/") == server.length-1)
server = server.substr(0, server.length-1)
if (server.indexOf("https") == 0 && document.location.protocol == "http:")
server = server.replace("https", "http");
if (server.indexOf("http") == -1)
server = "http://" + server;
if (server != app.server) {
// Remove junk
$(".station").fadeOut();
app.server = server;
app.setMount();
}
$("#server-host").show();
$("#server-edit-box").hide();
$("#server-edit").removeClass("current");
}
}
// Load a effect from an object
app.loadEffect = function(obj) {
if (app.effect && app.effect.unload)
app.effect.unload();
if (!obj) {
var n = chooseProperty(app.effects);
obj = app.effects[n];
}
app.effect = obj;
base.time = 0;
if (obj.hasOwnProperty("renderer") && obj.renderer)
api.setRenderer(obj.renderer);
else
api.setRenderer("2d")
// Set up a "GLSL Sandbox"-like pipeline if requested
if (obj.hasOwnProperty("shaders") && (api.renderer == "webgl" || api.renderer == "experimental-webgl")) {
var buffer = api.gl.createBuffer();
api.gl.bindBuffer(api.gl.ARRAY_BUFFER, buffer);
api.gl.bufferData(api.gl.ARRAY_BUFFER, new Float32Array( [ - 1.0, - 1.0, 1.0, - 1.0, - 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, - 1.0, 1.0 ] ), api.gl.STATIC_DRAW);
var fragment = api.gl.createShader(api.gl.FRAGMENT_SHADER);
api.gl.shaderSource(fragment, obj.shaders.fragment ||
"precision mediump float;\n" +
"uniform float time;\n" +
"uniform vec2 resolution;\n" +
"void main(void) {\n" +
" gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n" +
"}");
api.gl.compileShader(fragment);
var vertex = api.gl.createShader(api.gl.VERTEX_SHADER);
api.gl.shaderSource(vertex, obj.shaders.vertex ||
"attribute vec3 position;\n" +
"void main(void) {\n" +
" gl_Position = vec4(position, 1.0);\n" +
"}");
api.gl.compileShader(vertex);
api.gl.program = api.gl.createProgram();
api.gl.attachShader(api.gl.program, fragment);
api.gl.attachShader(api.gl.program, vertex);
api.gl.deleteShader(fragment);
api.gl.deleteShader(vertex);
api.gl.linkProgram(api.gl.program);
api.gl.useProgram(api.gl.program);
api.gl.program.positionLocation = api.gl.getAttribLocation(api.gl.program, "position");
api.gl.enableVertexAttribArray(api.gl.program.positionLocation);
api.gl.program.timeLocation = api.gl.getUniformLocation(api.gl.program, "time");
api.gl.program.mouseLocation = api.gl.getUniformLocation(api.gl.program, "mouse");
api.gl.program.resolutionLocation = api.gl.getUniformLocation(api.gl.program, "resolution");
if (!obj.draw) {
obj.draw = function(w, h, s) {
api.gl.uniform2f(api.gl.program.resolutionLocation, w, h);
api.gl.vertexAttribPointer(api.gl.program.positionLocation, 2, api.gl.FLOAT, false, 0, 0);
api.gl.clear(api.gl.COLOR_BUFFER_BIT | api.gl.DEPTH_BUFFER_BIT);
api.gl.drawArrays(api.gl.TRIANGLES, 0, 6);
}
}
if (!obj.update) {
obj.update = function(dt, time) {
api.gl.uniform1f(api.gl.program.timeLocation, time);
api.gl.uniform2f(api.gl.program.mouseLocation,
base.mouse.x / base.canvas.width,
-base.mouse.y / base.canvas.height);
}
}
}
if (obj.hasOwnProperty("load") && obj.load)
obj.load();
};
// Load a effect from a JSON string
app.loadEffectFromJSON = function(json) {
var obj;
try {
obj = JSON.parse(json, function (k, v) {
if (v
&& typeof v === "string"
&& v.substr(0,8) == "function") {
var startBody = v.indexOf('{') + 1;
var endBody = v.lastIndexOf('}');
var startArgs = v.indexOf('(') + 1;
var endArgs = v.indexOf(')');
return new Function(v.substring(startArgs, endArgs),
v.substring(startBody, endBody));
}
return v;
});
} catch (e) {
console.error("Error while parsing effect JSON", e);
return false;
}
app.loadEffect(new app.effect(obj));
return true;
};
// Load a effect from a Icecast description string
app.loadEffectFromDescription = function(desc, failcb) {
var m = desc.match(/icedrop:(.+|\n+)/m);
if (!m) {
failcb();
return;
}
m = m[1];
if (m.match(/^\w+$/)) {
// Load effect by name
console.log("Station requested loading effect by name:", m);
if (app.effects.hasOwnProperty(m))
app.loadEffect(app.effects[m]);
else
failcb();
} else if (m.match(/^(?:https?:\/\/)?(?:[\w]+\.)(?:\.?[\w]{2,})+$/)) {
// Load effect from URL
console.log("Station requested loading effect from URL:", m);
$.get(m, function(data) {
if (!app.loadEffectFromJSON(data))
failcb();
}, failcb);
} else {
// Load effect from direct JSON
console.log("Station requested loading effect from JSON:", m);
if (!app.loadEffectFromJSON(m))
failcb();
}
};
// Set the current station by mount point
app.setMount = function(mount) {
if (mount) {
if (app.mount != mount) {
console.log("Switched station mount to", mount);
app.mount = mount;
// Load the new stream
app.player.setAttribute("src", app.server + "/" + mount);
app.player.load();
app.player.play();
// Update the hash
var hmount = window.location.hash.substr(1);
if (hmount != mount)
window.location.hash = "#" + mount;
$("#station.current").removeClass("current");
app.toggleMenu(false);
// Hide false meta stuff
$("#meta-listeners").text("");
$("#meta-title").text("");
$("#meta-artist").text("");
// Try to load a effect if existant
app.updateData(function(station, data) {
if (station && station.hasOwnProperty("server_description")) {
var success = app.loadEffectFromDescription(station.server_description,
function() {
// Error or not even requested, load random effect instead
app.loadEffect(app.effects["rose"]);
});
}
});
}
} else {
if (app.mount != "") {
console.log("Switched station mount to none");
app.mount = "";
app.player.pause();
// Update the hash
var hmount = window.location.hash.substr(1);
if (hmount != "")
window.location.hash = "";
// Hide false meta stuff
$("#meta-listeners").text("");
$("#meta-title").text("");
$("#meta-artist").text("");
app.toggleMenu(true);
app.updateData();
}
}
};
// Request data from the Icecast API and update everything that uses it
// The current station and the full data will be passed to the callback
app.updateData = function(cb) {
$.getJSON(app.server + "/status-json.xsl", function(data) {
var current, ids = [];
$("#server-host").text(data.icestats.host);;
$.each(data.icestats.source, function(i, v) {
var mount = v.listenurl.match(/\/([^\/]+)$/)[1];
var id = mount.replace(/[^\w]/g, "");
ids.push(id);
// Find existing station element or create it
var el = $(".station#" + id);
if (el.length == 0) {
// Clone the template element
el = $(".station.template")
.clone()
.removeClass("template")
.attr("id", id)
.appendTo("#stations").hide().fadeIn()
.on("click", function(e) {
$(".station.current").removeClass("current");
$(this).addClass("current");
});
}
// Update station informations
el.attr("href", "#" + mount);
el.find(".station-name").text(v.server_name || ("/" + mount));
el.find(".station-listeners").text(v.listeners);
el.find(".station-title").text(v.title || "Unknown");
el.find(".station-artist").text(v.artist || "Unknown");
// Found the station that is currently being listened to
if (mount == app.mount) {
current = v;
el.addClass("current");
}
});
// Clean up stations that have gone offline since the last update
$(".station").each(function(i, v) {
var el = $(v);
var id = el.attr("id");
if (id && ids.indexOf(id) == -1) {
el.fadeOut(function() {
el.remove();
});
}
});
if (!current && app.mount != "") {
// Station probably disconnected
console.log("Current station disconnected");
$(".station.current").fadeOut(function() {
$(this).remove();
app.updateData();
});
app.setMount();
} else if (current) {
// Update current station informations
var title = current.title || "Unknown";
var artist = current.artist || "Unknown";
$("#meta-listeners").text(current.listeners);
$("#meta-title").text(title);
$("#meta-artist").text(artist);
document.title = artist + " - " + title;
}
if (cb)
cb(current, data.icestats);
});
};
// Viewport has been resized
app.resize = function(w, h, ow, oh) {
var r = true;
if (app.effect && app.effect.resize) {
r = app.effect.resize(w, h, ow, oh);
}
if (r == true || typeof r == "undefined") {
api.canvas.width = w;
api.canvas.height = h;
api.ocanvas.width = w;
api.ocanvas.height = h;
if (api.gl && api.ogl) {
api.gl.viewport(0, 0, w, h);
api.ogl.viewport(0, 0, w, h);
}
}
};
// Get the current frequency- and time-domain data
app.update = function(dt, time) {
app.analyser.getByteFrequencyData(api.freqdata);
app.analyser.getByteTimeDomainData(api.timedata);
if (app.effect.update)
app.effect.update(dt, time);
};
// Draw the visualization
app.draw = function() {
var w = base.canvas.width, h = base.canvas.height;
var s = Math.min(w, h);
if (app.effect.draw)
app.effect.draw(w, h, s);
base.ctx.drawImage(api.canvas, 0, 0, w, h);
};
window.app = app;
})();