-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathReVidiaGUI.py
executable file
·2222 lines (1815 loc) · 81.2 KB
/
ReVidiaGUI.py
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!venv/bin/python
# -*- coding: utf-8 -*-
import ReverseFFT
import ReVidia
import sys
import time
import random
import subprocess
import threading as th
import multiprocessing as mp
from PyQt5.QtCore import Qt, QPoint, QRect, pyqtSignal
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# A hollow window to contain ReVidiaMain window to incorporate docking
class MetaWindow(QMainWindow):
def __init__(self, main):
super(MetaWindow, self).__init__()
self.main = main
self.setWindowIcon(QIcon('docs/REV.png'))
self.setWindowTitle('ReVidia')
self.setMinimumSize(200, 150)
self.setAttribute(Qt.WA_TranslucentBackground, True) # Initial background is transparent
self.setCentralWidget(self.main)
# Forwarding Events to ReVidiaMain
def keyPressEvent(self, event):
ReVidiaMain.keyPressEvent(self.main, event)
def closeEvent(self, event):
self.main.close()
# Because using self.update() or self.repaint() in the main loop was too much to ask for... ¯\_(ツ)_/¯
class ForcePaint(QWidget):
forcePaint = pyqtSignal()
# Create the self object and main window
class ReVidiaMain(QMainWindow):
def __init__(self):
super(ReVidiaMain, self).__init__()
self.meta = MetaWindow(self)
self.call = ForcePaint()
self.call.forcePaint.connect(self.update)
# Sets up window to be in the middle and to be half screen height
screen = QApplication.desktop().screenNumber(
QApplication.desktop().cursor().pos())
screenSize = QApplication.desktop().screenGeometry(screen)
self.width = screenSize.width() // 2
self.height = screenSize.height() // 2
self.left = screenSize.center().x() - self.width // 2
self.top = screenSize.center().y() - self.height // 2
# Default variables
# [startPoint, startCurve, midPoint, midPointPos, endCurve, endPoint]
self.pointsList = [0, 1, 1000, 0.66, 1, 12000]
self.split = 0
self.curvy = 0
self.interp = 8
self.audioBuffer = 4096
self.backgroundColor = QColor(50, 50, 50, 255) # R, G, B, Alpha 0-255
self.mainColor = QColor(255, 255, 255, 255)
self.outlineColor = QColor(0, 0, 0)
self.lumen = 0
self.stars = {}
self.gradient = 0
self.checkRainbow = 0
self.plotWidth = 14
self.gapWidth = 6
self.outlineSize = 0
self.dataCap = 0
self.wholeWidth = self.plotWidth + self.gapWidth
self.outlineOnly = 0
self.cutout = 0
self.checkFreq = 0
self.checkNotes = 0
self.checkDeadline = 0
self.checkPlotNum = 0
self.checkLatency = 0
self.checkDB = 0
self.mainMode = 'Bars'
self.frameRate = 150
self.initUI()
# Setup main window
def initUI(self, reload=False):
self.meta.setGeometry(self.left, self.top, self.width, self.height)
self.setTextPalette()
if not reload:
self.getDevice(True) # Get Device before starting
# Setup menu bar
mainBar = QMenuBar()
mainMenu = mainBar.addMenu('Main')
mainMenu.setToolTipsVisible(True)
designMenu = mainBar.addMenu('Design')
designMenu.setToolTipsVisible(True)
statsMenu = mainBar.addMenu('Stats')
statsMenu.setToolTipsVisible(True)
profilesMenu = QMenu('Profiles', self)
profilesMenu.setToolTip('Save and Load Profiles')
save = QAction('Save', self)
save.triggered.connect(lambda triggered, request='save': self.setProfile(request))
load = QAction('Load', self)
load.triggered.connect(lambda triggered, request='load': self.setProfile(request))
delete = QAction('Delete', self)
delete.triggered.connect(lambda triggered, request='delete': self.setProfile(request))
profilesMenu.addActions((save, load, delete))
deviceDialog = QAction('Device', self)
deviceDialog.setToolTip('Select Audio Device')
deviceDialog.triggered.connect(self.getDevice)
FFTAudDock = QAction('Reverse FFT', self)
FFTAudDock.setToolTip('Listen to the Sound of the Visualizer')
FFTAudDock.triggered.connect(self.getFFTAudDock)
scaleDock = QAction('Freq Scale', self)
scaleDock.setToolTip('Modify the Frequency Scale')
scaleDock.triggered.connect(self.getScaleDock)
splitCheck = QAction('Split Audio', self)
splitCheck.setCheckable(True)
splitCheck.setToolTip('Toggle to Split Audio Channels')
splitCheck.toggled.connect(self.setSplit)
splitCheck.setChecked(self.split)
curvyMenu = QMenu('Curviness', self)
curvyMenu.setToolTip('Set How Much the Plots Curves')
curvySettings = ['No Curves', 'Sharp', 'Narrow', 'Loose', 'Flat']
curveList = [0, (0.05, 3), (0.15, 3), (0.30, 3), (1, 3)] # [0, (5,3), (11,3), (23,3), (43,3)]
self.curvyDict = {}
for f in range(5):
curve = curveList[f]
self.curvyDict[str(curve)] = QAction(curvySettings[f], self)
self.curvyDict[str(curve)].setCheckable(True)
self.curvyDict[str(curve)].triggered.connect(lambda checked, index=curve: self.setCurve(index))
curvyMenu.addAction(self.curvyDict[str(curve)])
self.curvyDict[str(self.curvy)].setChecked(True)
self.curvyDict[str(self.curvy)].trigger()
interpMenu = QMenu('Interpolation', self)
interpMenu.setToolTip('Set Interp Amount (Noise)')
interpSettings = ['No Interpolation', 'Low [4x]', 'Mid [8x]', 'High [16x]', 'Ultra [32x]']
interpList = [0, 4, 8, 16, 32]
interp = 0
self.interpDict = {}
for f in range(5):
interp = interpList[f]
self.interpDict[str(interp)] = QAction(interpSettings[f], self)
self.interpDict[str(interp)].setCheckable(True)
self.interpDict[str(interp)].triggered.connect(lambda checked, index=interp: self.setInterp(index))
interpMenu.addAction(self.interpDict[str(interp)])
self.interpDict[str(self.interp)].setChecked(True)
self.interpDict[str(self.interp)].trigger()
bufferMenu = QMenu('Audio Buffer', self)
bufferMenu.setToolTip('Set the Audio Buffer Size')
audioRate = 1024
self.audioBufferDict = {}
for f in range(5):
self.audioBufferDict[str(audioRate)] = QAction(str(audioRate), self)
self.audioBufferDict[str(audioRate)].setCheckable(True)
self.audioBufferDict[str(audioRate)].triggered.connect(lambda checked, index=audioRate: self.setAudioBuffer(index))
bufferMenu.addAction(self.audioBufferDict[str(audioRate)])
audioRate *= 2
self.audioBufferDict[str(self.audioBuffer)].setChecked(True)
self.audioBufferDict[str(self.audioBuffer)].trigger()
colorMenu = QMenu('Color', self)
colorMenu.setToolTip('Select Colors and Transparency')
mainColorDialog = QAction('Main Color', self)
mainColorDialog.triggered.connect(self.setMainColor)
backColorDialog = QAction('Background Color', self)
backColorDialog.triggered.connect(self.setBackgroundColor)
outColorDialog = QAction('Outline Color', self)
outColorDialog.triggered.connect(self.setOutlineColor)
rainbowCheck = QAction('Rainbow', self)
rainbowCheck.setCheckable(True)
rainbowCheck.triggered.connect(self.setRainbow)
rainbowCheck.setChecked(self.checkRainbow)
colorMenu.addAction(mainColorDialog)
colorMenu.addAction(backColorDialog)
colorMenu.addAction(outColorDialog)
colorMenu.addAction(rainbowCheck)
lumenMenu = QMenu('Illuminate', self)
lumenMenu.setToolTip('Change the Bars Alpha Scale')
lumenSettings = ['None', '1/4', '1/2', '3/4', 'Whole']
lumenList = [0, 25, 50, 75, 100]
self.lumenDict = {}
for f in range(5):
lumen = lumenList[f]
self.lumenDict[str(lumen)] = QAction(lumenSettings[f], self)
self.lumenDict[str(lumen)].setCheckable(True)
self.lumenDict[str(lumen)].triggered.connect(lambda checked, index=lumen: self.setLumen(index))
lumenMenu.addAction(self.lumenDict[str(lumen)])
self.lumenDict[str(self.lumen)].setChecked(True)
self.lumenDict[str(self.lumen)].trigger()
starsDock = QAction('Stars', self)
starsDock.setToolTip('Animate Background with Stars')
starsDock.triggered.connect(self.getStarsDock)
gradDock = QAction('Gradient', self)
gradDock.setToolTip('Create a Gradient')
gradDock.triggered.connect(self.getGradDock)
sizesCheck = QAction('Dimensions', self)
sizesCheck.setToolTip('Change the Bars Dimensions')
sizesCheck.triggered.connect(self.getDimenDock)
self.autoLevel = QAction('Auto Level', self)
self.autoLevel.setCheckable(True)
self.autoLevel.setToolTip('Auto Scale the Height to Fit the Data')
self.autoLevel.triggered.connect(self.setAutoLevel)
if not self.dataCap:
self.autoLevel.setChecked(True)
outlineCheck = QAction('Outline Only', self)
outlineCheck.setCheckable(True)
outlineCheck.setToolTip('Draw Only the Outline With Main Color')
outlineCheck.toggled.connect(self.setOutlineOnly)
outlineCheck.setChecked(self.outlineOnly)
cutoutCheck = QAction('Cutout', self)
cutoutCheck.setCheckable(True)
cutoutCheck.setToolTip('Toggle to Cutout Background')
cutoutCheck.toggled.connect(self.setCutout)
cutoutCheck.setChecked(self.cutout)
deadlineCheck = QAction('Deadline', self)
deadlineCheck.setCheckable(True)
deadlineCheck.setToolTip('Display FPS Deadline Ratio')
deadlineCheck.toggled.connect(self.showDeadline)
deadlineCheck.setChecked(self.checkDeadline)
plotNumCheck = QAction('Plots', self)
plotNumCheck.setCheckable(True)
plotNumCheck.setToolTip('Display Amount of Plots Visible')
plotNumCheck.toggled.connect(self.showPlotNum)
plotNumCheck.setChecked(self.checkPlotNum)
latencyCheck = QAction('Latency', self)
latencyCheck.setCheckable(True)
latencyCheck.setToolTip('Display Latency Between Display and Audio')
latencyCheck.toggled.connect(self.showLatency)
latencyCheck.setChecked(self.checkLatency)
dbBarCheck = QAction('dB Bar', self)
dbBarCheck.setCheckable(True)
dbBarCheck.setToolTip('Display dB Bar Indicating Volume')
dbBarCheck.toggled.connect(self.showDB)
dbBarCheck.setChecked(self.checkDB)
self.freqsCheck = QAction('Frequencies', self)
self.freqsCheck.setCheckable(True)
self.freqsCheck.setToolTip('Show Each Plot\'s Frequency')
self.freqsCheck.toggled.connect(self.showFreq)
self.freqsCheck.setChecked(self.checkFreq)
self.notesCheck = QAction('Notes', self)
self.notesCheck.setCheckable(True)
self.notesCheck.setToolTip('Frequencies as Notes')
self.notesCheck.toggled.connect(self.showNotes)
self.notesCheck.setChecked(self.checkNotes)
self.mainModeCheck = QPushButton(self.mainMode, self)
self.mainModeCheck.pressed.connect(self.setMainMode)
fpsSpinBox = QSpinBox()
fpsSpinBox.setRange(1, 999)
fpsSpinBox.setSuffix(' FPS')
fpsSpinBox.valueChanged.connect(self.setFrameRate)
fpsSpinBox.setValue(self.frameRate)
fpsSpinBox.setKeyboardTracking(False)
fpsSpinBox.setFocusPolicy(Qt.ClickFocus)
mainMenu.addMenu(profilesMenu)
mainMenu.addAction(deviceDialog)
mainMenu.addAction(FFTAudDock)
mainMenu.addAction(scaleDock)
mainMenu.addAction(splitCheck)
mainMenu.addMenu(curvyMenu)
mainMenu.addMenu(interpMenu)
mainMenu.addMenu(bufferMenu)
designMenu.addMenu(colorMenu)
designMenu.addMenu(lumenMenu)
designMenu.addAction(starsDock)
designMenu.addAction(gradDock)
designMenu.addAction(sizesCheck)
designMenu.addAction(self.autoLevel)
designMenu.addAction(outlineCheck)
designMenu.addAction(cutoutCheck)
statsMenu.addAction(deadlineCheck)
statsMenu.addAction(plotNumCheck)
statsMenu.addAction(latencyCheck)
statsMenu.addAction(dbBarCheck)
statsMenu.addAction(self.freqsCheck)
statsMenu.addAction(self.notesCheck)
self.menuWidget = QWidget(self)
menu = QHBoxLayout(self.menuWidget)
menu.addWidget(mainBar)
menu.addWidget(self.mainModeCheck)
menu.addWidget(fpsSpinBox)
menu.addStretch(10)
self.setMenuWidget(self.menuWidget)
self.meta.show()
self.starterVars()
if not reload:
self.updateStack()
self.startProcesses()
def starterVars(self):
# Define placeholder stater variables
self.plotValues = [0]
self.plotSplitValues = [0]
self.delay = 0
self.frames = 0
self.paintBusy = 0
self.paintTime = 0
self.paintDelay = (1 / self.frameRate)
self.reverseFFT = 0
self.barsShape = [QRect()]
self.barsOutlineShape = [QRect()]
self.smoothShape = QPolygon()
self.starsList = []
self.loopTime = 0
def startProcesses(self):
self.blockLock = th.Lock()
self.syncLock = mp.Lock()
# Queues to change settings in process
self.dataQ = mp.Queue()
self.proQ = mp.Queue()
self.mainQ = mp.Queue()
# Values to carry timings
dataTime = mp.Value('d')
self.proTime = mp.Value('d')
self.audioPeak = mp.Value('i', 0)
# Arrays to transfer data between processes very fast
self.dataArray = mp.Array('i', 16384)
dataArray2 = mp.Array('i', 16384)
self.proArray = mp.Array('i', 8192)
self.proArray2 = mp.Array('i', 8192)
# Create separate process for audio data collection
self.T1 = mp.Process(target=ReVidia.collectData, args=(
dataTime, self.dataArray, dataArray2, self.dataQ, self.ID, self.audioBuffer, self.split))
# Create separate process for audio data processing
self.P1 = mp.Process(target=ReVidia.processData, args=(
self.syncLock, dataTime, self.proTime, self.audioPeak, self.dataArray, dataArray2, self.proArray, self.proArray2, self.proQ, self.dataQ,
self.frameRate, self.audioBuffer, self.plotsList, self.split, self.curvyValue, self.interp))
# Separate main thread from event loop
self.mainThread = th.Thread(target=self.mainLoop)
self.T1.daemon = True
self.P1.daemon = True
self.T1.start()
self.P1.start()
self.mainThread.start()
def mainLoop(self):
timer = time.time()
while True:
# Gets the real frametime for time sensitive objects
self.loopTime = time.time() - timer
timer = time.time()
# Gets final results from processing
self.delay = self.proTime.value
plotsData = self.proArray[:self.plotsAmt]
splitPlotData = self.proArray2[:self.plotsAmt]
# Resize Data with user's defined height or the data's height
self.plotValues = ReVidia.rescaleData(plotsData, self.dataCap, self.size().height())
self.plotSplitValues = ReVidia.rescaleData(splitPlotData, self.dataCap, self.size().height())
# Create the shapes for painter to draw
if self.mainMode == 'Bars':
self.barsShape = self.createBars()
if self.outlineSize > 0:
self.barsOutlineShape = self.createBarsOutline()
else:
self.smoothShape = self.createSmooth()
if self.stars:
self.createStars()
if not self.P1.is_alive():
print('RIP Audio Processor, shutting down.')
self.close()
if not self.T1.is_alive():
print('RIP Audio Data Collector, shutting down.')
self.close()
try: # Avoid Crash
self.syncLock.release() # Start processing next frame
except: pass
if not self.paintBusy: # Rare fail safe
# self.update()
self.call.forcePaint.emit()
self.updateMiscObjects()
blockTime = time.time()
self.blockLock.acquire(timeout=1)
if (time.time() - blockTime) >= 1:
print('QT refusing to paint, attempting revive...')
self.repaint() # Revives painter
if self.mainQ.qsize() > 0:
break
def updateMiscObjects(self):
if self.reverseFFT:
if not hasattr(self, 'waveFile'):
self.waveFile = ReverseFFT.createFile(self.sampleRate)
self.oldVolList = []
self.oldTimes = []
# Insert a Tiny bit of random to prevent overlap in freq's
self.waveFreqList = list(map(lambda freq: freq + random.uniform(-0.1, 0.1), self.freqList[:-1]))
self.oldVolList, self.oldTimes = ReverseFFT.start(self.waveFile, self.sampleRate, self.plotValues, self.loopTime,
self.size().height(), self.oldVolList, self.oldTimes, self.waveFreqList)
else:
if hasattr(self, 'waveFile'):
self.waveFile.close()
del self.waveFile
if self.checkDeadline:
block = self.frameRate // 10
if block < 1: block = 1
if self.frames % block == 0:
self.latePercent = round(((1 / self.frameRate) / self.loopTime) * 100, 2)
# print(1 / self.loopTime) testing frame times
# Update height slider
if hasattr(self, 'dimenDock'):
if self.dimenDock.heightSlider.isSliderDown():
self.dimenDock.setDataCap()
else:
self.dimenDock.heightSlider.setValue(0)
if self.checkRainbow:
self.setRainbow(1)
# Convenience function to update all at once in the right order
def updateStack(self):
self.updatePlotsAmt()
self.updatePlots()
self.updateFreqList()
def updatePlots(self):
plot = self.sampleRate / self.audioBuffer
startPoint = self.pointsList[0] / plot
startCurve = startPoint * self.pointsList[1]
midPoint = self.pointsList[2] / plot
midPointPos = int(round(self.plotsAmt * self.pointsList[3]))
endCurve = midPoint * self.pointsList[4]
endPoint = self.pointsList[5] / plot
startScale = ReVidia.quadBezier(startPoint, midPoint, startCurve, midPointPos)
endScale = ReVidia.quadBezier(midPoint, endPoint, endCurve, self.plotsAmt - midPointPos, True)
plots = startScale + endScale
self.plotsList = list(map(int, ReVidia.dataPlotter(plots, 1, self.audioBuffer // 2)))
if hasattr(self, 'proQ'):
self.proQ.put(['plots', self.plotsList])
def updatePlotsAmt(self):
self.plotsAmt = self.size().width() // self.wholeWidth
if self.plotsAmt > self.audioBuffer: # Max of buffer to avoid crash
self.plotsAmt = self.audioBuffer
if self.plotsAmt < 2: self.plotsAmt = 2 # Min of 2 point to avoid crash
if self.curvy:
self.setCurve(self.curvy)
def updateFreqList(self):
# Assigns frequencies locations based on plots
freq = self.sampleRate / self.audioBuffer
self.freqList = list(map(lambda plot: plot * freq, self.plotsList))
def setTextPalette(self):
if not hasattr(self, 'textPalette'):
self.textPalette = QPalette()
# Sets the text color to better see it against background
if self.backgroundColor.value() <= 128:
self.textPalette.setColor(QPalette.WindowText, QColor(255, 255, 255))
else:
self.textPalette.setColor(QPalette.WindowText, QColor(0, 0, 0))
self.setPalette(self.textPalette)
def createBars(self):
spacing = (self.gapWidth // 2)
xPoints = [((x * self.wholeWidth) + spacing) for x in range(len(self.plotValues))]
floor = self.size().height()
if self.split:
floor //= 2
yPoints = list(map(lambda y: int(floor - (y / 2)), self.plotValues))
bars = list(map(lambda x, y, height, splitH: QRect(x, y, self.plotWidth, int((height + splitH) / 2)),
xPoints, yPoints, self.plotValues, self.plotSplitValues))
else:
yPoints = list(map(lambda y: int(floor - y), self.plotValues))
bars = list(map(lambda x, y, height: QRect(x, y, self.plotWidth, height), xPoints, yPoints, self.plotValues))
return bars
# Hack way of making outline without the (Slow QPen)
def createBarsOutline(self):
outlineRects = []
outlineSize = self.outlineSize
if outlineSize > self.plotWidth // 2: outlineSize = self.plotWidth // 2
for rect in self.barsShape:
outlineRects.append(QRect(rect.x(), rect.y(), outlineSize, rect.height())) # Left
outlineRects.append(QRect(rect.x(), rect.y(), rect.width(), outlineSize)) # Top
outlineRects.append(QRect(rect.x() + rect.width(), rect.y(), -outlineSize, rect.height())) # Right
outlineRects.append(QRect(rect.x(), rect.y() + rect.height(), rect.width(), -outlineSize)) # Bottom
return outlineRects
def createSmooth(self):
# Plots Setup
spacing = self.wholeWidth // 2
xPoints = [((x * self.wholeWidth) + spacing) for x in range(len(self.plotValues))]
height = self.size().height()
start = -self.outlineSize
end = self.outlineSize + self.size().width()
if self.split:
height //= 2
yPoints = list(map(lambda y: int(height - (y / 2)), self.plotValues))
ySplitPoints = list(map(lambda y: int(height + (y / 2)), self.plotSplitValues))
floor = height
else:
yPoints = list(map(lambda y: int(height - y), self.plotValues))
floor = height + self.outlineSize
# Plot out points
allPoints = [start, floor, start, yPoints[0]]
[allPoints.extend(i) for i in zip(xPoints, yPoints)]
allPoints.extend([end, yPoints[-1], end, floor])
if self.split: # Clockwise Loop to start
allPoints.extend([end, ySplitPoints[-1]])
[allPoints.extend(i) for i in zip(reversed(xPoints), reversed(ySplitPoints))]
allPoints.extend([start, ySplitPoints[0], start, floor])
shape = QPolygon(allPoints)
return shape
def createStars(self):
# Parse star size range
starSizes = self.stars['SizeRange']
starSizes = [min(starSizes), max(starSizes) + 1]
# Starting off with random spread of stars
while len(self.starsList) < self.stars['Amount']:
self.starsList.append((random.randrange(0, self.size().width()),
random.randrange(0, self.size().height()),
random.randrange(starSizes[0], starSizes[1])))
while len(self.starsList) > self.stars['Amount']:
self.starsList.remove(random.choice(self.starsList))
# Parse star plot range
plotRange = self.stars['PlotRange']
plotMod = self.plotValues[min(plotRange) - 1:max(plotRange)]
# Main modifier that effects speed and twinkle based on user defined plot range avg.
modifier = (sum(plotMod) / len(plotMod)) / self.size().height()
# Calculate speed and angle of stars
import math
angleX = -math.sin(self.stars['Angle'] * (math.pi / 180))
angleY = math.cos(self.stars['Angle'] * (math.pi / 180))
speed = self.stars['MinSpeed']
speed += modifier * (self.stars['ModSpeed'] - self.stars['MinSpeed'])
# Normalize speed with frametime
speed *= self.loopTime
# Apply speed and angle to stars while removing out of bounds stars
newStarList = []
for star in self.starsList:
if (star[0] - star[2] > self.size().width()) or (star[0] + star[2] < 0):
pass
elif (star[1] - star[2] > self.size().height()) or (star[1] + star[2] < 0):
pass
else:
starXPos = star[0] + (speed * angleX)
StarYPos = star[1] + (speed * angleY)
newStarList.append((starXPos, StarYPos, star[2]))
self.starsList = newStarList
# Weighted random for stars start side
xSideSizeRatio = (self.size().width() / self.size().height())
ySideSizeRatio = (self.size().height() / self.size().width())
xWeight = int((abs(angleX) + (ySideSizeRatio * abs(angleX))) * 10)
yWeight = int((abs(angleY) + (xSideSizeRatio * abs(angleY))) * 10)
wieghtedSides = []
for w in range(xWeight):
wieghtedSides.append(0)
for w in range(yWeight):
wieghtedSides.append(1)
# Create new stars on a edge
while len(self.starsList) < self.stars['Amount']:
side = random.choice(wieghtedSides)
starSize = random.randrange(starSizes[0], starSizes[1])
if side == 0:
if angleX > 0:
starXPos = 0 - starSize
else:
starXPos = self.size().width() + starSize
starYPos = random.randrange(0, self.size().height())
else:
if angleY > 0:
starYPos = 0 - starSize
else:
starYPos = self.size().height() + starSize
starXPos = random.randrange(0, self.size().width())
self.starsList.append((starXPos, starYPos, starSize))
def paintEvent(self, event):
if hasattr(self, 'blockLock'): # Avoid painting too early
self.paintBusy = 1
painter = QPainter(self)
painter.setPen(QPen(Qt.NoPen)) # Removes pen
self.paintBackground(event, painter)
if self.stars:
self.paintStars(event, painter)
if self.mainMode == 'Bars' and not self.cutout:
self.paintBars(event, painter)
elif not self.cutout:
self.paintSmooth(event, painter)
if self.checkFreq or self.checkNotes:
self.paintFreq(event, painter)
if self.checkDB:
self.paintDB(event, painter)
if self.checkDeadline or self.checkPlotNum or self.checkLatency:
self.paintStats(event, painter)
painter.end()
self.paintBusy = 0
# Frame Counter to scale timings
if self.frames < 10000:
self.frames += 1
else:
self.frames = 0
if self.checkLatency:
block = self.frameRate // 10
if block < 1: block = 1
if self.frames % block == 0:
self.latency = round(((time.time() - self.delay) * 1000))
# Paint's Frame Time Delay Scalar
delay = self.paintDelay - (time.time() - self.paintTime)
if delay > 0:
time.sleep(delay)
# Auto correcting frame pacer to account for variance in os time
framePace = time.time() - self.paintTime
if framePace > (1 / self.frameRate):
self.paintDelay -= (0.001 / self.frameRate)
else:
self.paintDelay += (0.001 / self.frameRate)
self.paintTime = time.time()
try: # Avoid Crash
if self.blockLock.locked:
self.blockLock.release()
except: pass
def paintBackground(self, event, painter):
painter.setBrush(self.backgroundColor)
background = QRect(0, 0, self.size().width(), self.size().height())
if not self.cutout: # Normal background
painter.drawRect(background)
else: # Cutout background
back = QPolygon(background)
if self.mainMode == 'Smooth':
cutout = back.subtracted(self.smoothShape)
painter.drawPolygon(cutout)
else:
# barsPoints = []
# for rect in self.barsShape:
# barsPoints.extend([rect.bottomLeft(), rect.topLeft(), rect.topRight(), rect.bottomRight()])
# barsPoints.extend([background.bottomRight(), background.topRight(), background.topLeft(), background.bottomLeft()])
# cutout = QPolygon(barsPoints)
# This is still the fastest way to draw for bars
xSize = self.plotWidth
xPos = (self.gapWidth // 2)
yPos = 0
for y in range(len(self.plotValues)):
ySizeV = self.plotValues[y]
ySize = self.size().height() - ySizeV
painter.drawRect(xPos - self.gapWidth, yPos, self.gapWidth, self.size().height()) # Gap bar
if self.split:
ySplitV = self.plotSplitValues[y]
ySize = (self.size().height() // 2) - ySizeV
painter.drawRect(xPos, yPos, xSize, ySize) # Top background
ySize = (self.size().height() // 2) - ySplitV
painter.drawRect(xPos, self.size().height(), xSize, -ySize) # bottom background
else:
painter.drawRect(xPos, yPos, xSize, ySize)
xPos += self.wholeWidth
painter.drawRect(xPos - self.wholeWidth + xSize, yPos,
self.size().width() + self.wholeWidth - xPos, self.size().height()) # Last Gap bar
def paintStars(self, event, painter):
# Parse star plot range
plotRange = self.stars['PlotRange']
plotMod = self.plotValues[min(plotRange) - 1:max(plotRange)]
modifier = (sum(plotMod) / len(plotMod)) / self.size().height()
# Softens the stars and set brush
if self.stars['Twinkle']:
twinkle = modifier / 3
else:
twinkle = 0.33
gradient = QRadialGradient()
gradient.setCoordinateMode(QGradient.ObjectBoundingMode)
gradient.setStops(((twinkle, self.stars['Color']), (0.5, QColor(0,0,0,0))))
gradient.setCenter(0.5, 0.5)
gradient.setFocalPoint(0.5, 0.5)
painter.setBrush(gradient)
# Paint Stars
for star in self.starsList:
starPosCenter = (int(star[0] - (star[2] / 2)), int(star[1] - (star[2] / 2)))
painter.drawEllipse(starPosCenter[0], starPosCenter[1], star[2], star[2])
def paintSmooth(self, event, painter):
if not self.gradient:
fillColor = self.mainColor
else:
fillColor = QGradient(self.gradient)
painter.setBrush(fillColor)
if self.outlineOnly:
painter.setBrush(QColor(0, 0, 0, 0))
if self.outlineSize:
if not self.outlineOnly:
penColor = self.outlineColor
else:
penColor = fillColor
painter.setPen(QPen(penColor, self.outlineSize))
# Draw
# painter.setRenderHints(QPainter.Antialiasing) # Stupid expensive to run
painter.drawPolygon(self.smoothShape)
# painter.setRenderHints(QPainter.Antialiasing, False)
def paintBars(self, event, painter):
if self.lumen:
lumReigen = 255 / (self.size().height() * (self.lumen / 100))
lumList = []
if not self.gradient:
fillColor = self.mainColor
else:
fillColor = QGradient(self.gradient)
painter.setBrush(fillColor)
for rect in self.barsShape:
if self.lumen: # Lumen is applied per bar
lumBright = int(rect.height() * lumReigen)
if lumBright > 255: lumBright = 255
if not self.gradient:
lumenColor = QColor(fillColor)
lumenColor.setAlpha(lumBright)
else:
lumenColor = QGradient(fillColor)
for stop in fillColor.stops():
pos = stop[0]
point = stop[1]
point.setAlpha(lumBright)
lumenColor.setColorAt(pos, point)
if self.outlineOnly:
lumList.append(lumenColor)
painter.setBrush(lumenColor) # Fill of bar color
if not self.outlineOnly:
painter.drawRect(rect)
if self.outlineSize > 0 and len(self.barsOutlineShape) == len(self.barsShape)*4:
if not self.outlineOnly:
painter.setBrush(self.outlineColor)
for i in range(len(self.barsOutlineShape)):
if self.lumen and self.outlineOnly:
if not i % 4:
painter.setBrush(lumList[i // 4])
painter.drawRect(self.barsOutlineShape[i])
def paintFreq(self, event, painter):
# Set pen color to contrast main color
if self.mainColor.value() <= 128:
textColor = QColor(255, 255, 255)
else:
textColor = QColor(0, 0, 0)
painter.setPen(QPen(textColor))
font = QFont()
# Scale text with plot width
fontSize = self.plotWidth - 1
if fontSize < 1: fontSize = 1
font.setPixelSize(fontSize)
painter.setFont(font)
ySize = int(fontSize * 1.5)
xPos = self.gapWidth // 2
yPos = self.size().height()
if self.split:
yPos = self.size().height() // 2
# Paint frequency plot
if self.checkFreq:
for freq in self.freqList[:-1]:
freq = round(freq)
digits = 0
number = freq
if number == 0:
digits = 1
while number > 0:
number //= 10
digits += 1
xTextSize = fontSize
yTextSize = ySize * digits
xTextPos = xPos
yTextPos = yPos - yTextSize
painter.drawText(xTextPos, yTextPos, xTextSize, yTextSize, Qt.AlignCenter | Qt.TextWrapAnywhere, str(freq))
xPos += self.wholeWidth
# Instead of painting freq, give a approximation of notes
elif self.checkNotes:
notes = ReVidia.assignNotes(self.freqList[:-1])
plotWidth = self.plotWidth + 1
yTextPos = yPos - ySize
for note in notes:
painter.drawText(xPos, yTextPos, plotWidth, ySize, Qt.AlignCenter, note)
xPos += self.wholeWidth
# Draws a dB bar in right corner
def paintDB(self, event, painter):
dbValue = ReVidia.getDB(self.audioPeak.value)
if dbValue < -1.0:
painter.setPen(self.textPalette.color(QPalette.WindowText))
else:
painter.setPen(QColor(255, 30, 30))
painter.setFont(QApplication.font())
xPos = self.size().width() - 35
yPos = 145
if dbValue == -float('Inf'):
painter.drawText(xPos, yPos, '-Inf')
return
painter.drawText(xPos, yPos, str(dbValue))
xPos = self.size().width() - 15
yPos = yPos - 15
ySize = (-int(dbValue) - 50) * 2
if ySize > 0:
return
gradient = QLinearGradient(xPos, yPos-35, xPos, yPos-100) # xStart, yStart, xStop, yStop
gradient.setColorAt(0, QColor(50, 255, 50))
gradient.setColorAt(0.5, QColor(255, 200, 0))
gradient.setColorAt(1, QColor(255, 50, 50))
painter.setBrush(gradient)
painter.drawRect(xPos, yPos, 5, ySize)
# Draw simple Stats
def paintStats(self, event, painter):
painter.setPen(self.textPalette.color(QPalette.WindowText))
painter.setFont(QApplication.font())
yPos = 40
if self.checkDeadline:
if self.latePercent >= 10: # Keep 3 digits long
self.latePercent = round(self.latePercent, 1)
if self.latePercent >= 100:
self.latePercent = int(self.latePercent)
text = str(self.latePercent) + '%'
xPos = (self.size().width() // 2) - 88
painter.drawText(xPos, yPos, text)
if self.checkPlotNum:
text = str(self.plotsAmt) + ' Plots'
xPos = (self.size().width()//2) - 50
painter.drawText(xPos, 26, 75, 15, Qt.AlignHCenter, text)
if self.checkLatency:
text = str(self.latency) + ' ms'
xPos = (self.size().width() // 2) + 30
painter.drawText(xPos, yPos, text)
def setProfile(self, request):
import pickle
import os
self.width = self.size().width()
self.height = self.size().height()
self.gradAttr = 0
# Order Based Saving/Loading, adding new vars and changing vars names is fine as long as order is kept
saveList = ['width', 'height', 'frameRate', 'pointsList', 'split', 'curvy', 'interp', 'audioBuffer', 'lumen',
'checkRainbow', 'plotWidth', 'gapWidth', 'outlineSize', 'dataCap', 'wholeWidth', 'outlineOnly',
'cutout', 'checkFreq', 'checkNotes', 'checkDeadline', 'checkPlotNum', 'checkLatency', 'checkDB',
'backgroundColor', 'mainColor', 'outlineColor', 'gradAttr', 'stars', 'mainMode']
if request == 'save':
profile, ok = QInputDialog.getText(self, "Save Profile", "Profile Name:")
if ok and profile:
# Special care for the gradient as it cannot be pickled
if self.gradient:
grad = self.gradient
self.gradAttr = grad.start(), grad.finalStop(), grad.stops(), grad.coordinateMode()
# Saving
with open('profiles/' + profile + '.pkl', 'wb') as file:
for setting in saveList:
pickle.dump(getattr(self, setting), file)
else:
profileList = []
for file in os.listdir('profiles'):
profileList.append(file.replace('.pkl', ''))
if not profileList:
profileList.append('No Profiles Saved')
if request == 'load':
profile, ok = QInputDialog.getItem(self, "Load Profile", "Select Profile:", profileList, 0, False)
if ok and profile and profileList != ['No Profiles Saved']:
with open('profiles/' + profile + '.pkl', 'rb') as file:
for setting in saveList:
try:
var = pickle.load(file)
setattr(self, setting, var)
except EOFError:
print("Warning Old Profile: Some settings might not be imported")
break
if self.gradAttr:
self.gradient = QLinearGradient(self.gradAttr[0], self.gradAttr[1])
self.gradient.setStops(self.gradAttr[2])
self.gradient.setCoordinateMode(self.gradAttr[3])
else:
self.gradient = 0
self.menuWidget.close()
self.initUI(True)
elif request == 'delete':