-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathProgram.cs
517 lines (460 loc) · 24.7 KB
/
Program.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
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
using GICutscenes.FileTypes;
using GICutscenes.Mergers;
using GICutscenes.Mergers.GIMKV;
using GICutscenes.Utils;
using Microsoft.Extensions.Configuration;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Parsing;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
namespace GICutscenes
{
internal sealed class Settings
{
public string? MkvMergePath { get; set; }
public string? SubsFolder { get; set; }
public string? FfmpegPath { get; set; }
public string? SubsStyle { get; set; }
}
internal sealed class Program
{
public static Settings? settings;
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "Retrieves the configuration file")]
private static int Main(string[] args)
{
// CLI Options
var demuxFileOption = new Argument<FileInfo?>(
name: "Input file",
description: "The file to read and display on the console.");
var usmFolderArg = new Argument<DirectoryInfo>(
name: "USM Folder",
description: "Folder containing the .usm files to be demuxed.");
var hcaInputArg = new Argument<FileSystemInfo>(
name: "HCA Input",
description: "File or directory to be processed.");
var outputFolderOption = new Option<DirectoryInfo?>(
name: "--output",
description: "Output folder, default is './output'."
);
outputFolderOption.AddAlias("-o");
var key1Option = new Option<string?>(
name: "-a",
description: "4 lower bytes of the key");
var key2Option = new Option<string?>(
name: "-b",
description: "4 higher bytes of the key");
var subsOption = new Option<bool>(
name: "--subs",
description: "Adds the subtitles to the MKV file."
);
subsOption.AddAlias("--subtitles");
subsOption.AddAlias("-s");
var noCleanupOption = new Option<bool>(
name: "--no-cleanup",
description: "Keeps the extracted files instead of removing them.");
noCleanupOption.AddAlias("-nc");
var audioLangOption = new Option<string>(
name: "--audio-lang",
description: $"Select audio languages that you wish to include in MKV file.{Environment.NewLine}Example \"eng,jpn\")");
audioLangOption.AddAlias("-al");
audioLangOption.SetDefaultValue("chi,eng,jpn,kor");
var mergeOption = new Option<bool>(
name: "--merge",
description: "Merges the extracted content into a MKV container file."
);
mergeOption.AddAlias("-m");
var mkvEngineOption = new Option<string>(
name: "--mkv-engine",
description: "Merges the extracted content into a MKV container file."
).FromAmong(
"mkvmerge",
"internal",
"ffmpeg");
mkvEngineOption.SetDefaultValue("internal");
mkvEngineOption.AddAlias("-e");
var audioFormatOption = new Option<string>(
name: "--audio-format",
description: "Audio encode format in MKV file, the original is PCM.");
audioFormatOption.AddAlias("-af");
var videoFormatOption = new Option<string>(
name: "--video-format",
description: "Video encode format in MKV file, the original is VP9.");
videoFormatOption.AddAlias("-vf");
var notOpenBrowserOption = new Option<bool>(
name: "--no-browser",
description: "Do not open browser if there's new version.");
notOpenBrowserOption.AddAlias("-nb");
var proxyOption = new Option<string>(
name: "--proxy",
description: "Specifies a proxy server for the request.");
proxyOption.AddAlias("-p");
var stackTraceOption = new Option<bool>(
name: "--stack-trace",
description: "Show stack trace when throw exception.");
stackTraceOption.AddAlias("-st");
var rootCommand = new RootCommand("A command line program playing with the cutscenes files (USM) from Genshin Impact.");
rootCommand.AddGlobalOption(stackTraceOption);
var demuxUsmCommand = new Command("demuxUsm", "Demuxes a specified .usm file to a specified folder")
{
demuxFileOption,
key1Option,
key2Option,
subsOption,
mergeOption,
mkvEngineOption,
audioFormatOption,
videoFormatOption,
outputFolderOption,
noCleanupOption,
audioLangOption
};
var batchDemuxCommand = new Command("batchDemux", "Tries to demux all .usm files in the specified folder")
{
usmFolderArg,
subsOption,
mergeOption,
mkvEngineOption,
audioFormatOption,
videoFormatOption,
outputFolderOption,
noCleanupOption,
audioLangOption
};
//var hcaDecrypt = new Command();
var convertHcaCommand = new Command("convertHca", "Converts input .hca files into .wav files")
{
hcaInputArg,
outputFolderOption,
};
var updateCommand = new Command("update", "Update for usm secret key and GICutscenes.")
{
notOpenBrowserOption,
proxyOption,
};
var resetCommand = new Command("reset", "Reset 'appsettings.json' file to default.");
rootCommand.AddCommand(demuxUsmCommand);
rootCommand.AddCommand(batchDemuxCommand);
rootCommand.AddCommand(convertHcaCommand);
rootCommand.AddCommand(updateCommand);
rootCommand.AddCommand(resetCommand);
// Command Handlers
demuxUsmCommand.SetHandler((FileInfo file, string key1, string key2, DirectoryInfo? output, string engine, bool merge, bool subs, bool noCleanup, string audioFormat, string videoFormat, string audioLang) =>
{
ReadSetting();
output ??= new DirectoryInfo("./output");
output.Create();
DemuxUsmCommand(file, key1, key2, output, engine, merge, subs, noCleanup, audioFormat, videoFormat, audioLang);
}, demuxFileOption, key1Option, key2Option, outputFolderOption, mkvEngineOption, mergeOption, subsOption, noCleanupOption, audioFormatOption, videoFormatOption, audioLangOption);
batchDemuxCommand.SetHandler((DirectoryInfo inputDir, DirectoryInfo? outputDir, string engine, bool merge, bool subs, bool noCleanup, string audioFormat, string videoFormat, string audioLang) =>
{
ReadSetting();
outputDir ??= new DirectoryInfo("./output");
outputDir.Create();
var timer = Stopwatch.StartNew();
BatchDemuxCommand(inputDir, outputDir, engine, merge, subs, noCleanup, audioFormat, videoFormat, audioLang);
timer.Stop();
Console.WriteLine($"{timer.ElapsedMilliseconds}ms elapsed");
}, usmFolderArg, outputFolderOption, mkvEngineOption, mergeOption, subsOption, noCleanupOption, audioFormatOption, videoFormatOption, audioLangOption);
convertHcaCommand.SetHandler((FileSystemInfo input, DirectoryInfo? output) =>
{
output ??= new DirectoryInfo("./output");
output.Create();
ConvertHcaCommand(input, output);
}, hcaInputArg, outputFolderOption);
updateCommand.SetHandler(async (bool notOpenBrowser, string proxy) =>
{
await UpdateAsync(notOpenBrowser, proxy);
}, notOpenBrowserOption, proxyOption);
resetCommand.SetHandler(() =>
{
const string str = """
{
"Settings": {
"MkvMergePath": "",
"FfmpegPath": "",
"SubsFolder": "",
"SubsStyle": "Style: Default,{fontname},12,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100.0,100.0,0.0,0.0,1,0,0.5,2,10,10,14,1"
}
}
""";
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "appsettings.json"), str);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("'appsettings.json' has reset to default.");
Console.ResetColor();
});
return new CommandLineBuilder(rootCommand).UseDefaults().UseExceptionHandler((ex, context) =>
{
Console.ForegroundColor = ConsoleColor.Red;
if (context.ParseResult.GetValueForOption(stackTraceOption))
{
Console.Error.WriteLine(ex);
}
else
{
Console.Error.WriteLine($"{ex.GetType()}: {ex.Message}");
}
Console.ResetColor();
}).Build().Invoke(args);
}
[RequiresUnreferencedCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Get<T>()")]
private static void ReadSetting()
{
if (settings is null)
{
// Loading config file
// TODO: A LA MANO ?
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile(Path.Combine(AppContext.BaseDirectory, "appsettings.json"))
.AddEnvironmentVariables()
.Build();
settings = config?.GetSection(nameof(Settings)).Get<Settings>();
if (settings is null)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("File 'appsettings.json' has error section, use command 'reset' to reset it to default.");
Console.ResetColor();
Environment.Exit(1);
}
}
}
private static void DemuxUsmCommand(FileInfo file, string key1, string key2, DirectoryInfo? output, string engine, bool merge, bool subs, bool noCleanup, string audioFormat, string videoFormat, string audioLang)
{
if (file == null) throw new ArgumentNullException(nameof(file), "No file provided.");
if (!file.Exists) throw new ArgumentException("File {0} does not exist.", file.Name);
if (!file.Name.EndsWith(".usm"))
throw new ArgumentException($"File {file.Name} provided isn't a .usm file.");
if (key1 != null && key2 != null && (key1.Length != 8 || key2.Length != 8)) throw new ArgumentException("Keys are invalid.");
string outputArg = output == null
? file.Directory!.FullName
: ((output.Exists) ? output.FullName : throw new ArgumentException("Output directory is invalid."));
Console.WriteLine($"Output folder : {outputArg}");
byte[] key1Arg = Convert.FromHexString(key1 ?? "");
byte[] key2Arg = Convert.FromHexString(key2 ?? "");
Demuxer.Demux(file.FullName, key1Arg, key2Arg, outputArg);
if (merge)
{
MergeFiles(outputArg, Path.GetFileNameWithoutExtension(file.FullName), engine, subs, audioFormat, videoFormat, audioLang);
if (!noCleanup) CleanFiles(outputArg, Path.GetFileNameWithoutExtension(file.FullName));
}
if (!noCleanup && Directory.Exists(Path.Combine(outputArg, "Subs")))
{
Directory.Delete(Path.Combine(outputArg, "Subs"), true);
}
}
private static void BatchDemuxCommand(DirectoryInfo inputDir, DirectoryInfo? outputDir, string engine, bool merge, bool subs, bool noCleanup, string audioFormat, string videoFormat, string audioLang)
{
if (inputDir is not { Exists: true }) throw new DirectoryNotFoundException("Input directory is invalid.");
string outputArg = (outputDir == null)
? inputDir.FullName
: ((outputDir.Exists) ? outputDir.FullName : throw new ArgumentException("Output directory is invalid."));
Console.WriteLine($"Output folder : {outputArg}");
foreach (string f in Directory.EnumerateFiles(inputDir.FullName, "*.usm"))
{
bool demuxed = Demuxer.Demux(f, Array.Empty<byte>(), Array.Empty<byte>(), outputArg);
if (!demuxed) continue;
if (!merge) continue;
MergeFiles(outputArg, Path.GetFileNameWithoutExtension(f), engine, subs, audioFormat, videoFormat, audioLang);
if (!noCleanup) CleanFiles(outputArg, Path.GetFileNameWithoutExtension(f));
}
if (!noCleanup && Directory.Exists(Path.Combine(outputArg, "Subs")))
{
Directory.Delete(Path.Combine(outputArg, "Subs"), true);
}
}
private static void ConvertHcaCommand(FileSystemInfo input, DirectoryInfo? output)
{
if (!input.Exists) throw new ArgumentException("No file or directory given.");
string outputArg = (output == null)
? input.FullName
: ((output.Exists) ? output.FullName : throw new ArgumentException("Output directory is invalid."));
Console.WriteLine($"Output folder : {outputArg}");
switch (input)
{
case FileInfo f:
// TODO add keys :shrug:
if (Path.GetExtension(f.Name) == ".hca") throw new ArgumentException("File provided is not a .hca file.");
Hca file = new(f.FullName);
file.ConvertToWAV(outputArg);
break;
case DirectoryInfo directory:
foreach (string f in Directory.EnumerateFiles(directory.FullName, "*.hca"))
{
Hca singleFile = new(f);
singleFile.ConvertToWAV(outputArg);
}
break;
default:
Console.WriteLine("Not a valid file or directory name.");
break;
}
}
private static void MergeFiles(string outputPath, string basename, string engine, bool subs, string audioFormat, string videoFormat, string audioLang)
{
Merger merger;
if (!string.IsNullOrWhiteSpace(audioFormat) || !string.IsNullOrWhiteSpace(videoFormat))
{
engine = "ffmpeg";
}
switch (engine)
{
case "internal":
Console.WriteLine("Merging using the internal engine.");
// Video track is already added
merger = new GIMKV(basename, outputPath, "GI-Cutscenes v0.5.0", Path.Combine(outputPath, basename + ".ivf"));
break;
case "mkvmerge":
Console.WriteLine("Merging using mkvmerge.");
merger = File.Exists(
Path.GetFileNameWithoutExtension(settings?.MkvMergePath)?.ToLower() == "mkvmerge" ? settings?.MkvMergePath : "")
? new Mkvmerge(Path.Combine(outputPath, basename + ".mkv"), settings!.MkvMergePath!) : new Mkvmerge(Path.Combine(outputPath, basename + ".mkv"));
merger.AddVideoTrack(Path.Combine(outputPath, basename + ".ivf"));
break;
case "ffmpeg":
Console.WriteLine("Merging using ffmpeg.");
merger = File.Exists(
Path.GetFileNameWithoutExtension(settings?.FfmpegPath)?.ToLower() == "ffmpeg" ? settings?.FfmpegPath : "")
? new FFMPEG(Path.Combine(outputPath, basename + ".mkv"), settings!.FfmpegPath!) : new FFMPEG(Path.Combine(outputPath, basename + ".mkv"));
merger.AddVideoTrack(Path.Combine(outputPath, basename + ".ivf"));
break;
default:
throw new ArgumentException("Not implemented");
}
foreach (string f in Directory.EnumerateFiles(outputPath, $"{basename}_*.wav"))
{
if (!int.TryParse(Path.GetFileNameWithoutExtension(f)[^1..], out int language)) // Extracting language number from filename
throw new FormatException($"Unable to parse the language code from the file {Path.GetFileName(f)}.");
string[] langs = audioLang.Split(',');
if (language > 3 || !langs.Contains(MKV.AudioLang[language].Item2))
continue;
merger.AddAudioTrack(f, language);
}
if (subs)
{
string subsFolder = settings?.SubsFolder ?? throw new ArgumentException("Configuration value is not set for the key SubsFolder.");
subsFolder = Path.GetFullPath(subsFolder);
if (!Directory.Exists(subsFolder))
throw new ArgumentException(
"Path value for the key SubsFolder is invalid : Directory does not exist.");
string subName = ASS.FindSubtitles(basename, subsFolder) ?? "";//throw new FileNotFoundException($"Subtitles could not be found for file {basename}");
if (!string.IsNullOrEmpty(subName)) // Sometimes a cutscene has no subtitles (ChangeWeather), so we cna skip that part
{
subName = Path.GetFileNameWithoutExtension(subName);
Console.WriteLine($"Subtitles name found: {subName}");
foreach (string d in Directory.EnumerateDirectories(subsFolder))
{
string lang = Path.GetFileName(d) ?? throw new DirectoryNotFoundException();
string[] search = Directory.GetFiles(d, $"{subName}_{lang}.*").OrderBy(f => f).ToArray(); // Sorting by name
switch (search.Length)
{
case 0:
Console.WriteLine($"No subtitle for {subName} could be found for the language {lang}, skipping...");
break;
case 1:
// Could be either the presence of both .srt and .txt files (following the 3.0 release), but also .ass
case 2:
// Might be .srt+.txt+.ass
case 3:
// The "search" array is sorted by name, which means that the file order would be ASS > SRT > TXT
string res = Array.Find(search, name => ASS.SubsExtensions.Contains(Path.GetExtension(name))) ?? throw new FileNotFoundException(
$"No valid file could be found for the subs {subName} while the files corresponding to the name is {search.Length}"); ;
Console.WriteLine($"Using subs file {Path.GetFileName(res)}");
bool skipSubs = false;
ASS sub = new(res, lang);
string subFile = search[0];
if (!sub.IsAss())
{
if (sub.ParseSrt())
{
subFile = sub.ConvertToAss(outputPath);
}
else
{
skipSubs = true;
}
}
if (!skipSubs)
{
merger.AddSubtitlesTrack(subFile, lang);
}
break;
default:
throw new Exception($"Too many results ({search.Length}), please report this case");
}
}
// Adding attachments
if (File.Exists("ja-jp.ttf")) merger.AddAttachment("ja-jp.ttf", "Japanese Font"); else Console.WriteLine("ja-jp.ttf font not found, skipping...");
if (File.Exists("zh-cn.ttf")) merger.AddAttachment("zh-cn.ttf", "Chinese Font"); else Console.WriteLine("zh-cn.ttf font not found, skipping...");
}
else Console.WriteLine($"No subtitles found for cutscene {basename}");
}
// Merging the file
if (!string.IsNullOrWhiteSpace(audioFormat) || !string.IsNullOrWhiteSpace(videoFormat))
{
merger.Merge(audioFormat, videoFormat);
}
else
{
merger.Merge();
}
}
private static void CleanFiles(string outputPath, string basename)
{
string basePath = Path.Combine(outputPath, basename);
// Removing corresponding video file
if (File.Exists(basePath + ".ivf")) File.Delete(basePath + ".ivf");
// Removing audio files
foreach (string f in Directory.EnumerateFiles(outputPath, $"{basename}_*.hca")) File.Delete(f);
foreach (string f in Directory.EnumerateFiles(outputPath, $"{basename}_*.wav")) File.Delete(f);
}
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
private static async Task UpdateAsync(bool notOpenBroswer, string? proxy)
{
var webProxy = new WebProxy(proxy);
var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All, Proxy = webProxy });
client.DefaultRequestHeaders.Add("User-Agent", "GICutscenes");
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("Update 'versions.json'...");
Console.ResetColor();
var versionsString = await client.GetStringAsync("https://cdn.jsdelivr.net/gh/ToaHartor/GI-cutscenes@main/versions.json");
await File.WriteAllTextAsync(Path.Combine(AppContext.BaseDirectory, "versions.json"), versionsString);
Console.WriteLine("'versions.json' has updated to the latest version.");
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("Check update for GICutscenes...");
Console.ResetColor();
var releaseString = await client.GetStringAsync("https://api.github.com/repos/ToaHartor/GI-cutscenes/releases/latest");
var release = JsonSerializer.Deserialize<GithubRelease>(releaseString!, GithubJsonContext.Default.Options);
var currentVersion = typeof(Program).Assembly.GetName().Version;
if (System.Version.TryParse(release?.TagName?[1..], out var latestVersion))
{
if (latestVersion > currentVersion)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"Latest version is '{release?.TagName}', GICutscenes needs to update.");
Console.WriteLine($"Release page: {release?.HtmlUrl}");
Console.ResetColor();
if (!notOpenBroswer)
{
if (!string.IsNullOrWhiteSpace(release?.HtmlUrl))
{
// What happens on macOS or Linux?
Process.Start(new ProcessStartInfo(release.HtmlUrl) { UseShellExecute = true });
}
}
}
else
{
Console.WriteLine("GICutscenes is already the latest version.");
}
}
else
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"Cannot compare version, current version is '{currentVersion}', latest version is '{release?.TagName}'.");
Console.ResetColor();
}
}
}
}