-
Notifications
You must be signed in to change notification settings - Fork 6
/
FFMPEGAudioEncoder.py
13268 lines (12369 loc) · 556 KB
/
FFMPEGAudioEncoder.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
# Imports--------------------------------------------------------------------
import os
import pathlib
import pickle
import shutil
import subprocess
import sys
import threading
import tkinter.scrolledtext as scrolledtextwidget
import webbrowser
from collections import Counter
from configparser import ConfigParser
from ctypes import windll
from datetime import datetime
from glob import glob
from idlelib.tooltip import Hovertip
from random import randint
from time import sleep
from tkinter import (
filedialog,
StringVar,
ttk,
messagebox,
PhotoImage,
Menu,
NORMAL,
DISABLED,
N,
S,
W,
E,
Toplevel,
LabelFrame,
END,
INSERT,
Label,
Checkbutton,
Spinbox,
CENTER,
GROOVE,
OptionMenu,
Entry,
HORIZONTAL,
SUNKEN,
Button,
TclError,
font,
Frame,
Scrollbar,
VERTICAL,
Listbox,
EXTENDED,
)
import psutil
import pyperclip
from pyautogui import hotkey as pya_hotkey
from pymediainfo import MediaInfo
from tkinterdnd2 import DND_FILES, TkinterDnD
from Packages.About import openaboutwindow
from Packages.SimpleYoutubeDLGui import youtube_dl_launcher_for_ffmpegaudioencoder
from Packages.config_params import create_config_params
from Packages.general_settings import open_general_settings
from Packages.icon import gui_icon
from Packages.show_streams import (
show_streams_mediainfo_function,
exit_stream_window,
stream_menu,
)
from Packages.window_geometry_settings import set_window_geometry_settings
# Set variable to True if you want errors to pop up in window + log to file + console, False for console only
log_error_to_file = (
True # Change this to false if you don't want to log errors to file + pop up window
)
# Set main window title variable
main_root_title = "FFMPEG Audio Encoder v4.11"
# default an empty variable to be updated based off user input
batch_mode = None
# Checks for App Folder and Sub-Directories - Creates Folders if they are missing ---------
pathlib.Path(pathlib.Path.cwd() / "Runtime").mkdir(parents=True, exist_ok=True)
pathlib.Path(pathlib.Path.cwd() / "Runtime" / "logs").mkdir(parents=True, exist_ok=True)
pathlib.Path(pathlib.Path.cwd() / "Runtime" / "logs" / "error_logs").mkdir(
parents=True, exist_ok=True
)
pathlib.Path(pathlib.Path.cwd() / "Runtime" / "logs" / "job_manager_multi").mkdir(
parents=True, exist_ok=True
)
pathlib.Path(pathlib.Path.cwd() / "Runtime" / "logs" / "job_manager_single").mkdir(
parents=True, exist_ok=True
)
pathlib.Path(pathlib.Path.cwd() / "Runtime" / "logs" / "manual_auto").mkdir(
parents=True, exist_ok=True
)
pathlib.Path(pathlib.Path.cwd() / "Apps" / "FFMPEG").mkdir(parents=True, exist_ok=True)
pathlib.Path(pathlib.Path.cwd() / "Apps" / "MediaInfo").mkdir(
parents=True, exist_ok=True
)
pathlib.Path(pathlib.Path.cwd() / "Apps" / "fdkaac").mkdir(parents=True, exist_ok=True)
pathlib.Path(pathlib.Path.cwd() / "Apps" / "qaac").mkdir(parents=True, exist_ok=True)
pathlib.Path(pathlib.Path.cwd() / "Apps" / "qaac" / "QTfiles64").mkdir(
parents=True, exist_ok=True
)
pathlib.Path(pathlib.Path.cwd() / "Apps" / "mpv").mkdir(parents=True, exist_ok=True)
# ----------------------------------------------------------------------------- Folder Check
# Main Gui & Windows --------------------------------------------------------
def root_exit_function():
def save_root_pos(): # Function to write to config.ini
func_parser = ConfigParser()
func_parser.read(config_file)
if func_parser["save_window_locations"]["ffmpeg audio encoder"] == "yes":
try: # If auto-save position on exit is checked
func_parser.set(
"save_window_locations",
"ffmpeg audio encoder position",
root.geometry(),
)
with open(config_file, "w") as configfile:
func_parser.write(configfile)
except (Exception,):
pass
open_tops = False # Set variable for open toplevel windows
for widget in root.winfo_children(): # Loop through roots children
if isinstance(
widget, Toplevel
): # If any of roots children is a TopLevel window
open_tops = True # Set variable for open tops to True
if open_tops: # If open_tops is True
confirm_exit = messagebox.askyesno(
title="Prompt",
message="Are you sure you want to exit the program?\n\n"
"Warning:\nThis will end all current tasks, "
"child-processes, and close all open windows!",
parent=root,
)
if confirm_exit: # If user wants to exit, kill app and all of it's children
parent = psutil.Process(root_pid) # Set psutil parent ID
for child in parent.children(recursive=True):
child.kill() # Loop through all the children processes and kill them with psutil module
save_root_pos() # Save root position
root.destroy() # Root destroy
exit_and_clean_empty_logs() # Exit and clean empty error log files
if not open_tops: # If no top levels are found, exit the program without prompt
parent = psutil.Process(root_pid) # Set psutil parent ID
for child in parent.children(recursive=True):
child.kill() # Loop through all the children processes and kill them with psutil module
save_root_pos() # Save root position
root.destroy() # Root destroy
exit_and_clean_empty_logs() # Exit and clean empty error log files
# ------------------------------------------------------------------------------------------------------- Config Parser
create_config_params() # Runs the function to define/create all the parameters in the needed .ini files
# Defines the path to config.ini and opens it for reading/writing
config_file = "Runtime/config.ini" # Creates (if doesn't exist) and defines location of config.ini
config = ConfigParser()
config.read(config_file)
# Defines the path to profiles.ini and opens it for reading/writing
config_profile_ini = "Runtime/profiles.ini" # Creates (if doesn't exist) and defines location of profile.ini
config_profile = ConfigParser()
config_profile.read(config_profile_ini)
# Config Parser -------------------------------------------------------------------------------------------------------
# Clean log files -----------------------------------------------------------------------------------------------------
def clean_manual_auto(): # Code to clean auto/manual job log files on start
log_path = "Runtime/logs/manual_auto/"
pathlib.Path(log_path).resolve().mkdir(parents=True, exist_ok=True)
max_log_files = 50
files = glob(os.path.join(log_path, "*.txt")) # Collect all files.
# Choose files to be deleted.
to_delete = sorted(files, key=lambda x: os.stat(x).st_mtime)[
: len(files) - max_log_files
]
for error_files in to_delete: # Delete files
os.remove(error_files)
def clean_job_window_single(): # Code to clean job manager window single encodes log files on start
log_path = "Runtime/logs/job_manager_single/"
pathlib.Path(log_path).resolve().mkdir(parents=True, exist_ok=True)
max_log_files = 100
files = glob(os.path.join(log_path, "*.txt")) # Collect all files.
# Choose files to be deleted.
to_delete = sorted(files, key=lambda x: os.stat(x).st_mtime)[
: len(files) - max_log_files
]
for error_files in to_delete: # Delete files
os.remove(error_files)
def clean_job_window_multi(): # Code to clean job manager window multi encodes log files on start
log_path = "Runtime/logs/job_manager_multi/"
pathlib.Path(log_path).resolve().mkdir(parents=True, exist_ok=True)
max_log_files = 100
files = glob(os.path.join(log_path, "*.txt")) # Collect all files.
# Choose files to be deleted.
to_delete = sorted(files, key=lambda x: os.stat(x).st_mtime)[
: len(files) - max_log_files
]
for error_files in to_delete: # Delete files
os.remove(error_files)
def clean_main_program_error_logs(): # Clean main gui error files
path = "Runtime/logs/error_logs/" # Set path to log files
empty_files = glob(os.path.join(path, "*.txt"))
to_delete = (f for f in empty_files if os.stat(f).st_size == 0)
for f in to_delete: # Get rid of any empty log files on start, if there is any
os.remove(f)
pathlib.Path(path).resolve().mkdir(
parents=True, exist_ok=True
) # Remove older error files over 10
max_error_files = 10 # Set maximum amount of error files in directory
files = glob(os.path.join(path, "*.txt")) # Collect all files.
# Choose files to be deleted.
to_delete = sorted(files, key=lambda x: os.stat(x).st_mtime)[
: len(files) - max_error_files
]
for error_files in to_delete: # Delete files
os.remove(error_files)
clean_manual_auto()
clean_job_window_single()
clean_job_window_multi()
clean_main_program_error_logs()
# ----------------------------------------------------------------------------------------------------- Clean log files
root = TkinterDnD.Tk()
root.title(main_root_title)
root.iconphoto(True, PhotoImage(data=gui_icon))
root.configure(background="#434547")
if (
config["save_window_locations"]["ffmpeg audio encoder position"] == ""
or config["save_window_locations"]["ffmpeg audio encoder"] == "no"
):
window_height = 325
window_width = 570
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x_coordinate = int((screen_width / 2) - (window_width / 2))
y_coordinate = int((screen_height / 2) - (window_height / 2))
root.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")
elif (
config["save_window_locations"]["ffmpeg audio encoder position"] != ""
and config["save_window_locations"]["ffmpeg audio encoder"] == "yes"
):
root.geometry(config["save_window_locations"]["ffmpeg audio encoder position"])
root.protocol("WM_DELETE_WINDOW", root_exit_function)
root_pid = os.getpid() # Get root process ID
# Block of code to fix DPI awareness issues on Windows 7 or higher
try:
windll.shcore.SetProcessDpiAwareness(2) # if your Windows version >= 8.1
except (Exception,):
windll.user32.SetProcessDPIAware() # Windows 8.0 or less
# Block of code to fix DPI awareness issues on Windows 7 or higher
for n in range(4):
root.grid_columnconfigure(n, weight=1)
for n in range(4):
root.grid_rowconfigure(n, weight=1)
# Themes --------------------------------------------------------------------------------------------------------------
# Font Variables ---------------------------------------------
detect_font = font.nametofont(
"TkDefaultFont"
) # Get default font value into Font object
set_font = detect_font.actual().get("family")
set_font_size = detect_font.actual().get("size")
# ---------------------------------------------- Font Variables
# Custom Tkinter Theme-----------------------------------------
custom_style = ttk.Style()
custom_style.theme_create(
"jlw_style",
parent="alt",
settings={
# Notebook Theme Settings -------------------
"TNotebook": {"configure": {"tabmargins": [5, 5, 5, 0]}},
"TNotebook.Tab": {
"configure": {
"padding": [5, 1],
"background": "grey",
"foreground": "white",
"focuscolor": "",
},
"map": {
"background": [("selected", "#434547")],
"expand": [("selected", [1, 1, 1, 0])],
},
},
# Notebook Theme Settings -------------------
# ComboBox Theme Settings -------------------
"TCombobox": {
"configure": {
"selectbackground": "#23272A",
"fieldbackground": "#23272A",
"background": "white",
"foreground": "white",
}
},
}
# ComboBox Theme Settings -------------------
)
custom_style.theme_use("jlw_style") # Enable the use of the custom theme
custom_style.configure("custom.Horizontal.TProgressbar", background="#3a4145")
# ------------------------------------------ Custom Tkinter Theme
# Hover over button theme ---------------------------------------
class HoverButton(Button):
def __init__(self, master, **kw):
Button.__init__(self, master=master, **kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self["background"] = self["activebackground"]
if self.cget("text") == "Input":
status_label.configure(text="Open input menu or drag and drop a file...")
if self.cget("text") == "Display\nCommand":
status_label.configure(text="Display command-line...")
if self.cget("text") == "Save File":
status_label.configure(text="Specify save location...")
if self.cget("text") == "Auto Encode:\nLast Used Options":
global rightclick_on_off
status_label.configure(text="Right click for more options...")
rightclick_on_off = 1
if self.cget("text") == "Codec Settings":
status_label.configure(text="Configure selected audio codec..")
if self.cget("text") == "Start Job":
status_label.configure(text="Start job..")
if self.cget("text") == "Add to Jobs List":
status_label.configure(text="Add configured job to jobs list...")
def on_leave(self, e):
self["background"] = self.defaultBackground
if self.cget("text") == "Auto Encode:\nLast Used Options":
global rightclick_on_off
status_label.configure(text="Right Click For More Options...")
rightclick_on_off = 0
status_label.configure(text="")
else:
status_label.configure(text="")
# --------------------------------------- Hover over button theme
# -------------------------------------------------------------------------------------------------------------- Themes
# Open GitHub tracker for program -------------------------------------------------------------------------------------
def open_github_error_tracker():
webbrowser.open("https://github.com/jlw4049/FFMPEG-Audio-Encoder/issues")
# ------------------------------------------------------------------------------------- Open github tracker for program
# Logger class, handles all traceback/stdout errors for program, writes to file and to window -------------------------
if log_error_to_file:
class Logger(
object
): # Logger class, this class puts stderr errors into a window and file at the same time
def __init__(self):
self.terminal = sys.stderr # Redirects sys.stderr
error_folder = pathlib.Path(
"Runtime/logs/error_logs/"
).resolve() # Define error folder
pathlib.Path(error_folder).mkdir(
parents=False, exist_ok=True
) # Create the folder if it doesn't exist
error_log_txt = pathlib.Path(
f"{str(error_folder)}/{datetime.now().strftime('%m-%d-%y - %I.%M.%S')}"
f"-errorlog.txt"
)
self.error_log_file = open(
error_log_txt, "w", encoding="utf-8"
) # Set log file name + open/write
def write(self, message):
global info_scrolled
self.terminal.write(message)
self.error_log_file.write(message)
root.bell() # Error bell sound
try:
info_scrolled.config(state=NORMAL)
if str(message).rstrip():
info_scrolled.insert(END, str(message).strip())
if not str(message).rstrip():
info_scrolled.insert(END, f"{str(message)}\n")
info_scrolled.see(END)
info_scrolled.config(state=DISABLED)
except (NameError, TclError):
error_window = Toplevel()
error_window.title("Traceback Error(s)")
error_window.configure(background="#434547")
window_height = 400
window_width = 600
screen_width = error_window.winfo_screenwidth()
screen_height = error_window.winfo_screenheight()
x_coordinate = int((screen_width / 2) - (window_width / 2))
y_coordinate = int((screen_height / 2) - (window_height / 2))
error_window.geometry(
f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}"
)
error_window.grab_set() # Brings attention to this window until it's closed
for e_w in range(4):
error_window.grid_columnconfigure(e_w, weight=1)
error_window.grid_rowconfigure(0, weight=1)
info_scrolled = scrolledtextwidget.ScrolledText(
error_window, tabs=10, spacing2=3, spacing1=2, spacing3=3
)
info_scrolled.grid(
row=0, column=0, columnspan=4, pady=5, padx=5, sticky=E + W + N + S
)
info_scrolled.configure(bg="black", fg="#CFD2D1", bd=8)
info_scrolled.insert(END, message)
info_scrolled.see(END)
info_scrolled.config(state=DISABLED)
report_error = HoverButton(
error_window,
text="Report Error",
command=open_github_error_tracker,
foreground="white",
background="#23272A",
borderwidth="3",
activebackground="grey",
)
report_error.grid(
row=1,
column=3,
columnspan=1,
padx=10,
pady=(5, 4),
sticky=S + E + N,
)
force_close_root = HoverButton(
error_window,
text="Force Close Program",
command=root.destroy,
foreground="white",
background="#23272A",
borderwidth="3",
activebackground="grey",
)
force_close_root.grid(
row=1,
column=0,
columnspan=1,
padx=10,
pady=(5, 4),
sticky=S + W + N,
)
def right_click_menu_func(
x_y_pos,
): # Function for mouse button 3 (right click) to pop up menu
right_click_menu.tk_popup(
x_y_pos.x_root, x_y_pos.y_root
) # This gets the position of cursor
right_click_menu = Menu(
info_scrolled, tearoff=False
) # This is the right click menu
right_click_menu.add_command(
label="Copy to clipboard",
command=lambda: pyperclip.copy(info_scrolled.get(1.0, END).strip()),
)
info_scrolled.bind(
"<Button-3>", right_click_menu_func
) # Uses mouse button 3 to open the menu
Hovertip(
info_scrolled, "Right click to copy", hover_delay=1200
) # Hover tip tool-tip
def flush(self):
pass
def __exit__(self): # Class exit function
sys.stderr = sys.__stderr__ # Redirect stderr back to original stderr
self.error_log_file.close() # Close file
def start_logger():
if log_error_to_file: # If True
sys.stderr = Logger() # Start the Logger() class to write to console and file
threading.Thread(target=start_logger).start()
def exit_and_clean_empty_logs(): # Function to exit logger() and delete logfile if it's empty
if log_error_to_file: # If True
Logger().__exit__() # Run Logger()__exit__() function
empty_files = glob(os.path.join("Runtime/logs/error_logs/", "*.txt"))
to_delete = (f for f in empty_files if os.stat(f).st_size == 0)
for f in to_delete: # Check and delete empty files, if there is any
os.remove(f)
elif (
not log_error_to_file
): # If error logging is set to false, do nothing inside this function
return
# ------------------------- Logger class, handles all traceback/stdout errors for program, writes to file and to window
# Bundled Apps --------------------------------------------------------------------------------------------------------
# define tool paths ------------------------------------------------------------------------
# define ffmpeg
ffmpeg = config["ffmpeg_path"]["path"]
# define mediainfo
mediainfo = config["mediainfogui_path"]["path"]
# define fdk-aac at program launch
# config_writer for fdk-aac
def write_fdk_config(fdk_var):
config.set("fdkaac_path", "path", fdk_var)
with open(config_file, "w") as fdk_cfg:
config.write(fdk_cfg) # write path to fdkaac to the config.ini file
if config["fdkaac_path"]["path"] != "": # if fdk path is defined
if not pathlib.Path(
str(config["fdkaac_path"]["path"]).replace('"', "")
).is_file(): # if fdk is not present
if pathlib.Path("Apps/fdkaac/fdkaac.exe").is_file():
write_fdk_config(f'"{str(pathlib.Path("Apps/fdkaac/fdkaac.exe"))}"')
elif not pathlib.Path("Apps/fdkaac/fdkaac.exe").is_file():
write_fdk_config("") # clear fdk_path in config.ini
elif (
pathlib.Path("Apps/fdkaac/fdkaac.exe").is_file()
and config["fdkaac_path"]["path"] == ""
):
write_fdk_config(
f'"{str(pathlib.Path("Apps/fdkaac/fdkaac.exe"))}"'
) # add path to fdk in apps folder to config.ini
elif (
not pathlib.Path("Apps/fdkaac/fdkaac.exe").is_file()
and config["fdkaac_path"]["path"] == ""
):
write_fdk_config("") # clear fdk_path in config.ini
fdkaac = config["fdkaac_path"]["path"] # define path to fdkaac via config.ini
# # define qaac at program launch
# # config_writer for qaac
def write_qaac_config(qaac_var):
config.set("qaac_path", "path", qaac_var)
with open(config_file, "w") as qaac_writer_cfg:
config.write(qaac_writer_cfg) # write path to fdkaac to the config.ini file
if config["qaac_path"]["path"] != "": # if qaac is defined
if not pathlib.Path(
str(config["qaac_path"]["path"]).replace('"', "")
).is_file(): # if qaac is not present
if pathlib.Path("Apps/qaac/qaac64.exe").is_file():
write_qaac_config(f'"{str(pathlib.Path("Apps/qaac/qaac64.exe"))}"')
config.set(
"qaac_path", "qt_path", f'"{str(pathlib.Path("Apps/qaac/QTfiles64"))}"'
)
with open(config_file, "w") as qaac_cfg:
config.write(qaac_cfg) # write path to qaac to the config.ini file
elif not pathlib.Path("Apps/qaac/qaac64.exe").is_file():
write_qaac_config("") # clear fdk_path in config.ini
config.set("qaac_path", "qt_path", "")
with open(config_file, "w") as qaac_cfg:
config.write(qaac_cfg) # write path to qaac to the config.ini file
elif (
pathlib.Path("Apps/qaac/qaac64.exe").is_file() and config["qaac_path"]["path"] == ""
):
write_qaac_config(f'"{str(pathlib.Path("Apps/qaac/qaac64.exe"))}"')
config.set("qaac_path", "qt_path", f'"{str(pathlib.Path("Apps/qaac/QTfiles64"))}"')
with open(config_file, "w") as qaac_cfg:
config.write(qaac_cfg) # write path to qaac to the config.ini file
elif (
not pathlib.Path("Apps/qaac/qaac64.exe").is_file()
and config["qaac_path"]["path"] == ""
):
write_qaac_config("") # clear fdk_path in config.ini
config.set("qaac_path", "qt_path", "")
with open(config_file, "w") as qaac_cfg:
config.write(qaac_cfg) # write path to qaac to the config.ini file
qaac = config["qaac_path"]["path"]
# define mpv player
mpv_player = config["mpv_player_path"]["path"]
# ------------------------------------------------------------------------ define tool paths
# -------------------------------------------------------------------------------------------------------- Bundled Apps
# Open InputFile with portable MediaInfo ------------------------------------------------------------------------------
def mediainfogui():
try:
file_input_quoted = '"' + file_input + '"'
commands = mediainfo + " " + file_input_quoted
subprocess.Popen(commands)
except (Exception,):
commands = mediainfo
subprocess.Popen(commands)
# ----------------------------------------------------------------------------------------------------------- MediaInfo
# Open InputFile with portable mpv ------------------------------------------------------------------------------------
def mpv_gui_main_gui():
try:
file_input_quoted = '"' + file_input + '"'
commands = mpv_player + " " + file_input_quoted
subprocess.Popen(commands)
except (Exception,):
commands = mpv_player
subprocess.Popen(commands)
# ----------------------------------------------------------------------------------------------------------------- mpv
# Menu Items and Sub-Bars ---------------------------------------------------------------------------------------------
my_menu_bar = Menu(root, tearoff=0)
root.config(menu=my_menu_bar)
file_menu = Menu(my_menu_bar, tearoff=0, activebackground="dim grey")
my_menu_bar.add_cascade(label="File", menu=file_menu)
options_menu = Menu(my_menu_bar, tearoff=0, activebackground="dim grey")
my_menu_bar.add_cascade(label="Options", menu=options_menu)
options_submenu = Menu(root, tearoff=0, activebackground="dim grey")
options_menu.add_cascade(label="Progress Output", menu=options_submenu)
progress_output_view = StringVar()
progress_output_view.set(config["debug_option"]["option"])
if progress_output_view.get() == "":
progress_output_view.set("Default")
elif progress_output_view.get() != "":
progress_output_view.set(config["debug_option"]["option"])
def update_shell_option():
try:
config.set("debug_option", "option", progress_output_view.get())
with open(config_file, "w") as configfile:
config.write(configfile)
except (Exception,):
pass
update_shell_option()
options_submenu.add_radiobutton(
label="Progress Bars",
variable=progress_output_view,
value="Default",
command=update_shell_option,
)
options_submenu.add_radiobutton(
label="CMD Shell (Debug)",
variable=progress_output_view,
value="Debug",
command=update_shell_option,
)
auto_close_window = StringVar()
auto_close_window.set(config["auto_close_progress_window"]["option"])
if auto_close_window.get() == "":
auto_close_window.set("on")
elif auto_close_window.get() != "":
auto_close_window.set(config["auto_close_progress_window"]["option"])
def update_auto_close():
try:
config.set("auto_close_progress_window", "option", auto_close_window.get())
with open(config_file, "w") as configfile:
config.write(configfile)
except (Exception,):
pass
update_auto_close()
options_submenu2 = Menu(root, tearoff=0, activebackground="dim grey")
options_menu.add_cascade(
label="Auto-Close Progress Window On Completion", menu=options_submenu2
)
options_submenu2.add_radiobutton(
label="On", variable=auto_close_window, value="on", command=update_auto_close
)
options_submenu2.add_radiobutton(
label="Off", variable=auto_close_window, value="off", command=update_auto_close
)
options_menu.add_separator()
options_menu.add_command(
label="Window Location Settings [CTRL + W]",
command=set_window_geometry_settings,
)
root.bind("<Control-w>", lambda event: set_window_geometry_settings())
def open_settings_window():
open_tops = False # Set variable for open toplevel windows
for widget in root.winfo_children(): # Loop through roots children
if isinstance(
widget, Toplevel
): # If any of roots children is a TopLevel window
open_tops = True # Set variable for open tops to True
if open_tops: # If open_tops is True
prompt = messagebox.askyesno(
title="Prompt",
message="This will close all secondary windows, are you sure "
"you want to continue?",
)
if prompt:
set_fresh_launch()
open_general_settings()
if not open_tops:
set_fresh_launch()
open_general_settings()
options_menu.add_command(
label="General Settings [CTRL + S]", command=open_settings_window
)
root.bind("<Control-s>", lambda event: open_settings_window())
options_menu.add_separator()
def reset_config():
msg = messagebox.askyesno(
title="Warning",
message="Are you sure you want to reset the config.ini file settings?",
)
if msg:
try:
pathlib.Path(config_file).unlink()
messagebox.showinfo(title="Prompt", message="Please restart the program")
except FileNotFoundError:
messagebox.showerror(
title="Error!",
message='"Config.ini" is already deleted, please restart the program',
)
root.destroy()
options_menu.add_command(label="Reset Configuration File", command=reset_config)
def clean_all_logs(): # Function to clean all log files if hit
msg = messagebox.askyesno(
title="Warning", message="Are you sure you want to delete all log files?"
)
if msg:
log_folder_manual = pathlib.Path("Runtime/logs/manual_auto/").resolve()
log_folder_job_manager_single = pathlib.Path(
"Runtime/logs/job_manager_single/"
).resolve()
log_folder_job_manager_multi = pathlib.Path(
"Runtime/logs/job_manager_multi/"
).resolve()
error_log_folder = pathlib.Path("Runtime/logs/error_logs/").resolve()
[f.unlink() for f in pathlib.Path(log_folder_manual).glob("*") if f.is_file()]
[
f.unlink()
for f in pathlib.Path(log_folder_job_manager_single).glob("*")
if f.is_file()
]
[
f.unlink()
for f in pathlib.Path(log_folder_job_manager_multi).glob("*")
if f.is_file()
]
try:
[
f.unlink()
for f in pathlib.Path(error_log_folder).glob("*")
if f.is_file()
]
except (
PermissionError
): # If file is in use (1 always will be, ignore the error)
pass
if (
len(os.listdir(log_folder_manual)) == 0
and len(os.listdir(log_folder_job_manager_single)) == 0
and len(os.listdir(log_folder_job_manager_multi))
and len(os.listdir(error_log_folder)) <= 1
):
messagebox.showinfo(
title="Info",
message="All log directories have been cleaned, other then file in use",
)
options_menu.add_command(label="Clean Log Files", command=clean_all_logs)
tools_submenu = Menu(my_menu_bar, tearoff=0, activebackground="dim grey")
my_menu_bar.add_cascade(label="Tools", menu=tools_submenu)
tools_submenu.add_command(label="MediaInfo", command=mediainfogui)
tools_submenu.add_command(label="MPV (Media Player)", command=mpv_gui_main_gui)
tools_submenu.add_command(
label="Simple-Youtube-DL-Gui", command=youtube_dl_launcher_for_ffmpegaudioencoder
)
help_menu = Menu(my_menu_bar, tearoff=0, activebackground="dim grey")
my_menu_bar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(
label="Documentation [F1]", # Open GitHub wiki
command=lambda: webbrowser.open(
"https://github.com/jlw4049/FFMPEG-Audio-Encoder/wiki"
),
)
root.bind(
"<F1>",
lambda event: webbrowser.open(
"https://github.com/jlw4049/FFMPEG-Audio-Encoder/wiki"
),
) # Hotkey
help_menu.add_command(
label="Project Page", # Open GitHub project page
command=lambda: webbrowser.open("https://github.com/jlw4049/FFMPEG-Audio-Encoder"),
)
help_menu.add_command(
label="Report Error / Feature Request", # Open GitHub tracker link
command=lambda: webbrowser.open(
"https://github.com/jlw4049/FFMPEG-Audio-Encoder/" "issues/new/choose"
),
)
help_menu.add_separator()
help_menu.add_command(
label="Info", command=lambda: openaboutwindow(main_root_title)
) # Opens about window
# --------------------------------------------------------------------------------------------- Menu Items and Sub-Bars
# # Help Button for FDK -----------------------------------------------------------------------------------------
# def gotofdkaachelp():
# helpfile_window = Toplevel()
# helpfile_window.title("FDK-AAC Advanced Settings Help")
# helpfile_window.configure(background="#434547")
# Label(helpfile_window, text="Advanced Settings Information",
# font=("Times New Roman", 14), background='#434547', foreground="white").grid(column=0, row=0)
# helpfile_window.grid_columnconfigure(0, weight=1)
# helpfile_window.grid_rowconfigure(0, weight=1)
# text_area = scrolledtextwidget.ScrolledText(helpfile_window, width=80, height=25)
# text_area.grid(column=0, pady=10, padx=10)
# with open("Apps/fdkaac/FDK-AAC-Help.txt", "r") as helpfile:
# text_area.insert(INSERT, helpfile.read())
# text_area.configure(font=("Helvetica", 14))
# text_area.configure(state=DISABLED)
#
#
# # ---------------------------------------------------------------------------------------------------- FDK Help
#
# # Help --------------------------------------------------------------------------------------------------------
# def gotoqaachelp():
# helpfile_window = Toplevel()
# helpfile_window.title("QAAC Advanced Settings Help")
# helpfile_window.configure(background="#434547")
# Label(helpfile_window, text="Advanced Settings Information",
# font=("Times New Roman", 14), background='#434547', foreground="white").grid(column=0, row=0)
# helpfile_window.grid_columnconfigure(0, weight=1)
# helpfile_window.grid_rowconfigure(0, weight=1)
# text_area = scrolledtextwidget.ScrolledText(helpfile_window, width=80, height=25)
# text_area.grid(column=0, pady=10, padx=10)
# with open("Apps/qaac/qaac information.txt", "r") as helpfile:
# text_area.insert(INSERT, helpfile.read())
# text_area.configure(font=("Helvetica", 14))
# text_area.configure(state=DISABLED)
#
# # -------------------------------------------------------------------------------------------------------- Help
# Hide/Open all top level window function -----------------------------------------------------------------------------
def hide_all_toplevels():
for widget in root.winfo_children():
if isinstance(widget, Toplevel):
widget.withdraw()
def open_all_toplevels():
for widget in root.winfo_children():
if isinstance(widget, Toplevel):
widget.deiconify()
# ----------------------------------------------------------------------------- Hide/Open all top level window function
# function to check state of root, then deiconify it accordingly ------------------------------------------------------
def advanced_root_deiconify():
if root.winfo_viewable():
root.deiconify()
elif not root.winfo_viewable():
root.iconify()
root.deiconify()
# ------------------------------------------------------ function to check state of root, then deiconify it accordingly
# Calls to show_streams.py show_streams_mediainfo_function to display a window with track information -----------------
def show_streams_mediainfo(): # All audio codecs can call this function in their menu's
show_streams_mediainfo_function(file_input)
# ----------------- Calls to show_streams.py show_streams_mediainfo_function to display a window with track information
# Root Frames ---------------------------------------------------------------------------------------------------------
input_frame = LabelFrame(root, text="Input", labelanchor="nw")
input_frame.grid(
column=0, row=0, columnspan=4, padx=5, pady=(0, 3), sticky=N + S + E + W
)
input_frame.configure(fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold"))
input_frame.grid_rowconfigure(0, weight=1)
for i_f in range(4):
input_frame.grid_columnconfigure(i_f, weight=1)
audio_setting_frame = LabelFrame(root, text="Codec Settings", labelanchor="n")
audio_setting_frame.grid(
column=1, row=1, columnspan=3, padx=5, pady=(0, 3), sticky=N + S + E + W
)
audio_setting_frame.configure(
fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold")
)
audio_setting_frame.grid_rowconfigure(0, weight=1)
audio_setting_frame.grid_columnconfigure(0, weight=1)
audio_setting_frame.grid_columnconfigure(1, weight=1)
audio_setting_frame.grid_columnconfigure(2, weight=1)
start_buttons_frame = LabelFrame(root, text="Job Control", labelanchor="nw")
start_buttons_frame.grid(
column=0, row=3, columnspan=4, padx=5, pady=(0, 3), sticky=N + S + E + W
)
start_buttons_frame.configure(
fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold")
)
start_buttons_frame.grid_rowconfigure(0, weight=1)
for s_b_f in range(4):
start_buttons_frame.grid_columnconfigure(s_b_f, weight=1)
output_frame = LabelFrame(root, text="Output", labelanchor="nw")
output_frame.grid(
column=0, row=2, columnspan=4, padx=5, pady=(0, 3), sticky=N + S + E + W
)
output_frame.configure(fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold"))
output_frame.grid_rowconfigure(0, weight=1)
for o_f in range(4):
output_frame.grid_columnconfigure(o_f, weight=1)
# --------------------------------------------------------------------------------------------------------- Root Frames
# File Auto Save Function ---------------------------------------------------------------------------------------------
def set_auto_save_suffix():
global file_out, autofilesave_dir_path
func_parser = ConfigParser()
func_parser.read(config_file)
autofilesave_file_path = pathlib.Path(
file_input
) # Command to get file input location
saved_dir = func_parser["output_path"]["path"]
if saved_dir != "file input directory" and pathlib.Path(saved_dir).is_dir():
autofilesave_dir_path = saved_dir
elif saved_dir == "file input directory":
autofilesave_dir_path = autofilesave_file_path.parents[
0
] # Final command to get only the directory
if encoder.get() != "Set Codec":
convert_filename = (
f"{str(autofilesave_dir_path)}/{str(pathlib.Path(file_input).name)}"