This repository has been archived by the owner on Jul 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
media.py
345 lines (287 loc) · 8.19 KB
/
media.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
import os, re, hashlib, subprocess, json, threading, multiprocessing
from concurrent.futures.thread import ThreadPoolExecutor
from ffmpeg import FFMpeg
#Allowed video extensions
videxts = (
".webm",
".mkv",
".flv",
".vob",
".ogv",".ogg",
".drc",
".mng",
".avi",
".mts",".m2ts",".ts",
".mov",".qt",
".wmv",
".yuv",
".rm",
".rmvb",
".asf",
".amv",
".mp4",".m4p",".m4v",
".mpg",".mp2",".mpeg",".mpe",".mpv",
".m2v",
".svi",
".3gp",
".3g2",
".mxf",
".roq",
".nsv",
".flv",".f4v",".f4p",".f4a",".f4b",
".gifv", #This is just a covername for a videotype, gifv is not a real media container type
)
#Allowed image extensions
imgexts = (
".tif",".tiff",
".bmp",
".jpg",".jpeg",".jp2",".jpx",".mjpeg",".jfif",
".gif",
".png",".apng",
".eps",
".raw",".cr2",".nef",".orf",".sr2",
".heic",".hevc",
)
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
def getext(name):
return name[name.rfind("."):].lower()
def ffprobe(file):
try:
return json.loads(subprocess.check_output([
"ffprobe",
"-show_format",
"-show_streams",
"-loglevel", "quiet",
"-print_format", "json",
file
]).decode("utf-8"))
except subprocess.CalledProcessError as e:
return None
#Global variables LOL
service_folder = None
thumbnail_height = None
probes_folder = None
thumbnails_folder = None
codes_folder = None
avc_table = None
hevc_table = None
class MediaFile:
def __init__(self, path, hash):
self.path = path
self.hash = hash
self.data = None
self.stored = os.path.join(probes_folder, self.hash) + ".json"
def scan(self):
if (self.data != None):
return
if (os.path.exists(self.stored)):
with open(self.stored, "r") as f:
self.data = json.load(f)
else:
self.data = ffprobe(self.path)
if (self.data == None):
return
with open(self.stored, "w") as f:
json.dump(self.data, f)
self.generateThumbnail()
def generateThumbnail(self):
self.scan()
return NotImplemented
def getSize(self):
self.scan()
width = 0
height = 0
if (self.data == None):
return (0,0)
for i in self.data["streams"]:
if (i["codec_type"] == "video"):
width = i["width"]
height = i["height"]
break
return (width, height)
def getThumbnailPath(self):
self.scan()
self.generateThumbnail()
return os.path.join(thumbnails_folder, self.hash + ".jpeg")
def getPath(self):
return self.path
def start(self):
self.scan()
return NotImplemented
class VideoFile(MediaFile):
def __init__(self, path, hash):
super().__init__(path, hash)
def generateThumbnail(self):
super().generateThumbnail()
file=os.path.join(thumbnails_folder, self.hash + ".png")
file2=os.path.join(thumbnails_folder, self.hash + ".jpeg")
if (os.path.exists(file2)):
return
#TODO: Remove this and only use convert, just set frame to fps*10
time = 10
dur = int(eval(self.data["format"]["duration"]))
if (dur <= time):
time = int(dur/2)
if (not os.path.exists(file2)):
#Extract frame
res = subprocess.run([
"ffmpeg",
"-i", self.path,
"-ss", str(time), #10 seconds in
"-vframes", "1",
file
])
if (res.returncode == 1):
print(self.hash + "'s media is invalid!")
else:
#Resize and convert
os.system("magick {0} -geometry x{1} {2} && rm -rf {0}".format(
file,
thumbnail_height,
file2
)
)
def getScriptPath(self):
#TODO: Shorten, at some point
file_path = self.getPath()
script_input = file_path[:file_path.rfind(".")]
#TODO: ini and json support
if (os.path.exists(script_input + ".csv")):
return script_input + ".csv"
elif (os.path.exists(script_input + ".funscript")):
return script_input + ".funscript"
else:
return None
def isHandy(self):
return self.getScriptPath() != None
def start(self, request):
super().start()
inst = FFMpeg(self, request.user_agent, codes_folder, avc_table, hevc_table)
inst.process(request)
#TODO: Should the media itself keep track of the instances it has started?
#Probably
#Later
#This would require us to remove this start and ask the MediaDirectory class to start a file
return inst
class ImageFile(MediaFile):
def __init__(self, path, hash):
super().__init__(path, hash)
#TODO: "convert test.heic json:"?
def generateThumbnail(self):
super().generateThumbnail()
file=os.path.join(thumbnails_folder, self.hash + ".jpeg")
if (os.path.exists(file)):
return
if (not os.path.exists(file)):
res = subprocess.run([
"magick",
self.path + "[0]", #[0] is for gif support
"-geometry", "x{}".format(thumbnail_height),#25x = 25 width, x25 = 25 height
file
])
if (res.returncode == 1):
print(self.hash + "'s media is invalid!")
class MediaDirectory:
def __init__(self, folders, service_folder_l, thumbnail_height_l, should_preprobe, avc_tbl, hevc_tbl):
global service_folder
global thumbnail_height
global probes_folder
global thumbnails_folder
global codes_folder
global avc_table
global hevc_table
service_folder = service_folder_l
thumbnail_height = thumbnail_height_l
probes_folder = os.path.join(service_folder, "media_probes")
thumbnails_folder = os.path.join(service_folder, "covers")
codes_folder = os.path.join(service_folder, "encodes")
avc_table = avc_tbl
hevc_table = hevc_tbl
try:
os.makedirs(probes_folder)
except:
pass
try:
os.makedirs(thumbnails_folder)
except:
pass
try:
os.makedirs(codes_folder)
except:
pass
self.folders = folders
self.file_browser = None
self.video_files = None
self.image_files = None
self.scanning_thread = None
self.should_preprobe = should_preprobe
self.scan()
print("Ready!")
def scan(self):
if (self.scanning_thread != None and self.scanning_thread.is_alive()):
return True
self.file_browser = {}
self.video_files = {}
self.image_files = {}
for i in self.folders:
name = i[i.rfind("/")+1:]
self.file_browser[name] = {}
self._traverse(self.file_browser[name],i)
if (self.should_preprobe):
self.scanning_thread = threading.Thread(target=self.preprobe, args=())
self.scanning_thread.start()
return False
def preprobe(self):
#TODO: max_workers should be amount of cores
with ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
for i in self.video_files:
executor.submit(self.video_files[i].scan)
for i in self.image_files:
executor.submit(self.image_files[i].scan)
for i in os.listdir(probes_folder):
path = os.path.join(probes_folder, i)
hash = i[:i.rfind(".")]
if not hash in self.video_files and not hash in self.image_files:
os.remove(path)
for i in os.listdir(thumbnails_folder):
path = os.path.join(thumbnails_folder, i)
hash = i[:i.rfind(".")]
if not hash in self.video_files and not hash in self.image_files:
os.remove(path)
def _traverse(self,dict,folder):
lsdir = os.listdir(folder)
lsdir.sort(key=natural_keys)
for name in lsdir:
path = os.path.join(folder,name)
if (os.path.isfile(path)):
ext = getext(name)
#Python sha256 is really slow LUL
#Should switch back to sha1
#TODO: Multi platform support (fix slashes between unix and windows)
#Maybe by going by each seperator and feeding sha256
#Also other places
hash = hashlib.sha256(path.encode("utf8")).hexdigest()
if (ext in videxts):
dict[name] = hash
self.video_files[hash] = VideoFile(path, hash)
elif (ext in imgexts):
dict[name] = hash
self.image_files[hash] = ImageFile(path, hash)
else:
dict[name] = {}
self._traverse(dict[name],path)
def getMedia(self, hash):
if hash in self.video_files:
return self.video_files[hash]
elif hash in self.image_files:
return self.image_files[hash]
else:
return None