-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFFMP.cs
350 lines (308 loc) · 11 KB
/
FFMP.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
namespace FFMP;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
class FFMP
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting application...");
var appArgs = args.TakeWhile(arg => arg != "--").ToArray();
var ffmpegArgs = args.SkipWhile(arg => arg != "--").Skip(1).ToArray();
if (!appArgs.Any())
{
Console.WriteLine("Error: No arguments provided. Please specify required arguments.");
Environment.Exit(1);
}
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Terminating processes...");
foreach (var processId in TrackedProcessIds.ToList())
{
try
{
var process = Process.GetProcessById(processId);
if (process != null && !process.HasExited)
{
process.Kill();
Console.WriteLine($"Terminated FFmpeg process with ID {process.Id}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error terminating process {processId}: {ex.Message}");
}
}
e.Cancel = true;
Environment.Exit(0);
};
Parser.Default.ParseArguments<Options>(appArgs)
.WithParsed(options =>
{
if (ValidateOptions(options))
{
Run(options, ffmpegArgs).Wait();
}
else
{
Environment.Exit(1);
}
})
.WithNotParsed(errors =>
{
if (errors.Any(error => error is CommandLine.HelpRequestedError || error is CommandLine.VersionRequestedError))
{
Environment.Exit(0);
}
Console.WriteLine("Error: Invalid arguments provided.");
Environment.Exit(1);
});
}
catch (Exception ex)
{
Console.WriteLine($"Fatal error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
private static readonly ConcurrentBag<int> TrackedProcessIds = new ConcurrentBag<int>();
static async Task Run(Options options, string[] ffmpegArgs)
{
try
{
var inputFiles = GetInputFiles(options)?.ToList();
if (inputFiles == null || !inputFiles.Any())
{
Console.WriteLine("No input files found.");
return;
}
Console.WriteLine($"Found {inputFiles.Count} files to process:");
foreach (var file in inputFiles)
{
Console.WriteLine(file);
}
var progress = new ProgressBar(inputFiles.Count);
var tasks = new List<Task>();
var semaphore = new SemaphoreSlim(options.ThreadCount);
foreach (var inputFile in inputFiles)
{
await semaphore.WaitAsync();
tasks.Add(Task.Run(async () =>
{
try
{
Console.WriteLine($"Processing file: {inputFile}");
// Call the ProcessFile method
await ProcessFile(inputFile, options, ffmpegArgs, progress, inputFiles.Count);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing file {inputFile}: {ex.Message}");
}
finally
{
semaphore.Release();
}
}));
}
await Task.WhenAll(tasks);
progress.Dispose();
Console.WriteLine("Processing complete.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static IEnumerable<string> GetInputFiles(Options options)
{
try
{
if (!string.IsNullOrEmpty(options.InputDirectory))
{
var excludedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// Non-Media file filter
".txt",
".doc",
".docx",
".xls",
".xlsx",
".csv",
".json",
".xml",
".html",
".htm",
".exe",
".dll",
".bat",
".cmd",
".zip",
".rar",
".7z",
".tar",
".gz",
".iso",
".bin",
".log",
".ini",
".cfg",
".tmp"
};
return Directory
.EnumerateFiles(Path.GetFullPath(options.InputDirectory), "*.*", SearchOption.AllDirectories)
.Where(file => !excludedExtensions.Contains(Path.GetExtension(file)));
}
if (!string.IsNullOrEmpty(options.InputFile) && File.Exists(options.InputFile))
{
return File.ReadLines(Path.GetFullPath(options.InputFile));
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading input files: {ex.Message}");
}
return Enumerable.Empty<string>();
}
static async Task ProcessFile(string inputFile, Options options, string[] ffmpegArgs, ProgressBar progress, int totalFiles)
{
string outputFile = GenerateOutputFilePath(inputFile, options.OutputPattern);
Directory.CreateDirectory(Path.GetDirectoryName(outputFile)!);
if (File.Exists(outputFile) && !options.Overwrite)
{
Console.WriteLine($"Skipping {inputFile}, output already exists.");
return;
}
var arguments = options.Overwrite ? "-y " : "";
arguments += $"-i \"{Path.GetFullPath(inputFile)}\" \"{outputFile}\"";
if (ffmpegArgs.Any())
{
arguments += $" {string.Join(" ", ffmpegArgs)}";
}
if (options.Verbose)
{
arguments = $"-loglevel verbose {arguments}";
}
else
{
arguments = $"-loglevel error {arguments}";
}
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
try
{
process.Start();
TrackedProcessIds.Add(process.Id);
if (options.Verbose)
{
var outputTask = Task.Run(() =>
{
while (!process.StandardOutput.EndOfStream)
{
Console.WriteLine(process.StandardOutput.ReadLine());
}
});
var errorTask = Task.Run(() =>
{
while (!process.StandardError.EndOfStream)
{
Console.WriteLine(process.StandardError.ReadLine());
}
});
await Task.WhenAll(outputTask, errorTask);
}
else
{
await process.WaitForExitAsync();
}
if (process.ExitCode == 0)
{
Console.WriteLine($"FFmpeg process completed successfully for file: {inputFile}");
progress.Report(1.0 / totalFiles);
}
else
{
Console.WriteLine($"FFmpeg process exited with code {process.ExitCode} for file: {inputFile}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error executing FFmpeg for file {inputFile}: {ex.Message}");
}
}
static string GenerateOutputFilePath(string inputFile, string pattern)
{
var directory = Path.GetDirectoryName(inputFile);
var fileName = Path.GetFileNameWithoutExtension(inputFile);
var extension = Path.GetExtension(inputFile);
var outputPath = pattern.Replace("{{dir}}", directory)
.Replace("{{name}}", fileName)
.Replace("{{ext}}", extension);
// Ensure the output path has a directory; default to input file's directory
if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(outputPath)))
{
outputPath = Path.Combine(directory!, outputPath);
}
return outputPath;
}
private static bool ValidateOptions(Options options)
{
bool isValid = true;
if (options.Convert)
{
// Ensure required fields for conversion
if (string.IsNullOrWhiteSpace(options.OutputPattern))
{
Console.WriteLine("Error: The 'output-pattern' argument is required when using '--convert'.");
isValid = false;
}
}
else
{
// Ensure required fields for transcoding
if (string.IsNullOrWhiteSpace(options.Codec))
{
Console.WriteLine("Error: The 'codec' argument is required.");
isValid = false;
}
if (string.IsNullOrWhiteSpace(options.OutputPattern))
{
Console.WriteLine("Error: The 'output-pattern' argument is required.");
isValid = false;
}
}
// Common validation for both modes
if (string.IsNullOrWhiteSpace(options.InputDirectory) && string.IsNullOrWhiteSpace(options.InputFile))
{
Console.WriteLine("Error: Either 'directory' or 'file' argument must be provided for input.");
isValid = false;
}
if (!string.IsNullOrWhiteSpace(options.InputFile) && !File.Exists(options.InputFile))
{
Console.WriteLine($"Error: Specified input file '{options.InputFile}' does not exist.");
isValid = false;
}
if (!string.IsNullOrWhiteSpace(options.InputDirectory) && !Directory.Exists(options.InputDirectory))
{
Console.WriteLine($"Error: Specified input directory '{options.InputDirectory}' does not exist.");
isValid = false;
}
return isValid;
}
}