-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVideoScripy.py
More file actions
1944 lines (1593 loc) · 62.7 KB
/
VideoScripy.py
File metadata and controls
1944 lines (1593 loc) · 62.7 KB
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
# built-in
import subprocess
import json
import re
from threading import Thread
from pathlib import Path
from datetime import timedelta, datetime
from shutil import rmtree
from os import walk, mkdir, remove, listdir, getcwd, rmdir, rename
from os.path import isdir, isfile
from time import time, sleep
from math import ceil, gcd
from typing import TypedDict
from enum import Enum
# dependencies
from alive_progress import alive_bar
from playsound import playsound
from PIL import Image
import psutil
from colorama import init
init()
# from VideoScripy import *
__all__ = [
'colorAnsi', 'printC',
# dict class
'GPUInfo', 'ProcAsyncReturn',
# dict class
'StreamInfo', 'FrameByte', 'VideoInfo',
# enum class
'VideoProcess',
# main object
'VideoScripy',
# 'run',
]
colorAnsi = {
"reset" : "\x1b[0m",
"red" : "\x1b[31m",
"green" : "\x1b[32m",
"yellow" : "\x1b[33m",
"blue" : "\x1b[34m",
}
def printC(text, color:str=None):
"""
print with color : red green blue yellow
"""
if color is None:
print(text)
return
global colorAnsi
try:
print(colorAnsi[color] + text + colorAnsi["reset"])
except:
print(f'"{color}" not avalable when printing "{text}"')
class GPUInfo(TypedDict):
id : int
name : str
codecs : list
class ProcAsyncReturn(TypedDict):
returnCode : int
stdout: str
class StreamInfo(TypedDict):
index : int
codec_type : str
codec_name : str
selected : bool
language: str
title: str
class FrameByte(TypedDict):
# picture timestamp
pts_time : datetime
# size in byte
size : int
class VideoInfo(TypedDict):
"""
VideoScripy.vList typing
"""
type: str
path: str
name: str
duration: timedelta
bitRate: int
quality: float
width: int
height: int
fps: float
nbFrames: int
streams : list[StreamInfo]
fileSize : int
frameBytePerPacket : list[FrameByte]
frameBytePerSecond : list[FrameByte]
class VideoProcess(Enum):
"""
Implemented processes and its substep
"""
compress = "compress"
resize = "resize"
upscale = ["getFrames", "upscale", "frameToVideo"]
interpolate = ["getFrames", "interpolate", "frameToVideo"]
preview = "preview"
frame = "frame"
stream = "stream"
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
COMPRESS_TOLERENCE (float):
do not compress if compressdBitRate * COMPRESS_TOLERENCE < 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\n
checkGPUs()\n
selectDevice()\n
setEncoder()\n
checkTools()
"""
self.path = getcwd()
self.vList:list[VideoInfo] = []
self.vType = ["mp4","mkv"]
# Real-ESRGAN support format
self.pType = ["png","jpg","jpeg","webp"]
self.aType = ["mp3", "m4a", "aac", "wav"]
self.sType = ["smi", "srt"]
self.scanType = self.vType + self.pType + self.aType + self.sType
self.folderSkip = [p.name for p in VideoProcess]
self.COMPRESS_TOLERENCE = 0.1
self.proc:subprocess.Popen = None
self.killed = False
self.stop_threads = False
self.procAsync:list[subprocess.Popen] = []
self.EXIT_CODE_FILE_NAME = "exitCode.txt"
self.h265 = False
self.gpu = False
self.devices:list[GPUInfo] = []
# TODO missing feature of cheking cpu h265 availability
self.devices.append({
"id" : -1,
"name" : "CPU",
"codecs" : ["H.264/AVC", "H.265/HEVC"],
})
self.checkGPUs()
self.selectedDevice:GPUInfo = None
self.selectDevice()
self.setEncoder(h265=True)
self.checkTools()
self.DAY_ZERO = datetime.strptime("2000/01/01", "%Y/%m/%d")
def checkTools(self) -> None:
"""
Check all tools by running -version or -h with cmd.exe asynchronously.\n
Tool found if returned code is 0 or 4_294_967_295
"""
tools = {
"FFmpeg": "ffmpeg -version",
"FFprobe": "ffprobe -version",
"Real-ESRGAN": "realesrgan-ncnn-vulkan.exe -h",
"IFRNet": "ifrnet-ncnn-vulkan.exe -h",
"NVEncC": "NVEncC64.exe --version",
}
for tool, cmd in tools.items():
self._runProcAsync(cmd)
results = self._runProcAsyncWait()
for tool, result in zip(tools, results):
if result["returnCode"] in [0, 4294967295]:
printC(f'{tool} found', 'green')
else:
printC(f'{tool} not found, please check if it is in environment "PATH"', 'red')
def checkGPUs(self) -> None:
"""
Fill up self.devices by each GPU's info.
"""
# get gpu device
command = "NVEncC64.exe --check-device"
self._runProcAsync(command)
result = self._runProcAsyncWait()[0]
result:list[str] = result["stdout"].decode('utf-8').split("\r\n")
for resultStr in result:
if "DeviceId" in resultStr:
id = re.findall("#.+:", resultStr)[0].replace("#", "").replace(":", "")
try:
id = int(id)
except:
printC("Unexpected int conversion error at self.checkGPUs()", "red")
name = re.split("#.+:", resultStr)[-1].strip()
self.devices.append({
"id" : id,
"name" : name,
"codecs" : [],
})
# get codec of each gpu
for device in self.devices:
# skip CPU
if device["id"] == -1:
continue
command = f'NVEncC64.exe --check-features {device["id"]}'
self._runProcAsync(command)
result = self._runProcAsyncWait()[0]
result = result["stdout"].decode('utf-8').split("\r\n")
for resultStr in result:
if "Codec:" in resultStr:
device["codecs"].append(resultStr.split(":")[-1].strip())
def selectDevice(self, deviceId:int=0) -> None:
"""
Set self.selectedDevice to corresponding element of self.devices.\n
Re setEncoder() with self.h265 as argument.\n
Set self.gpu to True if selected device's id is not -1.\n
If wrong id entered, will use -1 as default which correspond to CPU.\n
"""
# check device id availability
if deviceId not in [device["id"] for device in self.devices]:
printC(f'Wrong device id "{deviceId}" is entered, available id are:', "red")
for device in self.devices:
print(f' {device["id"]} : {device["name"]}')
printC("Using CPU as default device", "yellow")
deviceId = -1
# select device
for device in self.devices:
if deviceId == device["id"]:
self.selectedDevice = device
printC(f'Selecting device {self.selectedDevice["id"]} : {self.selectedDevice["name"]}', "blue")
printC(f'Available codec : {" | ".join(self.selectedDevice["codecs"])}', "blue")
# set gpu state
self.gpu = deviceId != -1
# set encoder according to selected device ability
# print("Need to reset the video encoder")
self.setEncoder(self.h265)
def removeEmptyFolder(self, folderName:str = None):
if folderName is not None:
try:
rmdir(folderName)
except:
pass
else:
for process in [p.name for p in VideoProcess]:
outputFolder = self.path+f'\\{process}'
self.removeEmptyFolder(outputFolder)
def noticeProcessBegin(self):
sound = "./assets/typewriter_carriage_return.mp3"
try:
playsound(sound, block=False)
except:
pass
def noticeProcessEnd(self):
sound = "./assets/typewriter_bell.mp3"
try:
playsound(sound, block=True)
except:
pass
# get video related
def setPath(self, path:str="") -> bool:
"""
Set attributes path, return setting result
Parameters:
path (str):
set to empty "" will use os.getcwd() as default 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) -> bool:
"""
Set attribute vList's path and name by os.walk().\n
Return false if self.path do not exist anymore.
Parameters:
folderDepthLimit (int):
limit the scan depth
"""
# empty video list
self.vList = []
# check path validity
if not isdir(self.path):
printC(f'Path "{self.path}" do not exist', "red")
return False
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:
# skip not supported type
fileFormat = file.split(".")[-1].lower()
if fileFormat not in self.scanType:
continue
# 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'])
return True
def getVideoInfo(self) -> None:
"""
Set attributes vList's stream and video properties with ffprobe asynchronously
"""
# run probe
for video in self.vList:
command = (
f' ffprobe'
f' -i "{video["path"]}"'
f' -show_format'
f' -show_streams'
f' -of json'
)
self._runProcAsync(command)
# wait and retrieve results
results = self._runProcAsyncWait()
for index in range(len(results)-1,-1,-1):
if results[index]['returnCode'] != 0:
printC(f'FFprobe error, remove {self.vList[index]["name"]}', "red")
# delete errored video
self.vList.pop(index)
results.pop(index)
else:
# convert stdout to json format
results[index] = (
json.loads(results[index]['stdout'].decode('utf-8'))
)
# get info
for videoIndex in range(len(self.vList)-1,-1,-1):
try:
streamInfo:list[StreamInfo] = []
videoStream = []
# get stream info
for stream in results[videoIndex]['streams']:
# some subtitle dont has codec_name (mov_text)
try :
codecName = stream["codec_name"]
except:
codecName = stream["codec_tag_string"]
# mkv video stream dont has language tags, needs to be initialized
try :
tagLanguage = stream["tags"]["language"]
except:
tagLanguage = "und"
# use handler_name as title
try :
# mp4
tagTitle = stream["tags"]["handler_name"]
except:
try:
# mkv
tagTitle = stream["tags"]["HANDLER_NAME"]
except:
# others (png)
tagTitle = ""
streamInfo.append({
"index": int(stream["index"]),
"codec_type": stream["codec_type"],
"codec_name": codecName,
"selected": True,
"language": tagLanguage,
"title": tagTitle,
})
if stream['codec_type'] == 'video':
videoStream.append(stream)
# write info
self.vList[videoIndex]['streams'] = streamInfo
self.vList[videoIndex]['fileSize'] = int(results[videoIndex]['format']['size'])
# video
if self.vList[videoIndex]["type"] in self.vType:
# # warn more than 1 video stream
# if len(videoStream) > 1:
# printC(
# f'More than 1 video stream found in "{self.vList[videoIndex]["name"]}", '
# f'only the first will be processed', "yellow"
# )
try:
videoStream = videoStream[0]
self.vList[videoIndex]['width'] = int(videoStream['width'])
self.vList[videoIndex]['height'] = int(videoStream['height'])
num, denom = videoStream['r_frame_rate'].split('/')
self.vList[videoIndex]['fps'] = round(float(num)/float(denom),2)
except:
printC(
f'"{self.vList[videoIndex]["name"]}" typed as video but has no video content',
"yellow"
)
self.vList[videoIndex]["type"] = "other"
# mp4
if self.vList[videoIndex]["type"] == "mp4":
self.vList[videoIndex]['duration'] = timedelta(seconds=float(videoStream['duration']))
self.vList[videoIndex]['bitRate'] = int(videoStream['bit_rate'])
self.vList[videoIndex]['nbFrames'] = int(videoStream['nb_frames'])
self.vList[videoIndex]["quality"] = round(
self.vList[videoIndex]['bitRate']
/(self.vList[videoIndex]['width']*self.vList[videoIndex]["height"]),1
)
# mkv
elif self.vList[videoIndex]["type"] == "mkv":
self.vList[videoIndex]['duration'] = timedelta(seconds=float(results[videoIndex]['format']['duration']))
self.vList[videoIndex]['bitRate'] = int(results[videoIndex]['format']['bit_rate'])
self.vList[videoIndex]['nbFrames'] = ceil(
self.vList[videoIndex]['fps']
* self.vList[videoIndex]['duration'].total_seconds()
)
self.vList[videoIndex]["quality"] = round(
self.vList[videoIndex]['bitRate']
/(self.vList[videoIndex]['width']*self.vList[videoIndex]["height"]),1
)
# picture
elif self.vList[videoIndex]["type"] in self.pType:
self.vList[videoIndex]['duration'] = timedelta(seconds=0)
self.vList[videoIndex]['bitRate'] = 0
self.vList[videoIndex]['nbFrames'] = 1
self.vList[videoIndex]['width'] = int(videoStream[0]['width'])
self.vList[videoIndex]['height'] = int(videoStream[0]['height'])
self.vList[videoIndex]['fps'] = 1.0
self.vList[videoIndex]["quality"] = 0.0
# audio
elif self.vList[videoIndex]["type"] in self.aType:
self.vList[videoIndex]['duration'] = timedelta(seconds=float(results[videoIndex]['format']['duration']))
self.vList[videoIndex]['bitRate'] = int(results[videoIndex]['format']['bit_rate'])
self.vList[videoIndex]['nbFrames'] = 0
self.vList[videoIndex]['width'] = 0
self.vList[videoIndex]['height'] = 0
self.vList[videoIndex]['fps'] = 0.0
self.vList[videoIndex]["quality"] = 0.0
# subtitle and other
elif self.vList[videoIndex]["type"] in self.sType + ["other"]:
self.vList[videoIndex]['duration'] = timedelta(seconds=0)
self.vList[videoIndex]['bitRate'] = 0
self.vList[videoIndex]['nbFrames'] = 0
self.vList[videoIndex]['width'] = 0
self.vList[videoIndex]['height'] = 0
self.vList[videoIndex]['fps'] = 0.0
self.vList[videoIndex]["quality"] = 0.0
else:
printC(
f'Uncovered type "{self.vList[videoIndex]["type"]}" at "{self.vList[videoIndex]["name"]}"',
"red"
)
except Exception as e:
printC(f'Unexpected erro "{e.with_traceback(None)}"', "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)} file info")
# ffmpeg encoder related
def setEncoder(self, h265=True) -> None:
"""
Set encoder parameters according h265 and GPU usage.\n
Make sure to be called after self.checkGPUs() and self.selectDevice().
Parameters:
h265 (bool):
_
"""
# check h265 possibility
if (h265) and ("265" not in " ".join(self.selectedDevice["codecs"])):
printC("Selected device do not has H265 video encoder", "yellow")
h265 = False
# summary
self.h265 = h265
printC(f'Using {"(h265)" if h265 else "(h264)"} and {"(gpu)" if self.gpu else "(cpu)"} as video encoder', "blue")
# cpu
if not self.gpu:
if not h265:
self.encoder = ' libx264 -crf 1'
else:
self.encoder = ' libx265 -crf 0'
self.encoder += (
' -preset medium'
)
# gpu
else:
if not h265:
self.encoder = ' h264_nvenc -b_ref_mode middle'
else:
self.encoder = ' hevc_nvenc -weighted_pred 1'
self.encoder += (
f' -gpu {self.selectedDevice["id"]}'
' -preset p6'
' -tune hq'
' -rc vbr'
' -rc-lookahead 32'
' -multipass fullres'
' -spatial_aq 1'
' -cq 1'
)
def _getCommand(self, video:VideoInfo, process:str, substep='') -> str:
"""
Return shell script according to videoInfo and process.\n
Grouped in one function to handle ffmpeg command together.
Parameters:
video (VideoInfo):
element of vList
process (str):
VideoProcess.[process].name
"""
videoPath = video['path']
videoName = video['name']
videoFps = video['fps']
if substep == 2 and process == VideoProcess.interpolate.name:
videoFps = video["interpolateFps"]
hwaccel = ''
if self.gpu:
hwaccel = (
' -hwaccel cuda'
f' -hwaccel_device {self.selectedDevice["id"]}'
' -hwaccel_output_format cuda'
)
# set communFFmpegOut
communFFmpegOut = (
f' -c:v copy -c:a copy -c:s copy'
f' -c:v:0 {self.encoder} {video["compressBitRateParam"]}'
f' -r {videoFps}'
f' -y'
f' "{process}\\{videoName}"'
)
if process == VideoProcess.compress.name:
command = (
f' ffmpeg'
f' {hwaccel}'
f' -i "{videoPath}"'
f' -map 0:v -map 0:a? -map 0:s?'
f' {communFFmpegOut}'
)
elif process == VideoProcess.resize.name:
resizeFilter = "scale"
if self.gpu:
resizeFilter = "scale_cuda"
command = (
f' ffmpeg'
f' {hwaccel}'
f' -i "{videoPath}"'
f' -map 0:v -map 0:a? -map 0:s?'
f' -filter:v:0 {resizeFilter}={video["resizeWidth"]}:{video["resizeHeight"]}'
f' {communFFmpegOut}'
)
elif process in [VideoProcess.upscale.name, VideoProcess.interpolate.name]:
if substep == 0:
command = (
f' ffmpeg'
f' -i "{videoPath}"'
f' -qscale:v 1 -qmin 1 -qmax 1 -y'
f' -r {videoFps}'
f' "{video["getFramesOutputPath"]}/frame%08d.jpg"'
)
else:
gpuNumber = 0
if self.gpu:
gpuNumber = self.selectedDevice["id"]+1
if process == VideoProcess.upscale.name:
processOutputPath = video["upscaleOutputPath"]
upscaleFactor = video["upscaleFactor"]
elif process == VideoProcess.interpolate.name:
processOutputPath = video["interpolateOutputPath"]
if substep == 1 and process == VideoProcess.upscale.name:
command = (
f' realesrgan-ncnn-vulkan.exe'
f' -i "{video["getFramesOutputPath"]}"'
f' -o "{processOutputPath}"'
)
if upscaleFactor in [2,3,4]:
command += f' -n realesr-animevideov3 -s {upscaleFactor}'
elif upscaleFactor == "4p":
command += ' -n realesrgan-x4plus'
elif upscaleFactor == "4pa":
command += ' -n realesrgan-x4plus-anime'
else:
printC(f'Unknown upscale factor "{upscaleFactor}"', "red")
return None
command += (
f' -f jpg -g {gpuNumber}'
)
elif substep == 1 and process == VideoProcess.interpolate.name:
command = (
f' ifrnet-ncnn-vulkan.exe'+
f' -i "{video["getFramesOutputPath"]}"'+
f' -o "{processOutputPath}"'+
f' -m IFRNet_GoPro -g {gpuNumber} -f frame%08d.jpg'+
f' -n {video["interpolateFrame"]}'
)
elif substep == 2:
# ffmpeg -decoders
imgDecoder = "mjpeg"
if self.gpu:
imgDecoder = "mjpeg_cuvid"
command = (
f' ffmpeg'
f' {hwaccel}'
f' -i "{videoPath}"'
f' {hwaccel}'
f' -c:v {imgDecoder} -r {videoFps}'
f' -i "{processOutputPath}/frame%08d.jpg"'
f' -map 1:v:0 -map 0:a? -map 0:s?'
f' {communFFmpegOut}'
)
else:
printC(f'Unknown video process "{process}"', "red")
return None
return command
# run process related
def killProc(self) -> None:
"""
Kill and stop running process of _runProc() and _runProcAsync().\n
Set self.killed to True if correctly killed.
"""
if self.proc != None:
parent = psutil.Process(self.proc.pid)
for child in parent.children(recursive=True):
child.kill()
self.killed = True
if self.procAsync != []:
for procAsync in self.procAsync:
parent = psutil.Process(procAsync.pid)
for child in parent.children(recursive=True):
child.kill()
self.killed = True
def _runProc(self, command:str, processName='', silence=False) -> bool:
"""
Warp shell script then run it in a minimized and realtime cmd.exe,
wait till its end and check its exit code.\n
Return True if exit code is 0 or -1, else False.
Parameters:
command (str):
command line script
processName (str):
name shown on the cmd.exe
silence (str):
don't print time took and exit code check
"""
processTime = time()
printC(f'Running process : {processName}', "blue")
commandWarped = (
f' start "VideoScripy-{processName}" /I /min /wait /realtime'
f' cmd /v:on /c " {self.path[0]}:'
f' & cd {self.path}'
f' & {command}'
f' & echo ^!errorLevel^! > {self.EXIT_CODE_FILE_NAME}"'
)
self.killed = False
self.proc = subprocess.Popen(
commandWarped,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
self.proc.communicate()
self.proc = None
if not silence:
processTime = time() - processTime
processTime = timedelta(seconds=processTime)
print(f"Took : {str(processTime)[:-3]}")
return self._checkExitCode(silence)
def _checkExitCode(self, silence=False) -> bool:
"""
Open EXIT_CODE_FILE_NAME file to get process returned code.\n
Return True if 0 or -1, else False.
Parameters:
silence (str):
don't print exit code check
"""
filePath = self.path+f'\\{self.EXIT_CODE_FILE_NAME}'
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")
# real esrgan can not read/write special character named folder/file eg: ⋟﹏⋞
if returnCode == -1073740791:
printC(f'Real-ESRGAN can not read/write special character named folder/file eg: ⋟﹏⋞', "red")
return False
def _runProcAsync(self, command:str) -> None:
"""
Run shell script in a hidden "cmd.exe".\n
Warning ! Output path must be absolute.\n
Must call _runProcAsyncWait() to get its return code and content.
Parameters:
command (str):
shell script command, _getCommand return command
"""
self.killed = False
self.procAsync.append(
subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
)
def _runProcAsyncWait(self) -> list[ProcAsyncReturn]:
"""
Wait all "asynchronous" process.\n
Return list of process's {returnCode, stdout}
"""
result:list[ProcAsyncReturn] = []
for proc in self.procAsync:
out, _ = proc.communicate()
result.append({
"returnCode": proc.returncode,
"stdout": out,
})
self.procAsync.clear()
return result
def _frameWatch(self, outDir:str, total:int) -> None:
"""
Track video frame process with progress bar in while loop,
Set attribute self.stop_threads to True to stop.
Parameters:
outDir (str):
process output directory, where progress increase
total (int):
when to stop
"""
self.stop_threads = False
# wait 1s to avoid print overlap with "Running process"
sleep(1)
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(1)
progressed = len(listdir(outDir)) - alreadyProgressed
bar(progressed - progressedPrev)
progressedPrev = progressed
if self.stop_threads:
break
progressed = len(listdir(outDir)) - alreadyProgressed
bar(progressed - progressedPrev)
progressedPrev = progressed
def _frameWatchStart(self, outDir:str, total:int) -> None:
"""
Run _frameWatch() in a thread.
Parameters:
outDir (str):
process output directory, where progress increase
total (int):
when to stop
"""
self.watch = Thread(
target=self._frameWatch,
args=(outDir, total)
)
self.watch.start()
def _frameWatchStop(self) -> None:
"""
Stop the _frameWatch() thread by setting attribute self.stop_threads to True.
"""
self.stop_threads = True
while self.watch.is_alive():
pass
# video process related
def _getFrames(self, video:VideoInfo, process:VideoProcess) -> bool:
"""
Transform video to frames
Parameters:
video (VideoInfo):
element of vList
"""
getFramesOutputPath = video["getFramesOutputPath"]
# check if get frame is necessary
if isdir(getFramesOutputPath):
# get number of frames, 3rd round
if isdir(f'{getFramesOutputPath}\\processed'):
obtainedFrames = (
len(listdir(getFramesOutputPath)) - 1
+ len(listdir(f'{getFramesOutputPath}\\processed'))
)
# get number of frames, less than 3rd round
else:
obtainedFrames = len(listdir(getFramesOutputPath))
# equal to what it should has, allow +- 1 frame difference
if abs(obtainedFrames - video["nbFrames"]) <= 1:
printC("No need to get frames", "yellow")
self.killed = False
return True
else:
printC("Missing frames, regenerate frames needed", "yellow")
rmtree(getFramesOutputPath)
# create new temporary frames folder
mkdir(getFramesOutputPath)
command = self._getCommand(video, process.name, substep=0)
result = self._runProc(command, process.value[0])
# check frames count
obtainedFrames = len(listdir(getFramesOutputPath))
if obtainedFrames != video["nbFrames"]:
printC(
f'Warning, obtained frames {obtainedFrames} '
f'is not equal to video frames {video["nbFrames"]}',
"yellow"
)
# modify frame number if +- 1 frame difference
if abs(video["nbFrames"] - obtainedFrames) <= 1:
video["nbFrames"] = obtainedFrames
return result
def pre_compress(self, video:VideoInfo, width:int, height:int, quality:float) -> bool:
"""
Compute compressBitRate and compressBitRateParam, to limit video bit rate\n
Return True if compression is needed else False
Parameters:
video (VideoInfo):
element of vList