-
Notifications
You must be signed in to change notification settings - Fork 25
/
VideoSplitter.cs
440 lines (366 loc) · 18 KB
/
VideoSplitter.cs
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
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Threading;
namespace NotEnoughAV1Encodes.Video
{
class VideoSplitter
{
private Queue.QueueElement queueElement = new();
public void Split(Queue.QueueElement _queueElement, CancellationToken token)
{
queueElement = _queueElement;
Global.Logger("INFO - VideoSplitter.Split()", queueElement.Output + ".log");
if (queueElement.ChunkingMethod == 0)
{
// Equal Chunking
FFmpegChunking(token);
}
else if(queueElement.ChunkingMethod == 1)
{
// PySceneDetect
PySceneDetect(token);
}
}
private void PySceneDetect(CancellationToken _token)
{
Global.Logger("DEBUG - VideoSplitter.Split() => PySceneDetect()", queueElement.Output + ".log");
// Skip Scene Detect if the file already exist
if (!File.Exists(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "splits.txt")))
{
// Detects the Scenes with PySceneDetect
Process pySceneDetect = new();
ProcessStartInfo startInfo = new()
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
FileName = "cmd.exe",
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Apps", "pyscenedetect"),
Arguments = "/C scenedetect -i \"" + queueElement.VideoDB.InputPath + "\" -o \"" + Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier) + '\u0022' + " detect-content -t " + queueElement.PySceneDetectThreshold.ToString() + " list-scenes"
};
pySceneDetect.StartInfo = startInfo;
pySceneDetect.Start();
_token.Register(() => { KillProcessAndChildren(pySceneDetect.Id); });
StreamReader sr = pySceneDetect.StandardError;
while (!sr.EndOfStream)
{
try
{
queueElement.Status = "Splitting - " + sr.ReadLine();
}
catch { }
}
pySceneDetect.WaitForExit();
sr.Close();
if (!_token.IsCancellationRequested)
{
PySceneDetectParse(_token);
}
else
{
Global.Logger("FATAL - Cancellation Requested - Currently in VideoSplitter.Split() => PySceneDetect()", queueElement.Output + ".log");
}
}
else
{
Global.Logger("WARN - VideoSplitter.Split() => PySceneDetect() => File already exist - Resuming?", queueElement.Output + ".log");
}
}
private void PySceneDetectParse(CancellationToken token)
{
List<string> FFmpegArgs = new();
using (TextFieldParser parser = new TextFieldParser(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, Path.GetFileNameWithoutExtension(queueElement.VideoDB.InputPath) + "-Scenes.csv")))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
// KISS
bool firstLine = true;
bool secondLine = true;
while (!parser.EndOfData)
{
//Process row
string[] fields = parser.ReadFields();
if (firstLine)
{
firstLine = false;
continue;
}
if (secondLine)
{
secondLine = false;
continue;
}
int counter = 0;
string seek = "";
foreach (string field in fields)
{
counter++;
if (counter == 4)
{
// Start Time (seconds)
seek = field;
}
if (counter == 10)
{
// Length (seconds)
FFmpegArgs.Add("-ss " + seek + " -t " + field);
counter = 0;
}
}
}
}
// Writes splitting arguments to text file
foreach (string lineArg in FFmpegArgs)
{
using (StreamWriter sw = File.AppendText(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "splits.txt")))
{
sw.WriteLine(lineArg);
sw.Close();
}
}
PySceneTargetVMAFChunking(FFmpegArgs, token);
}
private void PySceneTargetVMAFChunking(List<string> ffmpegArgs, CancellationToken token)
{
// To avoid getting incorrect vmaf values due to ffmpeg seeking issue,
// we have to split the video into chunks
if (!queueElement.Preset.TargetVMAF) return;
if (File.Exists(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "splitted.log")))
{
Global.Logger("WARN - VideoSplitter.Split() => PySceneTargetVMAFChunking() => Skipped Splitting - Resuming?", queueElement.Output + ".log");
return;
}
// Create Chunks Folder
Directory.CreateDirectory(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks"));
Global.Logger("DEBUG - VideoSplitter.Split() => PySceneTargetVMAFChunking() => Path: " + Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks"), queueElement.Output + ".log");
int counter = 0;
int amount = ffmpegArgs.Count() * 2;
foreach (string seek in ffmpegArgs)
{
string ss = seek.Split("-t")[0];
string to = seek.Split(ss)[1];
// Generate Command
string ffmpegCommand = "/C ffmpeg.exe -y " + ss + " -i \"" + queueElement.VideoDB.InputPath + "\" " + to + " -c:v libx264 -preset ultrafast -crf 0" +
" -reset_timestamps 1 -map_metadata -1 -sn -an \"" +
Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks", "split" + counter.ToString("D6") + ".mkv") + "\"";
// Start Splitting
Process chunkingProcess = new();
ProcessStartInfo startInfo = new()
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
RedirectStandardInput = false,
RedirectStandardError = false,
CreateNoWindow = true,
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Apps", "FFmpeg"),
Arguments = ffmpegCommand
};
chunkingProcess.StartInfo = startInfo;
token.Register(() => { try { chunkingProcess.StandardInput.Write("q"); } catch { } });
// Start Process
chunkingProcess.Start();
// Get launched Process ID
int tempPID = chunkingProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.LaunchedPIDs.Add(tempPID);
queueElement.Status = "Splitting - Chunk " + counter.ToString() + "/" + amount.ToString();
// Wait for Exit
chunkingProcess.WaitForExit();
// Get Exit Code
int exit_code = chunkingProcess.ExitCode;
// Remove PID from Array after Exit
Global.LaunchedPIDs.RemoveAll(i => i == tempPID);
counter++;
}
// We repeat the process for max 1s long chunks for later VMAF calculation
int counter_temp = 0;
foreach (string seek in ffmpegArgs)
{
string ss = seek.Split("-t")[0];
double to = Convert.ToDouble(seek.Split("-t")[1]);
string seekto = to.ToString();
// Only use TargetVMAFProbeLength when the chunk is longer than that value
if (to > queueElement.Preset.TargetVMAFProbeLength)
{
seekto = queueElement.Preset.TargetVMAFProbeLength.ToString();
}
// Generate Command
string ffmpegCommand = "/C ffmpeg.exe -y " + ss + " -i \"" + queueElement.VideoDB.InputPath + "\" -t " + seekto +
" -c:v libx264 -preset ultrafast -crf 0 -reset_timestamps 1 -map_metadata -1 -sn -an \"" +
Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks", "split" + counter_temp.ToString("D6") + ".mkv_vmaf_reference.mp4") + "\"";
// Start Splitting
Process chunkingProcess = new();
ProcessStartInfo startInfo = new()
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
RedirectStandardInput = false,
RedirectStandardError = false,
CreateNoWindow = true,
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Apps", "FFmpeg"),
Arguments = ffmpegCommand
};
chunkingProcess.StartInfo = startInfo;
token.Register(() => { try { chunkingProcess.StandardInput.Write("q"); } catch { } });
// Start Process
chunkingProcess.Start();
// Get launched Process ID
int tempPID = chunkingProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.LaunchedPIDs.Add(tempPID);
queueElement.Status = "Splitting - Chunk " + counter.ToString() + "/" + amount.ToString();
// Wait for Exit
chunkingProcess.WaitForExit();
// Get Exit Code
int exit_code = chunkingProcess.ExitCode;
// Remove PID from Array after Exit
Global.LaunchedPIDs.RemoveAll(i => i == tempPID);
counter++;
counter_temp++;
}
}
private void FFmpegChunking(CancellationToken _token)
{
Global.Logger("DEBUG - VideoSplitter.Split() => FFmpegChunking()", queueElement.Output + ".log");
// Skips Splitting of already existent
if (File.Exists(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "splitted.log")))
{
Global.Logger("WARN - VideoSplitter.Split() => FFmpegChunking() => Skipped Splitting - Resuming?", queueElement.Output + ".log");
return;
}
// Create Chunks Folder
Directory.CreateDirectory(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks"));
Global.Logger("DEBUG - VideoSplitter.Split() => FFmpegChunking() => Path: " + Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks"), queueElement.Output + ".log");
// Generate Command
string ffmpegCommand = "/C ffmpeg.exe -y -i \"" + queueElement.VideoDB.InputPath + "\"";
// Subtitle Input for Hardcoding
if (!string.IsNullOrEmpty(queueElement.SubtitleBurnCommand))
{
// Filter not compatible with filter_complex
if (string.IsNullOrEmpty(queueElement.FilterCommand))
{
if (queueElement.SubtitleBurnCommand.Contains("-filter_complex"))
{
ffmpegCommand += " -i \"" + Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Subtitles", "subs.mkv") + "\"";
}
}
}
// Set Encoder
string encoder = queueElement.ReencodeMethod switch
{
0 => " -c:v libx264 -preset ultrafast -crf 0",
1 => " -c:v ffv1 -level 3 -threads 4 -coder 1 -context 1 -slicecrc 0 -slices 4",
2 => " -c:v utvideo",
3 => " -c:v copy",
_ => " -c:v copy"
};
ffmpegCommand += " -reset_timestamps 1 -map_metadata -1 -sn -an" + encoder;
if (queueElement.ReencodeMethod != 3)
{
ffmpegCommand += " -sc_threshold 0 -g " + queueElement.ChunkLength.ToString();
ffmpegCommand += " -force_key_frames " + '\u0022' + "expr:gte(t, n_forced * " + queueElement.ChunkLength.ToString() + ")" + '\u0022';
ffmpegCommand += queueElement.FilterCommand;
if (queueElement.SubtitleBurnCommand != null)
{
if (string.IsNullOrEmpty(queueElement.FilterCommand))
{
ffmpegCommand += queueElement.SubtitleBurnCommand;
}
else
{
// Don't want to mix filter_complex with vf
if (!queueElement.SubtitleBurnCommand.Contains("-filter_complex"))
{
// Prevents using "-vf" two times
ffmpegCommand += "," + queueElement.SubtitleBurnCommand.Remove(0, 5);
}
}
}
}
ffmpegCommand += " -segment_time " + queueElement.ChunkLength.ToString() + " -f segment \"";
ffmpegCommand += Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "Chunks", "split%6d.mkv") + "\"";
Global.Logger("INFO - VideoSplitter.Split() => FFmpegChunking() => FFmpeg Command: " + ffmpegCommand, queueElement.Output + ".log");
// Start Splitting
Process chunkingProcess = new();
ProcessStartInfo startInfo = new()
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Apps", "FFmpeg"),
Arguments = ffmpegCommand
};
chunkingProcess.StartInfo = startInfo;
_token.Register(() => { try { chunkingProcess.StandardInput.Write("q"); } catch { } });
// Start Process
chunkingProcess.Start();
// Get launched Process ID
int tempPID = chunkingProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.LaunchedPIDs.Add(tempPID);
StreamReader sr = chunkingProcess.StandardError;
string stderr = "\n";
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (!line.Contains("frame=") && !line.Contains("[segment"))
stderr += line + "\n";
int processedFrames = Global.GetTotalFramesProcessed(line);
if (processedFrames != 0)
{
queueElement.Progress = Convert.ToDouble(processedFrames);
queueElement.Status = "Splitting - " + ((decimal)queueElement.Progress / queueElement.FrameCount).ToString("0.00%");
}
}
// Wait for Exit
chunkingProcess.WaitForExit();
// Get Exit Code
int exit_code = chunkingProcess.ExitCode;
// Remove PID from Array after Exit
Global.LaunchedPIDs.RemoveAll(i => i == tempPID);
// Write Save Point
if (chunkingProcess.ExitCode == 0 && _token.IsCancellationRequested == false)
{
FileStream _finishedLog = File.Create(Path.Combine(Global.Temp, "NEAV1E", queueElement.UniqueIdentifier, "splitted.log"));
_finishedLog.Close();
Global.Logger("DEBUG - VideoSplitter.Split() => FFmpegChunking() => FFmpeg Exit Code: " + exit_code, queueElement.Output + ".log");
}
else
{
queueElement.Error = true;
queueElement.ErrorCount += 1;
Global.Logger("FATAL - VideoSplitter.Split() => FFmpegChunking() => FFmpeg Exit Code: " + exit_code, queueElement.Output + ".log");
Global.Logger("==========================================================" + stderr, queueElement.Output + ".log");
Global.Logger("==========================================================", queueElement.Output + ".log");
}
}
private static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
}
}