asigalov61 commited on
Commit
c913064
1 Parent(s): b80c25e

Upload app.js

Browse files
Files changed (1) hide show
  1. javascript/app.js +399 -0
javascript/app.js ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function gradioApp() {
2
+ const elems = document.getElementsByTagName('gradio-app')
3
+ const gradioShadowRoot = elems.length == 0 ? null : elems[0].shadowRoot
4
+ return !!gradioShadowRoot ? gradioShadowRoot : document;
5
+ }
6
+
7
+ uiUpdateCallbacks = []
8
+ msgReceiveCallbacks = []
9
+
10
+ function onUiUpdate(callback){
11
+ uiUpdateCallbacks.push(callback)
12
+ }
13
+
14
+ function onMsgReceive(callback){
15
+ msgReceiveCallbacks.push(callback)
16
+ }
17
+
18
+ function runCallback(x, m){
19
+ try {
20
+ x(m)
21
+ } catch (e) {
22
+ (console.error || console.log).call(console, e.message, e);
23
+ }
24
+ }
25
+ function executeCallbacks(queue, m) {
26
+ queue.forEach(function(x){runCallback(x, m)})
27
+ }
28
+
29
+ document.addEventListener("DOMContentLoaded", function() {
30
+ var mutationObserver = new MutationObserver(function(m){
31
+ executeCallbacks(uiUpdateCallbacks, m);
32
+ });
33
+ mutationObserver.observe( gradioApp(), { childList:true, subtree:true })
34
+ });
35
+
36
+ (()=>{
37
+ let mse_receiver_inited = null
38
+ onUiUpdate(()=>{
39
+ let app = gradioApp()
40
+ let msg_receiver = app.querySelector("#msg_receiver");
41
+ if(!!msg_receiver && mse_receiver_inited !== msg_receiver){
42
+ let mutationObserver = new MutationObserver(function(ms){
43
+ ms.forEach((m)=>{
44
+ m.addedNodes.forEach((node)=>{
45
+ if(node.nodeName === "P"){
46
+ let obj = JSON.parse(node.innerText);
47
+ if(obj instanceof Array){
48
+ obj.forEach((o)=>{executeCallbacks(msgReceiveCallbacks, o);});
49
+ }else{
50
+ executeCallbacks(msgReceiveCallbacks, obj);
51
+ }
52
+ }
53
+ })
54
+ })
55
+ });
56
+ mutationObserver.observe( msg_receiver, {childList:true, subtree:true, characterData:true})
57
+ console.log("receiver init");
58
+ mse_receiver_inited = msg_receiver;
59
+ }
60
+ })
61
+ })()
62
+
63
+ function HSVtoRGB(h, s, v) {
64
+ let r, g, b, i, f, p, q, t;
65
+ i = Math.floor(h * 6);
66
+ f = h * 6 - i;
67
+ p = v * (1 - s);
68
+ q = v * (1 - f * s);
69
+ t = v * (1 - (1 - f) * s);
70
+ switch (i % 6) {
71
+ case 0: r = v; g = t; b = p; break;
72
+ case 1: r = q; g = v; b = p; break;
73
+ case 2: r = p; g = v; b = t; break;
74
+ case 3: r = p; g = q; b = v; break;
75
+ case 4: r = t; g = p; b = v; break;
76
+ case 5: r = v; g = p; b = q; break;
77
+ }
78
+ return {
79
+ r: Math.round(r * 255),
80
+ g: Math.round(g * 255),
81
+ b: Math.round(b * 255)
82
+ };
83
+ }
84
+
85
+ class MidiVisualizer extends HTMLElement{
86
+ constructor() {
87
+ super();
88
+ this.midiEvents = [];
89
+ this.activeNotes = [];
90
+ this.midiTimes = [];
91
+ this.wrapper = null;
92
+ this.svg = null;
93
+ this.timeLine = null;
94
+ this.config = {
95
+ noteHeight : 4,
96
+ beatWidth: 32
97
+ }
98
+ this.tickPreBeat = 500
99
+ this.svgWidth = 0;
100
+ this.playTime = 0
101
+ this.playTimeMs = 0
102
+ this.colorMap = new Map();
103
+ this.playing = false;
104
+ this.timer = null;
105
+ this.init();
106
+ }
107
+
108
+ init(){
109
+ this.innerHTML=''
110
+ const shadow = this.attachShadow({mode: 'open'});
111
+ const style = document.createElement("style");
112
+ const wrapper = document.createElement('div');
113
+ style.textContent = ".note.active {stroke: black;stroke-width: 0.75;stroke-opacity: 0.75;}";
114
+ wrapper.style.overflowX= "scroll"
115
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
116
+ svg.style.height = `${this.config.noteHeight*128}px`;
117
+ svg.style.width = `${this.svgWidth}px`;
118
+ const timeLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
119
+ timeLine.style.stroke = "green"
120
+ timeLine.style.strokeWidth = 2;
121
+ shadow.appendChild(style)
122
+ shadow.appendChild(wrapper);
123
+ wrapper.appendChild(svg);
124
+ svg.appendChild(timeLine)
125
+ this.wrapper = wrapper;
126
+ this.svg = svg;
127
+ this.timeLine= timeLine;
128
+ this.setPlayTime(0);
129
+ }
130
+
131
+ clearMidiEvents(){
132
+ this.pause()
133
+ this.midiEvents = [];
134
+ this.activeNotes = [];
135
+ this.midiTimes = [];
136
+ this.colorMap.clear()
137
+ this.setPlayTime(0);
138
+ this.playTimeMs = 0
139
+ this.svgWidth = 0
140
+ this.svg.innerHTML = ''
141
+ this.svg.style.width = `${this.svgWidth}px`;
142
+ this.svg.appendChild(this.timeLine)
143
+ }
144
+
145
+ appendMidiEvent(midiEvent){
146
+ if(midiEvent instanceof Array && midiEvent.length > 0){
147
+ if(midiEvent[0] === "note"){
148
+ let t = midiEvent[1]
149
+ let duration = midiEvent[2]
150
+ let channel = midiEvent[3]
151
+ let pitch = midiEvent[4]
152
+ let velocity = midiEvent[5]
153
+ let x = (t/this.tickPreBeat)*this.config.beatWidth
154
+ let y = (127 - pitch)*this.config.noteHeight
155
+ let w = (duration/this.tickPreBeat)*this.config.beatWidth
156
+ let h = this.config.noteHeight
157
+ this.svgWidth = Math.ceil(Math.max(x + w, this.svgWidth))
158
+ let color = this.getColor(0, channel)
159
+ let opacity = Math.min(1, velocity/127 + 0.1).toFixed(2)
160
+ let rect = this.drawNote(x,y,w,h, `rgba(${color.r}, ${color.g}, ${color.b}, ${opacity})`)
161
+ midiEvent.push(rect)
162
+ this.setPlayTime(t);
163
+ this.wrapper.scrollTo(this.svgWidth - this.wrapper.offsetWidth, 0)
164
+ }
165
+ this.midiEvents.push(midiEvent);
166
+ this.svg.style.width = `${this.svgWidth}px`;
167
+ }
168
+
169
+ }
170
+
171
+ getColor(track, channel){
172
+ let key = `${track},${channel}`;
173
+ let color = this.colorMap.get(key);
174
+ if(!!color){
175
+ return color;
176
+ }
177
+ color = HSVtoRGB(Math.random(),Math.random()*0.5 + 0.5,1);
178
+ this.colorMap.set(key, color);
179
+ return color;
180
+ }
181
+
182
+ drawNote(x, y, w, h, fill) {
183
+ if (!this.svg) {
184
+ return null;
185
+ }
186
+ const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
187
+ rect.classList.add('note');
188
+ rect.setAttribute('fill', fill);
189
+ // Round values to the nearest integer to avoid partially filled pixels.
190
+ rect.setAttribute('x', `${Math.round(x)}`);
191
+ rect.setAttribute('y', `${Math.round(y)}`);
192
+ rect.setAttribute('width', `${Math.round(w)}`);
193
+ rect.setAttribute('height', `${Math.round(h)}`);
194
+ this.svg.appendChild(rect);
195
+ return rect
196
+ }
197
+
198
+ finishAppendMidiEvent(){
199
+ this.pause()
200
+ let midiEvents = this.midiEvents.sort((a, b)=>a[1]-b[1])
201
+ let tempo = (60 / 120) * 10 ** 3
202
+ let ms = 0
203
+ let lastT = 0
204
+ this.midiTimes.push({ms:ms, t: 0, tempo: tempo})
205
+ midiEvents.forEach((midiEvent)=>{
206
+ let t = midiEvent[1]
207
+ ms += ((t- lastT) / this.tickPreBeat) * tempo
208
+ if(midiEvent[0]==="set_tempo"){
209
+ tempo = midiEvent[2]
210
+ this.midiTimes.push({ms:ms, t: t, tempo: tempo})
211
+ }
212
+ lastT = t
213
+ })
214
+ }
215
+
216
+ setPlayTime(t){
217
+ this.playTime = t
218
+ let x = Math.round((t/this.tickPreBeat)*this.config.beatWidth)
219
+ this.timeLine.setAttribute('x1', `${x}`);
220
+ this.timeLine.setAttribute('y1', '0');
221
+ this.timeLine.setAttribute('x2', `${x}`);
222
+ this.timeLine.setAttribute('y2', `${this.config.noteHeight*128}`);
223
+
224
+ this.wrapper.scrollTo(Math.max(0, x - this.wrapper.offsetWidth/2), 0)
225
+
226
+ if(this.playing){
227
+ let activeNotes = []
228
+ this.removeActiveNotes(this.activeNotes)
229
+ this.midiEvents.forEach((midiEvent)=>{
230
+ if(midiEvent[0] === "note"){
231
+ let time = midiEvent[1]
232
+ let duration = midiEvent[2]
233
+ let note = midiEvent[midiEvent.length - 1]
234
+ if(time <=this.playTime && time+duration>= this.playTime){
235
+ activeNotes.push(note)
236
+ }
237
+ }
238
+ })
239
+ this.addActiveNotes(activeNotes)
240
+ }
241
+ }
242
+
243
+ setPlayTimeMs(ms){
244
+ this.playTimeMs = ms
245
+ let playTime = 0
246
+ for(let i =0;i<this.midiTimes.length;i++){
247
+ let midiTime = this.midiTimes[i]
248
+ if(midiTime.ms>=ms){
249
+ break;
250
+ }
251
+ playTime = midiTime.t + (ms-midiTime.ms) * this.tickPreBeat / midiTime.tempo
252
+ }
253
+ this.setPlayTime(playTime)
254
+ }
255
+
256
+ addActiveNotes(notes){
257
+ notes.forEach((note)=>{
258
+ this.activeNotes.push(note)
259
+ note.classList.add('active');
260
+ });
261
+ }
262
+
263
+ removeActiveNotes(notes){
264
+ notes.forEach((note)=>{
265
+ let idx = this.activeNotes.indexOf(note)
266
+ if(idx>-1)
267
+ this.activeNotes.splice(idx, 1);
268
+ note.classList.remove('active');
269
+ });
270
+ }
271
+
272
+ play(){
273
+ this.playing = true;
274
+ this.timer = setInterval(() => {
275
+ this.setPlayTimeMs(this.playTimeMs + 10)
276
+ }, 10);
277
+ }
278
+
279
+ pause(){
280
+ if(!!this.timer)
281
+ clearInterval(this.timer)
282
+ this.removeActiveNotes(this.activeNotes)
283
+ this.timer = null;
284
+ this.playing = false;
285
+ }
286
+
287
+
288
+ bindAudioPlayer(audio){
289
+ this.pause()
290
+ audio.addEventListener("play", (event)=>{
291
+ this.play()
292
+ })
293
+ audio.addEventListener("pause", (event)=>{
294
+ this.pause()
295
+ })
296
+ audio.addEventListener("timeupdate", (event)=>{
297
+ this.setPlayTimeMs(event.target.currentTime*10**3)
298
+ })
299
+ }
300
+ }
301
+
302
+ customElements.define('midi-visualizer', MidiVisualizer);
303
+
304
+ (()=>{
305
+ let midi_visualizer_container_inited = null
306
+ let midi_audio_inited = null;
307
+ let midi_visualizer = document.createElement('midi-visualizer')
308
+
309
+ if(window.innerWidth < 300){
310
+ midi_visualizer.config.noteHeight = 1
311
+ midi_visualizer.config.beatWidth = 8
312
+ }else if(window.innerWidth < 600){
313
+ midi_visualizer.config.noteHeight = 2
314
+ midi_visualizer.config.beatWidth = 16
315
+ }else if(window.innerWidth < 1280){
316
+ midi_visualizer.config.noteHeight = 4
317
+ midi_visualizer.config.beatWidth = 32
318
+ }else {
319
+ midi_visualizer.config.noteHeight = 4
320
+ midi_visualizer.config.beatWidth = 64
321
+ }
322
+ midi_visualizer.svg.style.height = `${midi_visualizer.config.noteHeight*128}px`; //reload svg height
323
+
324
+ onUiUpdate((m)=>{
325
+ let app = gradioApp()
326
+ let midi_visualizer_container = app.querySelector("#midi_visualizer_container");
327
+ if(!!midi_visualizer_container && midi_visualizer_container_inited!== midi_visualizer_container){
328
+ midi_visualizer_container.appendChild(midi_visualizer)
329
+ midi_visualizer_container_inited = midi_visualizer_container;
330
+ }
331
+ let midi_audio = app.querySelector("#midi_audio > audio");
332
+ if(!!midi_audio && midi_audio_inited!==midi_audio){
333
+ midi_visualizer.bindAudioPlayer(midi_audio)
334
+ midi_audio_inited = midi_audio
335
+ }
336
+ })
337
+
338
+ function createProgressBar(progressbarContainer){
339
+ let parentProgressbar = progressbarContainer.parentNode;
340
+ let divProgress = document.createElement('div');
341
+ divProgress.className='progressDiv';
342
+ let rect = progressbarContainer.getBoundingClientRect();
343
+ divProgress.style.width = rect.width + "px";
344
+ divProgress.style.background = "#b4c0cc";
345
+ divProgress.style.borderRadius = "8px";
346
+ let divInner = document.createElement('div');
347
+ divInner.className='progress';
348
+ divInner.style.color = "white";
349
+ divInner.style.background = "#0060df";
350
+ divInner.style.textAlign = "right";
351
+ divInner.style.fontWeight = "bold";
352
+ divInner.style.borderRadius = "8px";
353
+ divInner.style.height = "20px";
354
+ divInner.style.lineHeight = "20px";
355
+ divInner.style.paddingRight = "8px"
356
+ divInner.style.width = "0%";
357
+ divProgress.appendChild(divInner);
358
+ parentProgressbar.insertBefore(divProgress, progressbarContainer);
359
+ }
360
+
361
+ function removeProgressBar(progressbarContainer){
362
+ let parentProgressbar = progressbarContainer.parentNode;
363
+ let divProgress = parentProgressbar.querySelector(".progressDiv");
364
+ parentProgressbar.removeChild(divProgress);
365
+ }
366
+
367
+ function setProgressBar(progressbarContainer, progress, total){
368
+ let parentProgressbar = progressbarContainer.parentNode;
369
+ let divProgress = parentProgressbar.querySelector(".progressDiv");
370
+ let divInner = parentProgressbar.querySelector(".progress");
371
+ if(total===0)
372
+ total = 1;
373
+ divInner.style.width = `${(progress/total)*100}%`;
374
+ divInner.textContent = `${progress}/${total}`;
375
+ }
376
+
377
+ onMsgReceive((msg)=>{
378
+ switch (msg.name) {
379
+ case "visualizer_clear":
380
+ midi_visualizer.clearMidiEvents();
381
+ createProgressBar(midi_visualizer_container_inited)
382
+ break;
383
+ case "visualizer_append":
384
+ midi_visualizer.appendMidiEvent(msg.data);
385
+ break;
386
+ case "progress":
387
+ let progress = msg.data[0]
388
+ let total = msg.data[1]
389
+ setProgressBar(midi_visualizer_container_inited, progress, total)
390
+ break;
391
+ case "visualizer_end":
392
+ midi_visualizer.finishAppendMidiEvent()
393
+ midi_visualizer.setPlayTime(0);
394
+ removeProgressBar(midi_visualizer_container_inited);
395
+ break;
396
+ default:
397
+ }
398
+ })
399
+ })();