-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrossFireLtcDecoder.cs
More file actions
381 lines (331 loc) · 11.9 KB
/
CrossFireLtcDecoder.cs
File metadata and controls
381 lines (331 loc) · 11.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
using System.Diagnostics;
using System.IO;
using System.Text;
namespace CFRezManager;
internal sealed record CrossFireLtcTextDocument(
string Text,
string EncodingName,
string StorageDescription,
int SourceByteCount,
int DecodedByteCount);
internal static class CrossFireLtcDecoder
{
private const int ExternalConverterTimeoutMilliseconds = 15_000;
// CrossFire stores standard LithTech LTC with a small repeating XOR layer.
private static readonly byte[] CrossFireLtcMagic = [0x54, 0x83, 0xB2, 0xE1];
private static readonly byte[] CrossFireLtcXorKey =
[
0x54, 0x83, 0xB2, 0xE1,
0x10, 0x3F, 0x6E, 0x9D,
0xCC, 0xFB, 0x2A, 0x59,
0x88, 0xB7, 0xE6, 0x15
];
public static bool IsCandidate(string extension)
{
return string.Equals(extension, "ltc", StringComparison.OrdinalIgnoreCase);
}
public static bool HasCrossFireMagic(byte[] data)
{
return HasPrefix(data, CrossFireLtcMagic);
}
public static string GetUnsupportedMessage(string? converterError)
{
if (!string.IsNullOrWhiteSpace(converterError))
{
return converterError;
}
return LocalizedText.T("CrossFireLtcUnsupported");
}
public static bool TryUnlockCrossFirePayload(byte[] data, out byte[] unlocked)
{
unlocked = data;
if (!HasCrossFireMagic(data))
{
return false;
}
unlocked = new byte[data.Length];
for (int i = 0; i < data.Length; i++)
{
unlocked[i] = (byte)(data[i] ^ CrossFireLtcXorKey[i & 15]);
}
return true;
}
public static bool TryDecodeText(
byte[] data,
string fallbackName,
out CrossFireLtcTextDocument? document,
out string? errorMessage)
{
document = null;
errorMessage = null;
byte[]? prepared = LzmaAloneDecoder.TryPrepareData(data);
if (prepared is not null &&
TextPreviewDecoder.TryDecode(prepared, preferKorean: false, out string directText, out string directEncoding) &&
LooksLikeStructuredText(directText))
{
string directStorage = ReferenceEquals(prepared, data) ? "LTC text" : "LZMA-compressed LTC";
document = new CrossFireLtcTextDocument(directText, directEncoding, directStorage, data.Length, prepared.Length);
return true;
}
if (TryConvertToText(data, fallbackName, out document, out errorMessage))
{
return true;
}
if (HasCrossFireMagic(data))
{
errorMessage = GetUnsupportedMessage(errorMessage);
return false;
}
errorMessage = string.IsNullOrWhiteSpace(errorMessage)
? LocalizedText.T("LtcNotRecognized")
: errorMessage;
return false;
}
public static bool TryConvertToText(
byte[] ltcData,
string fallbackName,
out CrossFireLtcTextDocument? document,
out string? errorMessage)
{
document = null;
errorMessage = null;
bool isCrossFireLocked = TryUnlockCrossFirePayload(ltcData, out byte[] converterInput);
if (TryDecodeNativeToText(converterInput, ltcData.Length, isCrossFireLocked, out document, out string? nativeError) &&
document is not null)
{
return true;
}
string? converterPath = ResolveLtcConverterPath();
if (converterPath is null)
{
errorMessage = string.IsNullOrWhiteSpace(nativeError)
? LocalizedText.T("LtcNativeAndConverterMissing")
: nativeError;
return false;
}
string workingDirectory = Path.Combine(Path.GetTempPath(), "CFRezManager", "LtcConvert", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(workingDirectory);
string baseName = Path.GetFileNameWithoutExtension(fallbackName);
if (string.IsNullOrWhiteSpace(baseName))
{
baseName = "model";
}
string inputPath = Path.Combine(workingDirectory, $"{baseName}.ltc");
string outputPath = Path.Combine(workingDirectory, $"{baseName}.lta");
File.WriteAllBytes(inputPath, converterInput);
try
{
var startInfo = new ProcessStartInfo
{
FileName = converterPath,
WorkingDirectory = workingDirectory,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
};
AddConverterArguments(startInfo, converterPath, inputPath, outputPath);
using Process? process = Process.Start(startInfo);
if (process is null)
{
errorMessage = LocalizedText.Format("LtcConverterStartFailed", converterPath);
return false;
}
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
if (!process.WaitForExit(ExternalConverterTimeoutMilliseconds))
{
TryKillProcess(process);
errorMessage = LocalizedText.T("LtcConverterTimeout");
return false;
}
string stdout = stdoutTask.GetAwaiter().GetResult();
string stderr = stderrTask.GetAwaiter().GetResult();
if (process.ExitCode != 0 || !File.Exists(outputPath))
{
string detail = string.IsNullOrWhiteSpace(stderr) ? stdout : stderr;
errorMessage = string.IsNullOrWhiteSpace(detail)
? LocalizedText.Format("LtcConverterFailedExitCode", process.ExitCode)
: detail.Trim();
return false;
}
byte[] convertedBytes = File.ReadAllBytes(outputPath);
if (!TextPreviewDecoder.TryDecode(convertedBytes, preferKorean: isCrossFireLocked, out string text, out string encodingName))
{
errorMessage = LocalizedText.T("LtcConverterOutputEncodingUnrecognized");
return false;
}
string storageDescription = isCrossFireLocked ? "CrossFire LTC XOR -> LTA" : "LTC -> LTA";
document = new CrossFireLtcTextDocument(
text,
encodingName,
storageDescription,
ltcData.Length,
convertedBytes.Length);
return true;
}
finally
{
TryDeleteDirectory(workingDirectory);
}
}
private static bool TryDecodeNativeToText(
byte[] converterInput,
int sourceByteCount,
bool isCrossFireLocked,
out CrossFireLtcTextDocument? document,
out string? errorMessage)
{
document = null;
errorMessage = null;
if (!LithTechLtcNativeDecoder.TryDecode(converterInput, out byte[] convertedBytes, out string? nativeError))
{
errorMessage = nativeError;
return false;
}
if (!TextPreviewDecoder.TryDecode(convertedBytes, preferKorean: isCrossFireLocked, out string text, out string encodingName) ||
!LooksLikeStructuredText(text))
{
errorMessage = LocalizedText.T("LtcNativeOutputNotLta");
return false;
}
string storageDescription = isCrossFireLocked ? "CrossFire LTC native -> LTA" : "LTC native -> LTA";
document = new CrossFireLtcTextDocument(
text,
encodingName,
storageDescription,
sourceByteCount,
convertedBytes.Length);
return true;
}
private static string? ResolveLtcConverterPath()
{
string? configured = Environment.GetEnvironmentVariable("CFREZ_LTC_TO_LTA");
if (!string.IsNullOrWhiteSpace(configured) && File.Exists(configured))
{
return configured;
}
string[] relativeCandidates =
[
Path.Combine("tools", "ltc_to_lta.exe"),
Path.Combine("tools", "ltc_to_lta.cmd"),
Path.Combine("tools", "ltc_to_lta.bat"),
Path.Combine("tools", "LTC.exe"),
Path.Combine("tools", "CFLTC_Converter.exe"),
Path.Combine("tools", "guao_ltc.exe"),
Path.Combine("tools", "WinLTC.exe"),
"LTC.exe"
];
foreach (string root in EnumerateToolSearchRoots())
{
foreach (string relativeCandidate in relativeCandidates)
{
string candidate = Path.Combine(root, relativeCandidate);
if (File.Exists(candidate))
{
return candidate;
}
}
}
return null;
}
private static IEnumerable<string> EnumerateToolSearchRoots()
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string root in EnumerateRootAndParents(AppContext.BaseDirectory))
{
if (seen.Add(root))
{
yield return root;
}
}
foreach (string root in EnumerateRootAndParents(Environment.CurrentDirectory))
{
if (seen.Add(root))
{
yield return root;
}
}
}
private static IEnumerable<string> EnumerateRootAndParents(string startPath)
{
DirectoryInfo? directory;
try
{
directory = new DirectoryInfo(Path.GetFullPath(startPath));
}
catch
{
yield break;
}
for (int depth = 0; directory is not null && depth < 8; depth++, directory = directory.Parent)
{
yield return directory.FullName;
}
}
private static void AddConverterArguments(ProcessStartInfo startInfo, string converterPath, string inputPath, string outputPath)
{
string fileName = Path.GetFileName(converterPath);
if (string.Equals(fileName, "LTC.exe", StringComparison.OrdinalIgnoreCase) ||
string.Equals(fileName, "WinLTC.exe", StringComparison.OrdinalIgnoreCase))
{
startInfo.ArgumentList.Add(inputPath);
startInfo.ArgumentList.Add("-out");
startInfo.ArgumentList.Add(outputPath);
return;
}
startInfo.ArgumentList.Add(inputPath);
startInfo.ArgumentList.Add(outputPath);
}
private static bool HasPrefix(byte[] data, byte[] prefix)
{
return data.Length >= prefix.Length && data.AsSpan(0, prefix.Length).SequenceEqual(prefix);
}
private static bool LooksLikeStructuredText(string text)
{
ReadOnlySpan<char> sample = text.AsSpan(0, Math.Min(text.Length, 4096));
if (sample.IsEmpty)
{
return true;
}
int asciiText = 0;
int structural = 0;
foreach (char ch in sample)
{
if (ch is >= ' ' and <= '~' || ch is '\r' or '\n' or '\t')
{
asciiText++;
}
if (ch is '\r' or '\n' or '(' or ')' or '[' or ']' or '{' or '}' or '=' or ':' or '_' or '"' or '\'')
{
structural++;
}
}
return asciiText >= sample.Length * 85 / 100 && structural > 0;
}
private static void TryKillProcess(Process process)
{
try
{
process.Kill(entireProcessTree: true);
}
catch
{
// External converters may already have exited after the timeout check.
}
}
private static void TryDeleteDirectory(string directory)
{
try
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
catch
{
// Temporary conversion files are best-effort cleanup only.
}
}
}