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
|
"""
Home to the Core class which tracks program state. Used by GUI & commandline
to create a list of components and create a video thread to export.
"""
from PyQt6 import QtCore, QtGui, uic
import sys
import os
import json
from importlib import import_module
import logging
from . import toolkit
appName = "Audio Visualizer Python"
log = logging.getLogger("AVP.Core")
STDOUT_LOGLVL = logging.WARNING
class Core:
"""
MainWindow and Command module both use an instance of this class
to store the core program state. This object tracks the components,
talks to the components, handles opening/creating project files
and presets, and creates the video thread to export.
This class also stores constants as class variables.
"""
def __init__(self):
self.importComponents()
self.selectedComponents = []
self.savedPresets = {} # copies of presets to detect modification
self.openingProject = False
def __repr__(self):
return "\n=~=~=~=\n".join([repr(comp) for comp in self.selectedComponents])
def importComponents(self):
def findComponents():
for f in os.listdir(Core.componentsPath):
name, ext = os.path.splitext(f)
if name.startswith("__"):
continue
elif ext == ".py":
yield name
log.debug("Importing component modules")
self.modules = [
import_module(".components.%s" % name, __package__)
for name in findComponents()
]
# store canonical module names and indexes
self.moduleIndexes = [i for i in range(len(self.modules))]
self.compNames = [mod.Component.name for mod in self.modules]
# alphabetize modules by Component name
sortedModules = sorted(zip(self.compNames, self.modules))
self.compNames = [y[0] for y in sortedModules]
self.modules = [y[1] for y in sortedModules]
# store alternative names for modules
self.altCompNames = []
for i, mod in enumerate(self.modules):
if hasattr(mod.Component, "names"):
for name in mod.Component.names():
self.altCompNames.append((name, i))
def componentListChanged(self):
for i, component in enumerate(self.selectedComponents):
component.compPos = i
def insertComponent(self, compPos, component, loader):
"""
Creates a new component using these args:
(compPos, component obj or moduleIndex, MWindow/Command obj)
"""
if compPos < 0 or compPos > len(self.selectedComponents):
compPos = len(self.selectedComponents)
if len(self.selectedComponents) > 50:
return -1
if type(component) is int:
# create component using module index in self.modules
moduleIndex = int(component)
log.debug("Creating new component from module #%s", str(moduleIndex))
component = self.modules[moduleIndex].Component(moduleIndex, compPos, self)
component.widget(loader)
else:
moduleIndex = -1
log.debug("Inserting previously-created %s component", component.name)
component._error.connect(loader.videoThreadError)
self.selectedComponents.insert(compPos, component)
if hasattr(loader, "insertComponent"):
loader.insertComponent(compPos)
self.componentListChanged()
self.updateComponent(compPos)
return compPos
def moveComponent(self, startI, endI):
comp = self.selectedComponents.pop(startI)
self.selectedComponents.insert(endI, comp)
self.componentListChanged()
return endI
def removeComponent(self, i):
self.selectedComponents.pop(i)
self.componentListChanged()
def clearComponents(self):
self.selectedComponents = list()
self.componentListChanged()
def updateComponent(self, i):
log.debug("Auto-updating %s #%s", self.selectedComponents[i], str(i))
self.selectedComponents[i].update(auto=True)
def moduleIndexFor(self, compName):
try:
index = self.compNames.index(compName)
return self.moduleIndexes[index]
except ValueError:
for altName, modI in self.altCompNames:
if altName == compName:
return self.moduleIndexes[modI]
def clearPreset(self, compIndex):
self.selectedComponents[compIndex].currentPreset = None
def openPreset(self, filepath, compIndex, presetName):
"""Applies a preset to a specific component"""
saveValueStore = self.getPreset(filepath)
if not saveValueStore:
return False
comp = self.selectedComponents[compIndex]
comp.loadPreset(saveValueStore, presetName)
self.savedPresets[presetName] = dict(saveValueStore)
return True
def getPreset(self, filepath):
"""Returns the preset dict stored at this filepath"""
if not os.path.exists(filepath):
return False
with open(filepath, "r") as f:
for line in f:
saveValueStore = toolkit.presetFromString(line.strip())
break
return saveValueStore
def getPresetDir(self, comp):
"""Get the preset subdir for a particular version of a component"""
return os.path.join(Core.presetDir, comp.name, str(comp.version))
def openProject(self, loader, filepath):
"""loader is the object calling this method which must have
its own showMessage(**kwargs) method for displaying errors.
"""
if not os.path.exists(filepath):
loader.showMessage(msg="Project file not found.")
return
errcode, data = self.parseAvFile(filepath)
if errcode == 0:
self.openingProject = True
try:
if hasattr(loader, "window"):
for widget, value in data["WindowFields"]:
widget = eval("loader.%s" % widget)
with toolkit.blockSignals(widget):
toolkit.setWidgetValue(widget, value)
for key, value in data["Settings"]:
Core.settings.setValue(key, value)
for tup in data["Components"]:
name, vers, preset = tup
clearThis = False
modified = False
# add loaded named presets to savedPresets dict
if "preset" in preset and preset["preset"] is not None:
nam = preset["preset"]
filepath2 = os.path.join(Core.presetDir, name, str(vers), nam)
origSaveValueStore = self.getPreset(filepath2)
if origSaveValueStore:
self.savedPresets[nam] = dict(origSaveValueStore)
modified = not origSaveValueStore == preset
else:
# saved preset was renamed or deleted
clearThis = True
# create the actual component object & get its index
i = self.insertComponent(-1, self.moduleIndexFor(name), loader)
if i is None:
loader.showMessage(
msg=f"Component '{name}' didn't initialize correctly and had to be removed."
)
continue
if i == -1:
loader.showMessage(msg="Too many components!")
break
try:
if "preset" in preset and preset["preset"] is not None:
self.selectedComponents[i].loadPreset(preset)
else:
self.selectedComponents[i].loadPreset(
preset, preset["preset"]
)
except KeyError as e:
log.warning(
"%s missing value: %s" % (self.selectedComponents[i], e)
)
if clearThis:
self.clearPreset(i)
if hasattr(loader, "updateComponentTitle"):
loader.updateComponentTitle(i, modified)
self.openingProject = False
return True
except Exception:
errcode = 1
data = sys.exc_info()
if errcode == 1:
typ, value, tb = data
if typ.__name__ == "KeyError":
# probably just an old version, still loadable
log.warning("Project file missing value: %s" % value)
return
if hasattr(loader, "createNewProject"):
loader.createNewProject(prompt=False)
msg = "%s: %s\n\n" % (typ.__name__, value)
msg += toolkit.formatTraceback(tb)
loader.showMessage(
msg="Project file '%s' is corrupted." % filepath,
showCancel=False,
icon="Warning",
detail=msg,
)
self.openingProject = False
return False
def parseAvFile(self, filepath):
"""
Parses an avp (project) or avl (preset package) file.
Returns dictionary with section names as the keys, each one
contains a list of tuples: (compName, version, compPresetDict)
"""
log.debug("Parsing av file: %s", filepath)
validSections = ("Components", "Settings", "WindowFields")
data = {sect: [] for sect in validSections}
try:
with open(filepath, "r") as f:
def parseLine(line):
"""Decides if a file line is a section header"""
line = line.strip()
newSection = ""
if (
line.startswith("[")
and line.endswith("]")
and line[1:-1] in validSections
):
newSection = line[1:-1]
return line, newSection
section = ""
i = 0
for line in f:
line, newSection = parseLine(line)
if newSection:
section = str(newSection)
continue
if line and section == "Components":
if i == 0:
lastCompName = str(line)
i += 1
elif i == 1:
lastCompVers = str(line)
i += 1
elif i == 2:
lastCompPreset = toolkit.presetFromString(line)
data[section].append(
(lastCompName, lastCompVers, lastCompPreset)
)
i = 0
elif line and section:
key, value = line.split("=", 1)
data[section].append((key, value.strip()))
return 0, data
except Exception:
return 1, sys.exc_info()
def importPreset(self, filepath):
errcode, data = self.parseAvFile(filepath)
returnList = []
if errcode == 0:
name, vers, preset = data["Components"][0]
presetName = (
preset["preset"]
if preset["preset"]
else os.path.basename(filepath)[:-4]
)
newPath = os.path.join(Core.presetDir, name, vers, presetName)
if os.path.exists(newPath):
return False, newPath
preset["preset"] = presetName
self.createPresetFile(name, vers, presetName, preset)
return True, presetName
elif errcode == 1:
# TODO: an error message
return False, ""
def exportPreset(self, exportPath, compName, vers, origName):
internalPath = os.path.join(Core.presetDir, compName, str(vers), origName)
if not os.path.exists(internalPath):
return
if os.path.exists(exportPath):
os.remove(exportPath)
with open(internalPath, "r") as f:
internalData = [line for line in f]
try:
saveValueStore = toolkit.presetFromString(internalData[0].strip())
self.createPresetFile(compName, vers, origName, saveValueStore, exportPath)
return True
except Exception:
return False
def createPresetFile(self, compName, vers, presetName, saveValueStore, filepath=""):
"""Create a preset file (.avl) at filepath using args.
Or if filepath is empty, create an internal preset using args"""
if not filepath:
dirname = os.path.join(Core.presetDir, compName, str(vers))
if not os.path.exists(dirname):
os.makedirs(dirname)
filepath = os.path.join(dirname, presetName)
internal = True
else:
if not filepath.endswith(".avl"):
filepath += ".avl"
internal = False
with open(filepath, "w") as f:
if not internal:
f.write("[Components]\n")
f.write("%s\n" % compName)
f.write("%s\n" % str(vers))
f.write(toolkit.presetToString(saveValueStore))
def createProjectFile(self, filepath, window=None):
"""Create a project file (.avp) using the current program state"""
log.info("Creating %s", filepath)
settingsKeys = [
"componentDir",
"inputDir",
"outputDir",
"presetDir",
"projectDir",
]
try:
if not filepath.endswith(".avp"):
filepath += ".avp"
if os.path.exists(filepath):
os.remove(filepath)
with open(filepath, "w") as f:
f.write("[Components]\n")
for comp in self.selectedComponents:
saveValueStore = comp.savePreset()
saveValueStore["preset"] = comp.currentPreset
f.write("%s\n" % str(comp))
f.write("%s\n" % str(comp.version))
f.write("%s\n" % toolkit.presetToString(saveValueStore))
f.write("\n[Settings]\n")
for key in Core.settings.allKeys():
if key in settingsKeys:
f.write("%s=%s\n" % (key, Core.settings.value(key)))
if window:
f.write("\n[WindowFields]\n")
f.write(
"lineEdit_audioFile=%s\n"
"lineEdit_outputFile=%s\n"
% (
window.lineEdit_audioFile.text(),
window.lineEdit_outputFile.text(),
)
)
return True
except Exception:
return False
def newVideoWorker(self, loader, audioFile, outputPath):
"""loader is MainWindow or Command object which must own the thread"""
from . import video_thread
self.videoThread = QtCore.QThread(loader)
videoWorker = video_thread.Worker(
loader, audioFile, outputPath, self.selectedComponents
)
videoWorker.moveToThread(self.videoThread)
videoWorker.videoCreated.connect(self.stopVideoThread)
self.videoThread.start()
return videoWorker
def stopVideoThread(self):
self.videoThread.quit()
self.videoThread.wait()
def cancel(self):
Core.canceled = True
def reset(self):
Core.canceled = False
@classmethod
def storeSettings(cls):
"""Store settings/paths to directories as class variables"""
from .__init__ import wd
from .toolkit.ffmpeg import findFfmpeg
cls.wd = wd
dataDir = QtCore.QStandardPaths.writableLocation(
QtCore.QStandardPaths.StandardLocation.AppConfigLocation
)
# Windows: C:/Users/<USER>/AppData/Local/audio-visualizer
# macOS: ~/Library/Preferences/audio-visualizer
# Linux: ~/.config/audio-visualizer
with open(os.path.join(wd, "encoder-options.json")) as json_file:
encoderOptions = json.load(json_file)
# Locate FFmpeg
ffmpegBin = findFfmpeg()
if not ffmpegBin:
print("Could not find FFmpeg")
settings = {
"canceled": False,
"FFMPEG_BIN": ffmpegBin,
"dataDir": dataDir,
"settings": QtCore.QSettings(
os.path.join(dataDir, "settings.ini"),
QtCore.QSettings.Format.IniFormat,
),
"presetDir": os.path.join(dataDir, "presets"),
"componentsPath": os.path.join(wd, "components"),
"junkStream": os.path.join(wd, "gui", "background.png"),
"encoderOptions": encoderOptions,
"resolutions": [
"1920x1080",
"1280x720",
"854x480",
],
"logDir": os.path.join(dataDir, "log"),
"logEnabled": False,
"previewEnabled": True,
}
settings["videoFormats"] = toolkit.appendUppercase(
[
"*.mp4",
"*.mov",
"*.mkv",
"*.avi",
"*.webm",
"*.flv",
]
)
settings["audioFormats"] = toolkit.appendUppercase(
[
"*.mp3",
"*.wav",
"*.ogg",
"*.fla",
"*.flac",
"*.aac",
]
)
settings["imageFormats"] = toolkit.appendUppercase(
[
"*.png",
"*.jpg",
"*.tif",
"*.tiff",
"*.gif",
"*.bmp",
"*.ico",
"*.xbm",
"*.xpm",
]
)
# Register all settings as class variables
for classvar, val in settings.items():
setattr(cls, classvar, val)
cls.loadDefaultSettings()
if not os.path.exists(cls.dataDir):
os.makedirs(cls.dataDir)
for neededDirectory in (
cls.presetDir,
cls.logDir,
cls.settings.value("projectDir"),
):
if not os.path.exists(neededDirectory):
os.mkdir(neededDirectory)
cls.makeLogger(deleteOldLogs=True)
@classmethod
def loadDefaultSettings(cls):
# settings that get saved into the ini file
cls.defaultSettings = {
"outputWidth": 1280,
"outputHeight": 720,
"outputFrameRate": 30,
"outputAudioCodec": "AAC",
"outputAudioBitrate": "192",
"outputVideoCodec": "H264",
"outputVideoBitrate": "2500",
"outputVideoFormat": "yuv420p",
"outputPreset": "medium",
"outputFormat": "mp4",
"outputContainer": "MP4",
"projectDir": os.path.join(cls.dataDir, "projects"),
"pref_insertCompAtTop": True,
"pref_genericPreview": True,
"pref_undoLimit": 10,
}
for parm, value in cls.defaultSettings.items():
if cls.settings.value(parm) is None:
cls.settings.setValue(parm, value)
# Allow manual editing of prefs. (Surprisingly necessary as Qt seems to
# store True as 'true' but interprets a manually-added 'true' as str.)
for key in cls.settings.allKeys():
if not key.startswith("pref_"):
continue
val = cls.settings.value(key)
try:
val = int(val)
except ValueError:
if val == "true":
val = True
elif val == "false":
val = False
cls.settings.setValue(key, val)
@staticmethod
def makeLogger(deleteOldLogs=False, fileLogLvl=None):
# send critical log messages to stdout
logStream = logging.StreamHandler()
logStream.setLevel(STDOUT_LOGLVL)
streamFormatter = logging.Formatter("<%(name)s> %(levelname)s: %(message)s")
logStream.setFormatter(streamFormatter)
log = logging.getLogger("AVP")
log.addHandler(logStream)
if fileLogLvl is not None:
# write log files as well!
Core.logEnabled = True
logFilename = os.path.join(Core.logDir, "avp_debug.log")
libLogFilename = os.path.join(Core.logDir, "global_debug.log")
if deleteOldLogs:
for log_ in (logFilename, libLogFilename):
if os.path.exists(log_):
os.remove(log_)
logFile = logging.FileHandler(logFilename, delay=True)
logFile.setLevel(fileLogLvl)
libLogFile = logging.FileHandler(libLogFilename, delay=True)
libLogFile.setLevel(fileLogLvl)
fileFormatter = logging.Formatter(
"[%(asctime)s] %(threadName)-10.10s %(name)-23.23s %(levelname)s: "
"%(message)s"
)
logFile.setFormatter(fileFormatter)
libLogFile.setFormatter(fileFormatter)
libLog = logging.getLogger()
log.addHandler(logFile)
libLog.addHandler(libLogFile)
# lowest level must be explicitly set on the root Logger
libLog.setLevel(0)
# always store settings in class variables even if a Core object is not created
Core.storeSettings()
|