-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressor.cs
More file actions
542 lines (452 loc) · 18.9 KB
/
Compressor.cs
File metadata and controls
542 lines (452 loc) · 18.9 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
using CryMediaAPI;
using CryMediaAPI.Video;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static CryCompressor.ColorConsole;
namespace CryCompressor;
public class Compressor
{
readonly Configuration configuration;
int fileCount;
int filesProcessed;
bool started, queuedone;
readonly CancellationToken tkn;
TaskCompletionSource<bool> taskState;
readonly ConcurrentQueue<string> fileQueue = new ConcurrentQueue<string>();
readonly ConcurrentQueue<string> videoQueue = new ConcurrentQueue<string>();
readonly ConcurrentQueue<string> imageQueue = new ConcurrentQueue<string>();
readonly ConcurrentQueue<string> audioQueue = new ConcurrentQueue<string>();
readonly ConcurrentQueue<string> errorQueue = new ConcurrentQueue<string>();
readonly ConcurrentQueue<string> warnQueue = new ConcurrentQueue<string>();
readonly SemaphoreSlim videoParamsSemaphore = new SemaphoreSlim(1);
readonly Dictionary<int, bool> videoParams = new Dictionary<int, bool>();
readonly SemaphoreSlim imageParamsSemaphore = new SemaphoreSlim(1);
readonly Dictionary<int, bool> imageParams = new Dictionary<int, bool>();
readonly SemaphoreSlim audioParamsSemaphore = new SemaphoreSlim(1);
readonly Dictionary<int, bool> audioParams = new Dictionary<int, bool>();
public Compressor(Configuration config, CancellationToken token)
{
tkn = token;
configuration = config;
for (int i = 0; i < config.VideoCompression.ParametersPriorityList.Length; i++) videoParams.Add(i, false);
for (int i = 0; i < config.ImageCompression.ParametersPriorityList.Length; i++) imageParams.Add(i, false);
for (int i = 0; i < config.AudioCompression.ParametersPriorityList.Length; i++) audioParams.Add(i, false);
}
public Task Start()
{
if (started) throw new InvalidOperationException("Compressor already started!");
started = true;
taskState = new TaskCompletionSource<bool>();
// get all files
WriteInfo("Getting files");
var files = Directory.GetFiles(configuration.InputDirectory, "*.*", SearchOption.AllDirectories);
WriteInfo($"Found {files.Length} files.");
fileCount = files.Length;
// Start up workers
for (int i = 0; i < configuration.VideoCompression.MaxConcurrentWorkers; i++) _ = Task.Run(VideoWorker, tkn);
for (int i = 0; i < configuration.ImageCompression.MaxConcurrentWorkers; i++) _ = Task.Run(ImageWorker, tkn);
for (int i = 0; i < configuration.AudioCompression.MaxConcurrentWorkers; i++) _ = Task.Run(AudioWorker, tkn);
_ = Task.Run(FileWorker, tkn);
// Start up progress logger
_ = Task.Run(Logger, tkn);
// Start filtering files and queueing them for work
var vidExtensions = configuration.VideoExtensions.Select(x => "." + x.ToLower().Trim().GetExtensionWithoutDot()).ToArray();
var imgExtensions = configuration.ImageExtensions.Select(x => "." + x.ToLower().Trim().GetExtensionWithoutDot()).ToArray();
var audExtensions = configuration.AudioExtensions.Select(x => "." + x.ToLower().Trim().GetExtensionWithoutDot()).ToArray();
foreach (var f in files)
{
var extension = Path.GetExtension(f).ToLower().Trim();
var size = new FileInfo(f).Length;
if (configuration.VideoCompression.CompressVideos && vidExtensions.Contains(extension) && size >= configuration.VideoCompression.MinSize)
{
// VIDEO
videoQueue.Enqueue(f);
}
else if (configuration.ImageCompression.CompressImages && imgExtensions.Contains(extension) && size >= configuration.ImageCompression.MinSize)
{
// IMAGE
imageQueue.Enqueue(f);
}
else if (configuration.AudioCompression.CompressAudio && audExtensions.Contains(extension) && size >= configuration.AudioCompression.MinSize)
{
// AUDIO
audioQueue.Enqueue(f);
}
else
{
// just copy these files
fileQueue.Enqueue(f);
}
}
queuedone = true;
return taskState.Task;
}
async Task Logger()
{
int lastCount = -1;
while (!tkn.IsCancellationRequested)
{
if (errorQueue.TryDequeue(out string err))
{
WriteEmpty();
Console.Write("\r");
WriteError(err);
}
if (warnQueue.TryDequeue(out string wrn))
{
WriteEmpty();
Console.Write("\r");
WriteInfo(wrn);
}
if (lastCount != filesProcessed)
{
lastCount = filesProcessed;
var fp = filesProcessed;
WriteUpdate(fileCount, fp);
if (fp == fileCount) break;
}
await Task.Delay(50);
}
taskState.SetResult(true);
}
readonly static Random rng = new Random();
(string destination_unchanged, string destination_modified) GetPath(string filename, string extension, bool generateSuffix)
{
extension = extension?.GetExtensionWithoutDot();
var directory = Path.GetRelativePath(configuration.InputDirectory, Path.GetDirectoryName(filename));
if (directory == ".") directory = "";
var destinationDirectory = Path.Combine(configuration.OutputDirectory, directory);
Directory.CreateDirectory(destinationDirectory);
var fileNameNoext = Path.GetFileNameWithoutExtension(filename);
var fileExtension = Path.GetExtension(filename).GetExtensionWithoutDot();
if (extension == null) extension = fileExtension;
// if defined extension is different from original, add a unique suffix to avoid
// rare cases of multiple files with same names but different extensions merging into one
if (generateSuffix && fileExtension.ToLower() != extension.ToLower())
{
fileNameNoext += $"({rng.Next(0, 1000)}-{fileExtension})";
}
var destination_unchanged = Path.Combine(destinationDirectory, Path.GetFileName(filename));
var destination_modified = Path.Combine(destinationDirectory, fileNameNoext + "." + extension);
return (destination_unchanged, destination_modified);
}
async Task VideoWorker()
{
var codecs = configuration.IgnoredVideoCodecs.Select(x => x.ToLower().Trim()).ToArray();
while (!tkn.IsCancellationRequested)
{
if (videoQueue.TryDequeue(out string f))
{
Process p = null;
// choose parameters based on priority list
var (pIndex, parameters) = await TakeVideoParameters();
var (dst_orig, dst) = GetPath(f, parameters.Extension, configuration.VideoCompression.RandomSuffixOnDifferentExtension);
string output = "";
try
{
// convert
using var reader = new VideoReader(f);
await reader.LoadMetadataAsync();
var codec = reader.Metadata.Codec.ToLower();
if (codecs.Contains(codec))
{
// ignore and copy file to destination
File.Copy(f, dst, true);
continue;
}
reader.Dispose();
p = FFmpegWrapper.ExecuteCommand("ffmpeg", $"-hide_banner -i \"{f}\" {parameters.Parameters} \"{dst}\" -y");
p.ErrorDataReceived += (s, data) =>
{
if (data.Data == null) return;
output += data.Data + "\n";
};
await p.WaitForExitAsync(tkn);
var code = p.ExitCode;
// validate result
var result = new FileInfo(dst);
if (result.Length < 1000 || code != 0)
{
File.Delete(dst);
File.Copy(f, dst, true);
throw new Exception($"Video conversion failed. (Code: {code}). Output:\n{output}");
}
if (configuration.DeleteResultIfBigger && result.Length > new FileInfo(f).Length)
{
File.Delete(dst);
File.Copy(f, dst, true);
warnQueue.Enqueue($"Converted video was larger than original, overwriting it. ('{f}')");
}
}
catch (Exception ex)
{
// in rare case it hasn't been copied over, copy it (use original filename for destination now instead)
if (!File.Exists(dst)) File.Copy(f, dst_orig, true);
errorQueue.Enqueue($"Failed to convert video '{f}': {ex.Message}" + (output.Length > 0 ? $"\n\nFFmpeg output:\n{output}" : ""));
}
finally
{
await ReleaseVideoParameters(pIndex);
if (p != null && !p.HasExited) p.Kill();
Interlocked.Increment(ref filesProcessed);
}
}
else if (queuedone) break;
await Task.Delay(10);
}
}
async Task ImageWorker()
{
while (!tkn.IsCancellationRequested)
{
if (imageQueue.TryDequeue(out string f))
{
Process p = null;
// choose parameters based on priority list
var (pIndex, parameters) = await TakeImageParameters();
var (dst_orig, dst) = GetPath(f, parameters.Extension, configuration.ImageCompression.RandomSuffixOnDifferentExtension);
string output = "";
try
{
// convert
using var reader = new VideoReader(f);
await reader.LoadMetadataAsync();
reader.Dispose();
p = FFmpegWrapper.ExecuteCommand("ffmpeg", $"-hide_banner -i \"{f}\" {parameters.Parameters} \"{dst}\" -y");
p.ErrorDataReceived += (s, data) =>
{
if (data.Data == null) return;
output += data.Data + "\n";
};
await p.WaitForExitAsync(tkn);
var code = p.ExitCode;
// validate result
var result = new FileInfo(dst);
if (result.Length < 1000 || code != 0)
{
File.Delete(dst);
File.Copy(f, dst, true);
throw new Exception($"Image conversion failed. (Code: {code}). Output:\n{output}");
}
if (configuration.DeleteResultIfBigger && result.Length > new FileInfo(f).Length)
{
File.Delete(dst);
File.Copy(f, dst, true);
warnQueue.Enqueue($"Converted image was larger than original, overwriting it. ('{f}')");
}
}
catch (Exception ex)
{
// in rare case it hasn't been copied over, copy it (use original filename for destination now instead)
if (!File.Exists(dst)) File.Copy(f, dst_orig, true);
errorQueue.Enqueue($"Failed to convert image '{f}': {ex.Message}" + (output.Length > 0 ? $"\n\nFFmpeg output:\n{output}" : ""));
}
finally
{
await ReleaseImageParameters(pIndex);
if (p != null && !p.HasExited) p.Kill();
Interlocked.Increment(ref filesProcessed);
}
}
else if (queuedone) break;
await Task.Delay(10);
}
}
async Task AudioWorker()
{
while (!tkn.IsCancellationRequested)
{
if (audioQueue.TryDequeue(out string f))
{
Process p = null;
// choose parameters based on priority list
var (pIndex, parameters) = await TakeAudioParameters();
var (dst_orig, dst) = GetPath(f, parameters.Extension, configuration.AudioCompression.RandomSuffixOnDifferentExtension);
string output = "";
try
{
// convert
using var reader = new VideoReader(f);
await reader.LoadMetadataAsync();
reader.Dispose();
p = FFmpegWrapper.ExecuteCommand("ffmpeg", $"-hide_banner -i \"{f}\" {parameters.Parameters} \"{dst}\" -y");
p.ErrorDataReceived += (s, data) =>
{
if (data.Data == null) return;
output += data.Data + "\n";
};
await p.WaitForExitAsync(tkn);
var code = p.ExitCode;
// validate result
var result = new FileInfo(dst);
if (result.Length < 1000 || code != 0)
{
File.Delete(dst);
File.Copy(f, dst, true);
throw new Exception($"Audio conversion failed. (Code: {code}). Output:\n{output}");
}
if (configuration.DeleteResultIfBigger && result.Length > new FileInfo(f).Length)
{
File.Delete(dst);
File.Copy(f, dst, true);
warnQueue.Enqueue($"Converted audio was larger than original, overwriting it. ('{f}')");
}
}
catch (Exception ex)
{
// in rare case it hasn't been copied over, copy it (use original filename for destination now instead)
if (!File.Exists(dst)) File.Copy(f, dst_orig, true);
errorQueue.Enqueue($"Failed to convert audio '{f}': {ex.Message}" + (output.Length > 0 ? $"\n\nFFmpeg output:\n{output}" : ""));
}
finally
{
await ReleaseAudioParameters(pIndex);
if (p != null && !p.HasExited) p.Kill();
Interlocked.Increment(ref filesProcessed);
}
}
else if (queuedone) break;
await Task.Delay(10);
}
}
async Task FileWorker()
{
while (!tkn.IsCancellationRequested)
{
if (fileQueue.TryDequeue(out string f))
{
try
{
var (_, dst) = GetPath(f, null, false);
File.Copy(f, dst, true);
}
catch (Exception ex)
{
errorQueue.Enqueue($"Failed to copy file '{f}': {ex.Message}");
}
finally
{
Interlocked.Increment(ref filesProcessed);
}
}
else if (queuedone) break;
await Task.Delay(10);
}
}
#region Getting Parameters
async Task<(int Index, ParametersObject Parameters)> TakeVideoParameters()
{
// pick the first parameters available - if last, take last one.
await videoParamsSemaphore.WaitAsync();
try
{
for (int i = 0; i < configuration.VideoCompression.ParametersPriorityList.Length; i++)
{
if (!videoParams[i])
{
videoParams[i] = true;
return (i, configuration.VideoCompression.ParametersPriorityList[i]);
}
}
// always return last one if all else is taken
return (
configuration.VideoCompression.ParametersPriorityList.Length - 1,
configuration.VideoCompression.ParametersPriorityList.Last());
}
finally
{
videoParamsSemaphore.Release();
}
}
async Task ReleaseVideoParameters(int index)
{
await videoParamsSemaphore.WaitAsync();
try
{
videoParams[index] = false;
}
finally
{
videoParamsSemaphore.Release();
}
}
async Task<(int Index, ParametersObject Parameters)> TakeImageParameters()
{
// pick the first parameters available - if last, take last one.
await imageParamsSemaphore.WaitAsync();
try
{
for (int i = 0; i < configuration.ImageCompression.ParametersPriorityList.Length; i++)
{
if (!imageParams[i])
{
imageParams[i] = true;
return (i, configuration.ImageCompression.ParametersPriorityList[i]);
}
}
// always return last one if all else is taken
return (
configuration.ImageCompression.ParametersPriorityList.Length - 1,
configuration.ImageCompression.ParametersPriorityList.Last());
}
finally
{
imageParamsSemaphore.Release();
}
}
async Task ReleaseImageParameters(int index)
{
await imageParamsSemaphore.WaitAsync();
try
{
imageParams[index] = false;
}
finally
{
imageParamsSemaphore.Release();
}
}
async Task<(int Index, ParametersObject Parameters)> TakeAudioParameters()
{
// pick the first parameters available - if last, take last one.
await audioParamsSemaphore.WaitAsync();
try
{
for (int i = 0; i < configuration.AudioCompression.ParametersPriorityList.Length; i++)
{
if (!audioParams[i])
{
audioParams[i] = true;
return (i, configuration.AudioCompression.ParametersPriorityList[i]);
}
}
// always return last one if all else is taken
return (
configuration.AudioCompression.ParametersPriorityList.Length - 1,
configuration.AudioCompression.ParametersPriorityList.Last());
}
finally
{
audioParamsSemaphore.Release();
}
}
async Task ReleaseAudioParameters(int index)
{
await audioParamsSemaphore.WaitAsync();
try
{
audioParams[index] = false;
}
finally
{
audioParamsSemaphore.Release();
}
}
#endregion
}