Repository navigation
Expand file tree
/
Copy pathextract_worker.cpp
More file actions
446 lines (376 loc) · 17.2 KB
/
Copy pathextract_worker.cpp
File metadata and controls
446 lines (376 loc) · 17.2 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
#include "extract_worker.h"
#include "fileio.h"
#include "bank_extract.h"
ExtractWorker::ExtractWorker(QObject *parent) : QObject(parent) {}
void ExtractWorker::extract_fsb()
{
ErrorChecks errorChecks = ErrorChecks::Success;
FMOD_RESULT result;
FMOD_SYSTEM *system = nullptr;
FMOD_SOUND *sound = nullptr;
// Initialize FMOD extended info structure
FMOD_CREATESOUNDEXINFO exinfo = {};
memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO));
exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO);
exinfo.length = 0;
// Load directory paths from config.ini
QString config = QString("%1/config.ini").arg(QCoreApplication::applicationDirPath());
QSettings settings(config, QSettings::IniFormat);
settings.beginGroup("Directorys");
QString fsbDir = QString("%1/fsb/").arg(QCoreApplication::applicationDirPath());
QString bankDir = QString("%1/").arg(fileio::resolveFolderPath(settings.value("BankDir").toString()));
QString wavDir = QString("%1/").arg(fileio::resolveFolderPath(settings.value("WavDir").toString()));
settings.endGroup();
// Scan the bank directory for all .bank files
QDir bank_directory(bankDir);
QStringList bankFileList = bank_directory.entryList(QStringList() << "*.bank");
int i = 0;
// Iterate through every detected FMOD bank file
for (QString &bankFile : bankFileList)
{
QString bankPath = bankDir + bankFile;
QFileInfo bankFileInfo(bankPath);
quint32 fsbCount;
// Extract raw FSB files out of the FMOD bank
errorChecks = bank_extract::extract(bankPath, fsbCount);
QString newLineCheck = (i == 0) ? "" : "\n";
emit updateConsole(QString("%1***** Initializing Fmod Bank file - %2 *****").arg(newLineCheck, QFileInfo(bankPath).fileName()));
// Handle bank extraction errors (e.g., bank is encrypted or file not found errors!!!!)
if (errorChecks != ErrorChecks::Success)
{
errorChecks = handleExtractionError(errorChecks, bankFile, bankPath, exinfo);
if (errorChecks != ErrorChecks::Success)
{
// If handleExtractionError allocated a key before failing,
// free it and reset to nullptr so it doesn't leak or crash the next loop iteration.
delete[] exinfo.encryptionkey;
exinfo.encryptionkey = nullptr;
continue;
}
}
QString fsbName = QFileInfo(bankPath).fileName().replace(".bank", "");
// Process each FSB sub-file inside the bank
for (quint32 j = 0; j < fsbCount; j++)
{
QString fsbPath = QString("%1%2[%3].fsb").arg(fsbDir, fsbName, QString::number(j));
if (!QFileInfo::exists(fsbPath))
{
emit updateConsole(QString("Error, %1[%2].fsb file is missing !!!").arg(fsbName, QString::number(j)));
continue;
}
// Reset loop-scoped pointers to prevent corruption from previous passes
system = nullptr;
sound = nullptr;
// Initialize a temporary FMOD system context for this FSB file
result = FMOD_System_Create(&system);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
continue;
}
result = FMOD_System_Init(system, 1, FMOD_INIT_NORMAL, nullptr);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_System_Release(system); // Prevent FMOD system handle leak
continue;
}
// Open the FSB file using FMOD to parse its sound structures
result = FMOD_System_CreateSound(system, fsbPath.toUtf8().constData(), FMOD_OPENONLY, &exinfo, &sound);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_System_Release(system); // Prevent FMOD system handle leak
continue;
}
// Create target folder for the exported wav files
QDir dir(wavDir);
dir.mkdir(QString("%1[%2]").arg(bankFileInfo.fileName().replace(".bank", ""), QString::number(j)));
emit updateConsole(QString("\nExtracting fsb file - %1\n").arg(QFileInfo(fsbPath).fileName()));
// Extract the actual audio files inside the FSB container
errorChecks = processSubSounds(sound, bankFileInfo, wavDir, j);
// Ensures resources close gracefully on both success or failure
if (sound)
FMOD_Sound_Release(sound);
if (system)
FMOD_System_Release(system);
}
// Delete the allocation and clear the pointer address.
delete[] exinfo.encryptionkey;
exinfo.encryptionkey = nullptr;
progressUpdated(0);
i++;
}
// Report final worker results to UI threads
if (errorChecks == ErrorChecks::Success)
emit taskFinished(GlobalErrors::errorToString(ErrorChecks::ExtSuccess));
else if (bankFileList.count() == 0)
emit taskFinished(GlobalErrors::errorToString(ErrorChecks::BankFileNotFound));
else
emit taskFinished("Bank Extraction was unsuccesful !!!!");
emit progressUpdated(0);
}
ErrorChecks ExtractWorker::handleExtractionError(ErrorChecks errorChecks, const QString &bankFile, QString bankPath, FMOD_CREATESOUNDEXINFO &exinfo)
{
switch (errorChecks)
{
case ErrorChecks::InvalidRIFF:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidRIFF) + bankFile);
break;
case ErrorChecks::InvalidFEV:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidFEV) + bankFile);
break;
case ErrorChecks::InvalidVersion:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidVersion) + bankFile);
break;
case ErrorChecks::InvalidLIST:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidLIST) + bankFile);
break;
case ErrorChecks::InvalidPROJ:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidPROJ) + bankFile);
break;
case ErrorChecks::InvalidBNKI:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidBNKI) + bankFile);
break;
case ErrorChecks::InvalidChunk:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::InvalidChunk) + bankFile);
break;
case ErrorChecks::ExtSndhOffsetSizeError:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::ExtSndhOffsetSizeError) + bankFile);
break;
case ErrorChecks::NoFSBFoundInBank:
emit updateConsole(GlobalErrors::errorToString(ErrorChecks::NoFSBFoundInBank) + bankFile);
break;
case ErrorChecks::IsEncrypted:
return handlePasswordProtectedBank(bankPath, exinfo);
break;
default:
emit updateConsole(QString("Unknown error with bank file: %1").arg(bankFile));
break;
}
return ErrorChecks::Success;
}
ErrorChecks ExtractWorker::handlePasswordProtectedBank(QString bankPath, FMOD_CREATESOUNDEXINFO &exinfo)
{
QFileInfo bankInfo(bankPath);
QString passwordTextFile = QDir(bankInfo.path()).filePath("password.txt");
QString passwordBankTextFile = QDir(bankInfo.path()).filePath(QString("%1.txt").arg(bankInfo.baseName()));
// Determine the correct password file to use.
if (QFileInfo::exists(passwordTextFile)) {
if (QFileInfo::exists(passwordBankTextFile))
passwordTextFile = passwordBankTextFile; // Prefer bank-specific password file for bank.
}
else if (QFileInfo::exists(passwordBankTextFile))
passwordTextFile = passwordBankTextFile; // Use bank-specific password file if default is missing.
else {
emit updateConsole(QString("%1%2 with password for decryption.").arg(GlobalErrors::errorToString(ErrorChecks::PasswordFileNotFound), passwordBankTextFile));
return ErrorChecks::PasswordFileNotFound; // Indicate password.txt failure
}
QString password = fileio::readTextFileToQStringList(passwordTextFile).constFirst(); // read first line in text file for password.
// Handle empty password case.
if (password.isEmpty()) {
emit updateConsole(QString("%1%2\n").arg(GlobalErrors::errorToString(ErrorChecks::PasswordEmpty), passwordTextFile));
return ErrorChecks::PasswordEmpty; // Indicate password empty failure
}
// Convert password to QByteArray and manage memory safely
QByteArray encryptionKeyArray = password.toUtf8();
char* encryption = new char[encryptionKeyArray.size() + 1];
std::memcpy(encryption, encryptionKeyArray.constData(), encryptionKeyArray.size() + 1);
exinfo.encryptionkey = encryption;
// Emit console update based on password availability
emit updateConsole(QString("Decrypting bank file with password: %1").arg(encryptionKeyArray));
return ErrorChecks::Success;
}
ErrorChecks ExtractWorker::processSubSounds(FMOD_SOUND *sound, QFileInfo bankFileInfo, const QString &wavDir, quint32 fsbIndex)
{
FMOD_RESULT result;
int numsubsounds = 0;
QString wavPath = QString("%1%2[%3]/")
.arg(wavDir,
bankFileInfo.fileName().replace(".bank", ""),
QString::number(fsbIndex));
QDir dir(wavPath);
if (dir.exists()) {
// Remove the wav directory and all its contents
dir.removeRecursively();
// Recreate the empty wav directory
dir.mkpath(wavPath);
}
result = FMOD_Sound_GetNumSubSounds(sound, &numsubsounds);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
return ErrorChecks::WriteFailure;
}
QStringList txtFileNames;
for (int j = 0; j < numsubsounds; j++)
{
// Initialize pointers to nullptr to safely handle cleanups
FMOD_SOUND *sound_to_play = nullptr;
FMOD_SOUND_TYPE stype;
FMOD_SOUND_FORMAT sformat;
// Increased nameLength from 64 to 256
unsigned int length = 0, dataLen = 0, nameLength = 256;
int schannels = 0, sbits = 0, priority = 0;
// Increased subsoundsName from 64 to 256
char subsoundsName[256];
char* buffer = nullptr;
float ssamplerate = 0;
// Fetch the subsound handle from FMOD container
result = FMOD_Sound_GetSubSound(sound, j, &sound_to_play);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
return ErrorChecks::WriteFailure; // No handle allocated yet, safe to return early
}
// --- Beyond this point, sound_to_play MUST be released if an error occurs ---
result = FMOD_Sound_SeekData(sound_to_play, 0);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
result = FMOD_Sound_GetDefaults(sound_to_play, &ssamplerate, &priority);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
result = FMOD_Sound_GetFormat(sound_to_play, &stype, &sformat, &schannels, &sbits);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
result = FMOD_Sound_GetLength(sound_to_play, &length, FMOD_TIMEUNIT_PCMBYTES);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
result = FMOD_Sound_GetName(sound_to_play, subsoundsName, nameLength);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
QString subsoundName = QString::fromUtf8(subsoundsName);
// If no filename, generate a fallback name
if (subsoundName.isEmpty())
subsoundName = QString("sound_%1").arg(QString::number(j));
QDir dir(wavPath);
QString baseName = subsoundName;
QString fileName = QString("%1.wav").arg(baseName);
// Loop until a unique filename is found
for (int suffix = j; dir.exists(fileName); ++suffix) {
subsoundName = QString("%1_%2").arg(baseName, QString::number(suffix));
fileName = QString("%1.wav").arg(subsoundName);
}
QString wavName = dir.absoluteFilePath(fileName);
QFile file(wavName);
// Check if the wav file opens for writing
if (!file.open(QIODevice::WriteOnly)) {
emit updateConsole("Wav File is not open for writing.");
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
// RIFF/WAVE HEADER SETUP
// Assemble standard RIFF specification header using calculated stream dimensions.
WAVHeader header;
header.headerLength = 38 + length;
header.numChannels = schannels;
header.sampleRate = ssamplerate;
int16_t bytesPerSample = sbits / 8;
header.bytesPerSecond = ssamplerate * schannels * bytesPerSample;
header.bytesPerSample = bytesPerSample;
header.bitsPerChannel = sbits;
header.dataSize = length;
// Commit the header payload block directly to the start of the WAV file.
qint64 headerError = file.write(reinterpret_cast<const char*>(&header), sizeof(header)) != sizeof(header);
if (headerError == -1) {
file.close();
emit updateConsole("Error: Failed to write wav header data!!!");
emit progressUpdated(0);
return ErrorChecks::WriteFailure;
}
quint32 chunkCount = fileio::chunkAmount(length);
std::vector<quint64> _chunkSizes = fileio::chunkSizes(length, chunkCount);
bool chunkError = false;
// Process audio stream chunks
for (unsigned int k = 0; k < chunkCount; k++)
{
buffer = (char*)malloc(_chunkSizes[k]);
if (buffer == nullptr)
{
emit updateConsole("Error: Memory allocation failed for audio data chunk.");
emit progressUpdated(0);
chunkError = true;
break;
}
result = FMOD_Sound_ReadData(sound_to_play, buffer, _chunkSizes[k], &dataLen);
if (result != FMOD_OK)
{
emit updateConsole(FMOD_ErrorString(result));
emit progressUpdated(0);
free(buffer);
buffer = nullptr;
chunkError = true;
break;
}
qint64 chunkWriteError = file.write(buffer, _chunkSizes[k]);
if (chunkWriteError == -1)
{
file.close();
emit updateConsole("Error: Failed to write raw wav chunk audio data!!!");
emit progressUpdated(0);
free(buffer);
buffer = nullptr;
chunkError = true;
break;
}
free(buffer); // Safely release the individual chunk heap allocation
buffer = nullptr;
}
// Explicitly close the file handle
file.flush();
file.close();
// If an error occurred inside the chunk loop, clean up the sub sound and exit
if (chunkError)
{
FMOD_Sound_Release(sound_to_play);
return ErrorChecks::WriteFailure;
}
// Post UI statistics updates
int subSoundsPercent = 100 * (j + 1) / numsubsounds;
emit progressUpdated(subSoundsPercent);
QString index = QString::number(j);
txtFileNames << QString("%1.wav").arg(subsoundName);
emit updateConsole(QString("%1: (%2.wav) [Extracting]").arg(index, subsoundName));
// Always release the sub sound handle at the iteration end
FMOD_Sound_Release(sound_to_play);
}
// Save fsb track list to txt file
writeFilenamesToFile(txtFileNames,
QString("%1%2[%3].txt")
.arg(wavPath,
bankFileInfo.fileName().replace(".bank", ""),
QString::number(fsbIndex)));
return ErrorChecks::Success;
}
void ExtractWorker::writeFilenamesToFile(const QStringList &filenames, const QString &outputFilePath) {
QFile file(outputFilePath);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
for (const QString &filename : filenames) {
out << filename << "\n"; // Write each filename followed by a newline
}
file.close();
} else {
emit updateConsole(QString("Error opening file for writing: %1").arg(file.errorString()));
}
}