-
Notifications
You must be signed in to change notification settings - Fork 0
/
VideoScripy.py
1253 lines (1003 loc) · 37 KB
/
VideoScripy.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
# dependencies
from alive_progress import alive_bar
from colorama import init, Fore, Style
import psutil
init()
# built-in
import subprocess
import json
from threading import Thread
from pathlib import Path
from datetime import timedelta
from shutil import rmtree
from os import walk, mkdir, remove, listdir, getcwd, rmdir
from os.path import isdir, isfile
from time import time, sleep
from playsound import playsound
from math import ceil
from typing import TypedDict
from enum import Enum
from math import ceil
# from VideoScripy import *
__all__ = ['VideoScripy', 'run']
class VideoInfo(TypedDict):
"""
VideoScripy.vList typing
"""
type: str
path: str
name: str
duration: timedelta
bitRate: int
width: int
height: int
fps: float
nbFrames: int
class VideoProcess(Enum):
optimize = "optimize"
resize = "resize"
getFrames = "getFrames"
upscale = "upscale"
interpolate = "interpolate"
merge = "merge"
def printC(text, color:str=None):
if color == "red":
print(Fore.RED, end='')
elif color == "green":
print(Fore.GREEN, end='')
elif color == "blue":
print(Fore.BLUE, end='')
elif color == "yellow":
print(Fore.YELLOW, end='')
else:
pass
print(text + Style.RESET_ALL)
def removeEmptyFolder(folderName:str):
try:
rmdir(folderName)
except:
pass
def noticeProcessBegin():
sound = "./assets/typewriter_carriage_return.mp3"
try:
playsound(sound, block=False)
except:
pass
def noticeProcessEnd():
sound = "./assets/typewriter_bell.mp3"
try:
playsound(sound, block=True)
except:
pass
def frameWatch(outDir:str, total:int):
"""
Track video frame process with progress bar,
Set global variable stop_threads to True to stop.
Parameters:
outDir (str):
process output directory, where progress increase
total (int):
when to stop
"""
global stop_threads
stop_threads = False
alreadyProgressed = len(listdir(outDir))
restToProgress = total - alreadyProgressed
print(f"Already progressed : {alreadyProgressed}/{total}")
print(f"Remain to progress : {restToProgress}/{total}")
progressedPrev = 0
with alive_bar(total) as bar:
if alreadyProgressed != 0:
bar(alreadyProgressed, skipped=True)
while len(listdir(outDir)) < total:
sleep(0)
progressed = len(listdir(outDir)) - alreadyProgressed
bar(progressed - progressedPrev)
progressedPrev = progressed
if stop_threads:
break
else:
progressed = len(listdir(outDir)) - alreadyProgressed
bar(progressed - progressedPrev)
progressedPrev = progressed
class VideoScripy():
"""
Class for video processesing
Attributes:
path (str):
absolute folder path of running script
vList ([VideoInfo]):
list of dictionnary contanning info of scanned videos
such as path, duration, bit rate etc.
vType ([str]):
supported video type are .mp4 and .mkv
folderSkip ([str]):
self generated folders, skiped when scanning
optimizationTolerence (float):
do not optimize if optimizedBitRate * optimizationTolerence < bitRate
highQualityParam (str):
hevc_nvenc high quality parameters
proc (subprocess.Popen):
running video process : ffmpeg, Real-ESRGAN, or Ifrnet
killed (bool):
indicate that kill video process is done
"""
def __init__(self) -> None:
"""
Initialise attributes
"""
self.path = getcwd()
self.vList:list[VideoInfo] = []
self.vType = ["mp4","mkv"]
self.folderSkip = [p.value for p in VideoProcess]
self.optimizationTolerence = 1.15
self.h265 = True
self.gpu = True
self.setEncoder(h265=True, gpu=True)
self.proc = None
self.killed = False
self.exitCodeFileName = "exitCode.txt"
self.checkTools()
def checkTools(self):
tools = {
"FFmpeg": "ffmpeg -version",
"FFprobe": "ffprobe -version",
"Real-ESRGAN": "realesrgan-ncnn-vulkan.exe -h",
"IFRNet": "ifrnet-ncnn-vulkan.exe -h",
}
prefix = 'start "checkTools" /min /wait cmd /v:on /c " '
sufix = f' & echo ^!errorLevel^! > {self.exitCodeFileName}"'
for tool, cmd in tools.items():
proc = subprocess.Popen(
prefix+cmd+sufix,
cwd=self.path,
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
proc.communicate()
result = self._checkExitCode(silence=True)
if result:
printC(f'{tool} found', 'green')
else:
printC(f'{tool} not found, please check if it is correctly installed', 'red')
# get video related
def setPath(self, path:str="") -> bool:
"""
Set attributes path, return setting result
Parameters:
path (str):
set to "" will use getcwd() as default path
Used attributes:
path
"""
if path == "":
self.path = getcwd()
printC(f'Path set to default "{self.path}"', "green")
return True
else:
if isdir(path):
self.path = path
printC(f'Path correctly set to "{self.path}"', "green")
return True
else:
printC(f'Path "{path}" do not exist', "red")
return False
def getVideo(self, folderDepthLimit:int=0) -> None:
"""
Set attributes vList's path and name by file scan
Parameters:
folderDepthLimit (int):
limit the scan depth
Used attributes:
path
vList
vType
folderSkip
"""
# empty video list
self.vList = []
for root, _, files in walk(self.path):
# get current root's depth
currentDepth = len(root.replace(self.path,"").split("\\"))-1
# skip too deep folder
if currentDepth > folderDepthLimit and folderDepthLimit != -1:
continue
# skip folder
skip = False
for folderSkip in self.folderSkip:
if Path(root).name == folderSkip:
printC(f'Self generated folder "{folderSkip}" skiped', "yellow")
skip = True
break
if skip:
continue
# get videos
for file in files:
fileFormat = file.split(".")[-1].lower()
if fileFormat in self.vType:
# check &
if "&" in root+"\\"+file:
printC(f'"&" must not used in path or file name', "yellow")
printC(f'Skipped "{file}"', "yellow")
continue
self.vList.append({
"type" : fileFormat,
"path" : root+"\\"+file,
"name" : (root+"\\"+file).replace(self.path+'\\','').replace('\\','__')
})
# stop scan for perfomance
if folderDepthLimit == 0:
break
# order by name
self.vList.sort(key= lambda video: video['name'])
def getVideoInfo(self) -> None:
"""
Set attributes vList's video properties with ffmpeg probe
Used attributes:
vList
"""
def probeProcess(fileName) -> subprocess.Popen:
command = [
'ffprobe', '-show_format', '-show_streams',
'-of', 'json', fileName
]
return subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# run probe
processes = []
for videoIndex in range(len(self.vList)-1,-1,-1):
processes.append(probeProcess(self.vList[videoIndex]["path"]))
processes.reverse()
# wait and retrieve results
results = []
for processIndex in range(len(processes)-1,-1,-1):
out, err = processes[processIndex].communicate()
if processes[processIndex].returncode != 0:
print(f'FFprobe error, remove {self.vList[processIndex]["name"]}')
# delete errored video
self.vList.pop(processIndex)
else:
results.append(json.loads(out.decode('utf-8')))
results.reverse()
# get info
for videoIndex in range(len(self.vList)-1,-1,-1):
try:
# get first video stream info
# TODO add multiple video stream waring
videoStreamTemp = [
streams for streams in results[videoIndex]['streams']
if streams['codec_type'] == 'video'
][0]
# write info
self.vList[videoIndex]['duration'] = timedelta(seconds=float(videoStreamTemp['duration']))
self.vList[videoIndex]['bitRate'] = int(videoStreamTemp['bit_rate'])
self.vList[videoIndex]['width'] = int(videoStreamTemp['width'])
self.vList[videoIndex]['height'] = int(videoStreamTemp['height'])
num, denom = videoStreamTemp['r_frame_rate'].split('/')
self.vList[videoIndex]['fps'] = round(float(num)/float(denom),2)
self.vList[videoIndex]['nbFrames'] = int(videoStreamTemp['nb_frames'])
except Exception as e:
printC(e, "red")
printC(f'Can not get video info of "{self.vList[videoIndex]["name"]}"', "red")
# delete errored video
self.vList.pop(videoIndex)
print(f"Get {len(self.vList)} video info")
# ffmpeg encoder related
def setEncoder(self, h265=True, gpu=True):
"""
Set encoder parameters according h265 and GPU usage
Parameters:
h265 (bool):
_
gpu (bool):
_
Used attributes:
h265
gpu
encoder
"""
self.h265 = h265
self.gpu = gpu
if not gpu:
if not h265:
self.encoder = ' libx264 -crf 1'
else:
self.encoder = ' libx265 -crf 0'
self.encoder += (
' -preset medium'
)
else:
if not h265:
self.encoder = ' h264_nvenc -b_ref_mode middle'
else:
self.encoder = ' hevc_nvenc -weighted_pred 1'
self.encoder += (
' -preset p6'
' -tune hq'
' -rc vbr'
' -rc-lookahead 32'
' -multipass fullres'
' -spatial_aq 1'
' -cq 1'
)
def _getFFmpegCommand(
self, video:VideoInfo, process:str,
commandInputs:str=None, commandMap:str=None, commandMetadata:str=None,
) -> str:
command = (
f'start "VideoScripy-{process}" /I /min /wait /realtime'
f' cmd /v:on /c " {self.path[0]}:'
f' & cd {self.path}'
' & ffmpeg'
)
path = video['path']
name = video['name']
fps = video['fps']
if self.gpu:
haccel = ' -hwaccel cuda -hwaccel_output_format cuda'
else:
haccel = ''
if process == VideoProcess.optimize.value:
command += (
f' {haccel}'
f' -i "{path}"'
' -map 0:v -map 0:a? -map 0:s?'
)
elif process == VideoProcess.resize.value:
if self.gpu:
resizeFilter = "scale_cuda"
else:
resizeFilter = "scale"
command += (
f' {haccel}'
f' -i "{path}"'
' -map 0:v -map 0:a? -map 0:s?'
f' -vf {resizeFilter}={video["resizeWidth"]}:{video["resizeHeight"]}'
)
elif process == VideoProcess.getFrames.value:
command += (
f' -i "{path}"'
' -qscale:v 1 -qmin 1 -qmax 1 -y'
f' -r {fps}'
f' "{video["getFramesOutputPath"]}/frame%08d.jpg"'
f' & echo ^!errorLevel^! > {self.exitCodeFileName}"'
)
return command
elif process in [VideoProcess.upscale.value, VideoProcess.interpolate.value]:
if process == VideoProcess.upscale.value:
processOutputPath = video["upscaleOutputPath"]
elif process == VideoProcess.interpolate.value:
processOutputPath = video["interpolateOutputPath"]
fps = video["interpolateFps"]
command += (
f' {haccel}'
f' -i "{path}"'
f' {haccel}'
f' -c:v mjpeg_cuvid -r {fps}'
f' -i "{processOutputPath}/frame%08d.jpg"'
' -map 1:v:0 -map 0:a? -map 0:s?'
)
elif process == VideoProcess.merge.value:
command += (
f' {commandInputs}'
f' {commandMap}'
' -c copy'
f' {commandMetadata}'
f' -y'
f' "{process}\\{name}"'
f' & echo ^!errorLevel^! > {self.exitCodeFileName}"'
)
return command
else:
printC(f'Unknown video process "{process}"', "red")
return None
command += (
f' -c:v copy -c:a copy -c:s copy'
f' -c:v:0 {self.encoder} {video["optimizeBitRateParam"]}'
f' -r {fps}'
f' -y'
f' "{process}\\{name}" '
f' & echo ^!errorLevel^! > {self.exitCodeFileName}"'
)
return command
# video process related
def killProc(self) -> None:
"""
Kill and stop running video process,
Only set killed to True if no running video process.
Used attributes:
killed
proc
"""
if self.proc != None:
parent = psutil.Process(self.proc.pid)
for child in parent.children(recursive=True):
child.kill()
self.killed = True
def _runProc(self, command:str) -> bool:
"""
Run shell script and wait till its end
Parameters:
command (str):
command line script
Used attributes:
killed
proc
"""
processTime = time()
self.killed = False
self.proc = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
self.proc.communicate()
self.proc = None
processTime = time() - processTime
processTime = timedelta(seconds=processTime)
print(f"Took :{str(processTime)[:-3]}")
return self._checkExitCode()
def _checkExitCode(self, silence=False) -> bool:
filePath = self.path+f'\\{self.exitCodeFileName}'
if not isfile(filePath):
if not silence:
printC("Process stoped", "red")
return False
else:
with open(filePath, "r") as f:
returnCode = int(f.readline().replace("\n",""))
remove(filePath)
if returnCode in [0, -1]:
if not silence:
printC('Process end correctly', "green")
return True
else:
if not silence:
printC(f'Process end with return code {returnCode}', "red")
return False
def _getFrames(self, video:VideoInfo) -> bool:
"""
Transform video to frames
Parameters:
video (dict):
info of one video. path, name, fps are used
Used attributes:
path
proc
"""
getFramesOutputPath = video["getFramesOutputPath"]
# check if get frame is necessary
if isdir(getFramesOutputPath):
# equal to what it should has
if len(listdir(getFramesOutputPath)) == video["nbFrames"]:
printC("No need to get frames", "yellow")
self.killed = False
return True
# less than what it should has
elif len(listdir(getFramesOutputPath)) < video["nbFrames"]:
printC("Missing frames, regenerate frames needed", "yellow")
rmtree(getFramesOutputPath)
# more than what it should has
elif len(listdir(getFramesOutputPath)) > video["nbFrames"]:
printC("To much frames, regenerate frames needed", "yellow")
rmtree(getFramesOutputPath)
else:
printC("_getFrames() : ???", "red")
# create new temporary frames folder
mkdir(getFramesOutputPath)
command = self._getFFmpegCommand(video, VideoProcess.getFrames.value)
printC(f'Getting Frames', "green")
result = self._runProc(command)
# check _getFrames accuracy
getedFrames = len(listdir(getFramesOutputPath))
if getedFrames != video["nbFrames"]:
printC(f'Waring, geted frames {getedFrames} != video frames {video["nbFrames"]}', "yellow")
return result
def pre_optimize(self, video:VideoInfo, width:int, height:int, quality:float) -> None:
# compute optimization bit rate
optimizeBitRate = width * height * quality
print(f'{video["bitRate"]/1_000:_.0f} Kbits/s --> {optimizeBitRate/1_000:_.0f} Kbits/s')
video['optimizeBitRate'] = optimizeBitRate
video['optimizeBitRateParam'] = (
f' -maxrate:v {optimizeBitRate}'
f' -bufsize:v {optimizeBitRate*2} '
)
def optimize(self, quality:float=3.0) -> None:
"""
Reduce video bit rate
Parameters:
quality (float):
video bit rate = width x height x quality
Used attributes:
path
vList
optimizationTolerence
highQualityParam
killed
proc
"""
process = VideoProcess.optimize.value
# create output folder
outputFolder = self.path+f'\\{process}'
if not isdir(outputFolder):
mkdir(outputFolder)
for index, video in enumerate(self.vList):
noticeProcessBegin()
name = video['name']
width = video['width']
height = video['height']
bitRate = video['bitRate']
# show current optimizing video
print('--- {}/{} ---'.format(index+1,len(self.vList)))
print(name)
print('{}x{}'.format(width, height))
self.pre_optimize(video, width, height, quality)
# check if optimization needed
if video["optimizeBitRate"] * self.optimizationTolerence > bitRate:
printC('Skipped', "yellow")
continue
command = self._getFFmpegCommand(video, process)
printC(f'Optimizing "{name}"', "green")
self._runProc(command)
if self.killed:
return
removeEmptyFolder(outputFolder)
noticeProcessEnd()
def resize(self, setWidth:int, setHeight:int, quality:float=3.0) -> None:
"""
Resize video
Parameters:
setWidth (int):
-1 to let it by default
setHeight (int):
-1 to let it by default
quality (float):
video bit rate = width x height x quality
Used attributes:
path
vList
highQualityParam
"""
process = VideoProcess.resize.value
# create output folder
outputFolder = self.path+f'\\{process}'
if not isdir(outputFolder):
mkdir(outputFolder)
for index, video in enumerate(self.vList):
noticeProcessBegin()
name = video['name']
width = video['width']
height = video['height']
# show current resizing video
print('--- {}/{} ---'.format(index+1,len(self.vList)))
print(name)
# TODO directly use -1
# compute setWidth and setHeight
if setWidth == -1 and setHeight == -1:
newWidth = width
newHeight = height
elif setWidth == -1:
newWidth = ceil(width * setHeight/height)
newHeight = setHeight
elif setHeight == -1:
newWidth = setWidth
newHeight = ceil(height * setWidth/width)
else:
newWidth = setWidth
newHeight = setHeight
# to positive size
newWidth = abs(newWidth)
newHeight = abs(newHeight)
# even newWidth and newHeight
if newWidth%2 != 0:
newWidth += 1
if newHeight%2 != 0:
newHeight += 1
# ratio warning
if newWidth/newHeight != width/height:
printC('Warning, rize ratio will be changed', "yellow")
print(f'{width}x{height} --> {newWidth}x{newHeight}')
# check if resize needed
if newWidth == width and newHeight == height:
printC("Skipped", "yellow")
continue
video["resizeWidth"] = newWidth
video["resizeHeight"] = newHeight
self.pre_optimize(video, newWidth, newHeight, quality)
command = self._getFFmpegCommand(video, process)
printC(f'Resizing "{name}"', "green")
self._runProc(command)
if self.killed:
return
removeEmptyFolder(outputFolder)
noticeProcessEnd()
def upscale(self, upscaleFactor:int=2, quality:float=3) -> None:
"""
Upscale video
Parameters:
upscaleFactor (int):
2, 3 or 4
quality (float):
video bit rate = width x height x quality
Used attributes:
path
vList
highQualityParam
Used functions/methodes:
_getFrames()
frameWatch()
"""
process = VideoProcess.upscale.value
# create output folder
outputFolder = self.path+f'\\{process}'
if not isdir(outputFolder):
mkdir(outputFolder)
for index, video in enumerate(self.vList):
noticeProcessBegin()
name = video['name']
width = video['width']
height = video['height']
# show current upscaling video
print('--- {}/{} ---'.format(index+1,len(self.vList)))
print(name)
# save and show size change
newWidth = width * upscaleFactor
newHeight = height * upscaleFactor
print(f'{width}x{height} --> {newWidth}x{newHeight}')
self.pre_optimize(video, newWidth, newHeight, quality)
getFramesOutputPath = self.path+'\\{}_tmp_frames'.format(name)
video["getFramesOutputPath"] = getFramesOutputPath
result = self._getFrames(video)
if self.killed:
return
if not result:
continue
upscaleOutputPath = self.path+f'\\{name}_{process}x{upscaleFactor}_frames'
# create upscaled frames folder if not existing
if not isdir(upscaleOutputPath):
mkdir(upscaleOutputPath)
printC(f'Upscaling "{name}"', "green")
# continue existing frames upscale
else:
for _, _, files in walk(upscaleOutputPath):
# remove upscaled frame's origin frames except last two
for framesUpscaled in files[:-2]:
remove(getFramesOutputPath+'\\'+framesUpscaled)
# remove last two upscaled frames
for lastTwoUpscaled in files[-2:]:
remove(upscaleOutputPath+'\\'+lastTwoUpscaled)
printC(f'Continue upscaling "{name}"', "green")
command = (
f'start "VideoScripy-{process}" /min /wait /realtime'+
f' cmd /v:on /c " {self.path[0]}:'+
f' & cd {self.path}'+
' & realesrgan-ncnn-vulkan.exe'+
f' -i "{getFramesOutputPath}"'+
f' -o "{upscaleOutputPath}"'
)
if upscaleFactor in [2,3,4]:
command += f' -n realesr-animevideov3 -s {upscaleFactor}'
# TODO
elif upscaleFactor == "4p":
command += ' -n realesrgan-x4plus'
elif upscaleFactor == "4pa":
command += ' -n realesrgan-x4plus-anime'
else:
printC(f'Unknown upscale factor "{upscaleFactor}"', "red")
return
command += (
' -f jpg -g 1'
f' & echo ^!errorLevel^! > {self.exitCodeFileName}"'
)
# frames watch
watch = Thread(
target=frameWatch,
args=(upscaleOutputPath, video["nbFrames"])
)
watch.start()
result = self._runProc(command)
if not result:
global stop_threads
stop_threads = True
while watch.is_alive():
pass
else:
watch.join()
if self.killed:
return
if not result:
continue
# remove frames
rmtree(getFramesOutputPath)
video["upscaleOutputPath"] = upscaleOutputPath
# upscaled frames to video
command = self._getFFmpegCommand(video, process)
printC(f'Upscaling frame to video "{name}"', "green")
result = self._runProc(command)
if self.killed:
return
if not result:
continue
# remove upscaled frames
rmtree(upscaleOutputPath)
removeEmptyFolder(outputFolder)
noticeProcessEnd()
def interpolate(self, fps:float=30.0, quality:float=3) -> None:
"""
Interpolate video to increase fps
Parameters:
fps (float):
must > than original fps
quality (float):
video bit rate = width x height x quality
Used attributes:
path
vList
highQualityParam
Used functions/methodes:
_getFrames()
frameWatch()
"""
process = VideoProcess.interpolate.value
# create output folder
outputFolder = self.path+f'\\{process}'
if not isdir(outputFolder):
mkdir(outputFolder)
for index, video in enumerate(self.vList):
noticeProcessBegin()
name = video['name']
width = video['width']
height = video['height']
frameRate = video['fps']
duration = video['duration']
# show current resizing video
print('--- {}/{} ---'.format(index+1,len(self.vList)))
print(name)
# check if interpolation needed
if fps < frameRate:
print(fps, '<', frameRate)
printC("Skipped", "yellow")
continue
# save and show interpolate change
interpolateFrame = ceil(duration.total_seconds() * fps)
print(f'{frameRate}fps --> {fps}fps')
self.pre_optimize(video, width, height, quality)
getFramesOutputPath = self.path+'\\{}_tmp_frames'.format(name)
video["getFramesOutputPath"] = getFramesOutputPath
result = self._getFrames(video)
if self.killed:
return
if not result:
continue
interpolateOutputPath = self.path+f'\\{name}_{process}_frames'
# empty interpolate frames folder
if isdir(interpolateOutputPath):
rmtree(interpolateOutputPath)
# new frames interpolate
mkdir(interpolateOutputPath)
command = (
f'start "VideoScripy-{process}" /min /wait /realtime'+
f' cmd /v:on /c " {self.path[0]}:'+
f' & cd {self.path}'+
' & ifrnet-ncnn-vulkan.exe'+
f' -i "{getFramesOutputPath}"'+
f' -o "{interpolateOutputPath}"'+
' -m IFRNet_GoPro -g 1 -f frame%08d.jpg'+
f' -n {interpolateFrame}'
f' & echo ^!errorLevel^! > {self.exitCodeFileName}"'
)
printC(f'Interpolating "{name}"', "green")
# frames watch
watch = Thread(
target=frameWatch,
args=(interpolateOutputPath,interpolateFrame)
)
watch.start()
result = self._runProc(command)
if not result:
global stop_threads
stop_threads = True