forked from Wouldubeinta/Fmod-Bank-Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrebuild_worker.cpp
More file actions
527 lines (429 loc) · 17.7 KB
/
Copy pathrebuild_worker.cpp
File metadata and controls
527 lines (429 loc) · 17.7 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
#include "rebuild_worker.h"
#include "fileio.h"
#include <fsbank_errors.h>
#include <cstring>
#include <QDataStream>
RebuildWorker::RebuildWorker(QObject *parent) : QObject(parent) {}
void RebuildWorker::rebuild_bank()
{
QString config = QCoreApplication::applicationDirPath() + "/config.ini";
QSettings settings(config, QSettings::IniFormat);
settings.beginGroup("Directorys");
QString fsbDir = QCoreApplication::applicationDirPath() + "/fsb/";
QString bankDir = settings.value("BankDir").toString() + "/";
QString wavDir = settings.value("WavDir").toString() + "/";
QString rebuildDir = settings.value("RebuildDir").toString() + "/";
QString cacheDir = settings.value("CacheDir").toString() + "/";
settings.endGroup();
settings.beginGroup("Options");
QString format = settings.value("Format").toString();
unsigned int quality = settings.value("Quality").toUInt();
unsigned int cpuThreads = settings.value("CPUThreads").toUInt();
QString defaultSettings = settings.value("DefaultSettings").toString();
QString encodeSyncPoint = settings.value("EncodeSyncPoint").toString();
QString looping = settings.value("Looping").toString();
QString embededFileNames = settings.value("EmbededFileNames").toString();
QString writePeakVolume = settings.value("WritePeakVolume").toString();
settings.endGroup();
QStringList nameFilters;
nameFilters << "*.txt";
QDirIterator it(wavDir, nameFilters, QDir::Files, QDirIterator::Subdirectories);
QStringList wavTxtList;
while (it.hasNext()) {
wavTxtList << it.next();
}
if (wavTxtList.isEmpty())
{
emit taskFinished("\nError: could not find txt wav lists !!!");
emit progressUpdated(0);
return;
}
FSBANK_RESULT result;
int i = 0;
for (QString &wavTxt : wavTxtList)
{
QByteArray cacheDirArray = cacheDir.toUtf8();
int cacheDirSize = cacheDirArray.size() + 1;
char* cachedir = new char[cacheDirSize];
std::memcpy(cachedir, cacheDirArray.constData(), cacheDirSize);
result = FSBank_Init(FSBANK_FSBVERSION_FSB5, FSBANK_INIT_GENERATEPROGRESSITEMS, cpuThreads, cachedir);
if (result != FSBANK_OK) { emit taskFinished(FSBank_ErrorString(result)); return; }
std::vector<FSBANK_SUBSOUND> subsounds;
QStringList wavFiles = readTextFileToQStringList(wavTxt);
QFileInfo wavFileInfo(wavTxt);
quint32 removePos = wavFileInfo.completeBaseName().length() - 3;
QString bankName = wavFileInfo.completeBaseName().remove(removePos, 3);
QString bankFileBasePath = bankDir + bankName;
QString bankFilePath = bankFileBasePath + ".bank";
QString passwordTextFile = QDir(bankDir).filePath("password.txt");
QString passwordBankTextFile = bankFileBasePath + ".txt";
QString fsbFilePath = fsbDir + wavFileInfo.completeBaseName() + ".fsb";
QString newLineCheck = (i == 0) ? "" : "\n";
emit updateConsole(newLineCheck + "Fmod Bank file: " + bankName + ".bank");
QString _format = "Vorbis";
if (format == "pcm")
_format = "PCM";
else if (format == "fadpcm")
_format = "FADPCM";
emit updateConsole("Format: " + _format);
emit updateConsole("Thread Count: 2\n");
emit updateConsole("ReBuilding " + bankName + ".bank has started, Please wait.....\n");
if (!QFileInfo::exists(bankFileBasePath + ".bank"))
{
emit updateConsole("Aborting bank rebuilding, can't find - " + bankFileBasePath + ".bank");
result = FSBank_Release();
if (result != FSBANK_OK) { emit taskFinished(FSBank_ErrorString(result)); return; }
continue;
}
QVector<char*> wavFile(wavFiles.size());
for (int j = 0; j < wavFiles.size(); ++j)
{
QString wavFilePath = wavDir + wavFileInfo.completeBaseName() + "/" + wavFiles[j];
QByteArray wavFilePathArray = wavFilePath.toUtf8();
int wavFilePathSize = wavFilePathArray.size() + 1;
wavFile[j] = new char[wavFilePathSize];
std::memcpy(wavFile[j], wavFilePathArray.constData(), wavFilePathSize);
auto &subsound = subsounds.emplace_back();
std::memset(&subsound, 0, sizeof(FSBANK_SUBSOUND));
subsound.numFiles = 1;
subsound.fileNames = &wavFile[j];
}
int fsbFilePathSize = fsbFilePath.toUtf8().size() + 1;
char* outputFile = new char[fsbFilePathSize];
std::memcpy(outputFile, fsbFilePath.toUtf8().constData(), fsbFilePathSize);
char* encryption = nullptr;
// Check if either password text file exists and encrypts bank
if (QFileInfo::exists(passwordTextFile) || QFileInfo::exists(passwordBankTextFile))
{
if (QFileInfo::exists(passwordBankTextFile))
passwordTextFile = passwordBankTextFile;
QString password = readTextFileToQStringList(passwordTextFile).constFirst();
// Ensure the password list is not empty before accessing
if (password.isEmpty()) {
emit updateConsole("Password file is empty: " + passwordTextFile + "\n");
result = FSBank_Release();
if (result != FSBANK_OK) { emit taskFinished(FSBank_ErrorString(result)); return; }
continue;
}
QByteArray encryptionKeyArray = password.toUtf8();
int encryptionKeySize = encryptionKeyArray.size() + 1;
encryption = new char[encryptionKeySize];
std::memcpy(encryption, encryptionKeyArray.constData(), encryptionKeySize);
emit updateConsole("Encrypting bank file with password: " + encryptionKeyArray + "\n");
}
FSBANK_FORMAT fsbankFormat = FSBANK_FORMAT_VORBIS;
if (format == "pcm")
fsbankFormat = FSBANK_FORMAT_PCM;
else if (format == "fadpcm")
fsbankFormat = FSBANK_FORMAT_FADPCM;
FSBANK_BUILDFLAGS fsbankBuildFlags = FSBANK_BUILD_DEFAULT;
if (defaultSettings == "false")
{
if (encodeSyncPoint == "false")
fsbankBuildFlags |= FSBANK_BUILD_DISABLESYNCPOINTS;
if (looping == "false")
fsbankBuildFlags |= FSBANK_BUILD_DONTLOOP;
if (embededFileNames == "false")
fsbankBuildFlags |= FSBANK_BUILD_FSB5_DONTWRITENAMES;
if (writePeakVolume == "true")
fsbankBuildFlags |= FSBANK_BUILD_WRITEPEAKVOLUME;
}
result = FSBank_Build(subsounds.data(), subsounds.size(), fsbankFormat, fsbankBuildFlags, quality, encryption, outputFile);
if (result != FSBANK_OK)
{
emit updateConsole(FSBank_ErrorString(result)); continue;
emit progressUpdated(0);
result = FSBank_Release();
if (result != FSBANK_OK) { emit taskFinished(FSBank_ErrorString(result)); return; }
}
bankProgress(wavFiles);
result = FSBank_Release();
if (result != FSBANK_OK) { emit taskFinished(FSBank_ErrorString(result)); return; }
for (char* file : wavFile)
{
delete[] file;
}
delete[] cachedir;
delete[] outputFile;
delete[] encryption;
bankRebuild(bankFilePath, rebuildDir);
i++;
}
emit progressUpdated(0);
emit taskFinished("\nRebuilding Bank files has finished");
}
void RebuildWorker::bankProgress(const QStringList wavList)
{
// Build process started successfully, now fetch progress items
const FSBANK_PROGRESSITEM* progressItem = nullptr;
int index = 0;
while (FSBank_FetchNextProgressItem(&progressItem) == FSBANK_OK && progressItem != nullptr)
{
// Process the progress item
switch (progressItem->state)
{
case FSBANK_STATE_PREPROCESSING:
// Item is waiting to be processed
break;
case FSBANK_STATE_ANALYSING:
// Item is analysing
break;
case FSBANK_STATE_DECODING:
// Item is decoding
break;
case FSBANK_STATE_ENCODING:
{
// Item is currently being built
break;
}
case FSBANK_STATE_WRITING:
{
// Item is writing
break;
}
case FSBANK_STATE_FINISHED:
{
// Item build complete
if (progressItem->subSoundIndex != -1)
{
emit updateConsole(QString::number(index) + ": (" + wavList[index] + ") [Proccessing]");
int subSoundsPercent = 100 * (index + 1) / wavList.size();
emit progressUpdated(subSoundsPercent); // Emit signal to update progress in UI
index++;
}
break;
}
case FSBANK_STATE_WARNING:
// Item warning
emit updateConsole("\nWarning, there is a issue with one of the wav files.");
break;
case FSBANK_STATE_FAILED:
// Item build failed
emit updateConsole("\nfsb file failed to build.");
break;
default:
emit updateConsole("\nUnknown error");
break;
}
FSBank_ReleaseProgressItem(progressItem); // Release memory for the item
progressItem = nullptr; // Reset for next fetch
QThread::msleep(10);
}
}
void RebuildWorker::bankRebuild(const QString bankFile, const QString buildPath)
{
QFile file(bankFile);
if (!file.open(QIODevice::ReadOnly)) {
emit taskFinished("\nError opening file: " + bankFile);
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_DefaultCompiledVersion);
in.setByteOrder(QDataStream::LittleEndian);
const QByteArray magicArray = readBytes(in, 4);
if (magicArray != "RIFF") {
emit taskFinished("\nError, has no RIFF in header");
return;
}
file.seek(0x08);
const QByteArray fevStringArray = readBytes(in, 4);
if (fevStringArray != "FEV ") {
emit taskFinished("\nError, has no FEV in header");
return;
}
file.seek(0x14);
quint32 version;
in >> version;
if (version == 0) {
emit taskFinished("\nError, version not supported");
return;
}
file.seek(0x1c);
const QByteArray listStringArray = readBytes(in, 4);
if (listStringArray != "LIST") {
emit taskFinished("\nError, has no LIST in header");
return;
}
file.seek(file.pos() + 0x04);
const QByteArray projStringArray = readBytes(in, 4);
const QByteArray BnkiStringArray = readBytes(in, 4);
if (projStringArray != "PROJ" || BnkiStringArray != "BNKI") {
emit taskFinished("\nError, has no PROJ or BNKI in header");
return;
}
QVector<quint32> sndh_fsbOffset, sndh_fsbSize, snd_location, snd_buffer;
quint32 chunk_size, sndh_unknown = 0, fsbCount = 1, sndh_location = 0;
in >> chunk_size;
file.seek(file.pos() + chunk_size);
sndh_fsbOffset.resize(1);
sndh_fsbOffset[0] = 0;
sndh_fsbSize.resize(1);
sndh_fsbSize[0] = 0;
snd_location.resize(1);
snd_location[0] = 0;
while (snd_location[0] == 0 && file.pos() < file.size()) {
quint32 chunk_type;
in >> chunk_type;
in >> chunk_size;
if (chunk_type == 0xFFFFFFFF || chunk_size == 0xFFFFFFFF) {
return; // Invalid chunk
}
switch(chunk_type)
{
case 0x48444E53: /* "SNDH" */
{
fsbCount = (chunk_size - 4) / 8;
sndh_fsbOffset.resize(fsbCount);
sndh_fsbSize.resize(fsbCount);
in >> sndh_unknown;
sndh_location = file.pos();
for (quint32 j = 0; j < fsbCount; j++)
{
in >> sndh_fsbOffset[j];
in >> sndh_fsbSize[j];
}
continue;
}
case 0x4C425453: /* "STBL" */
{
quint64 currentPos = file.pos();
if (chunk_size != 0)
{
file.seek(currentPos + chunk_size);
quint32 chunkTypeHash = 0;
in >> chunkTypeHash;
switch(chunkTypeHash)
{
case 0x20444E53: /* "SND " */
case 0x48534148: /* "HASH" */
break;
default:
chunk_size += 1;
break;
}
}
file.seek(currentPos + chunk_size);
continue;
}
case 0x20444E53: /* "SND " */
{
snd_location.resize(fsbCount);
snd_location[0] = file.pos() - 8;
snd_buffer.resize(fsbCount);
snd_buffer[0] = chunk_size - sndh_fsbSize[0];
if (fsbCount > 1)
{
for (quint32 j = 0; j < fsbCount - 1; j++)
{
snd_location[j + 1] = sndh_fsbOffset[j] + sndh_fsbSize[j];
file.seek(snd_location[j + 1] + 4);
quint32 _chunk_size = 0;
in >> _chunk_size;
snd_buffer[j + 1] = _chunk_size - sndh_fsbSize[j + 1];
}
}
break;
}
}
file.seek(file.pos() + chunk_size);
}
QString bankName = file.fileName();
if (sndh_fsbOffset[0] == 0 || sndh_fsbSize[0] == 0) { emit taskFinished("\nRebuilding Bank Error, sndh_offset or sndh_size should not be 0 for - " + bankName); return; }
if (sndh_location == 0) { emit taskFinished("\nRebuilding Bank Error, sndh_location should not be 0 for - " + bankName); return; }
if (snd_location[0] == 0) { emit taskFinished("\nRebuilding Bank Error, snd_location should not be 0 for - " + bankName); return; }
file.seek(0);
QByteArray bankHeader = readBytes(in, sndh_fsbOffset[0]);
file.close();
QFileInfo fileInfo(bankName);
QString bankNameTmp = fileInfo.fileName();
QFile bankoutFile(buildPath + bankNameTmp);
if (!bankoutFile.open(QIODevice::WriteOnly)) {
emit taskFinished("\nRebuilding Bank Error, writing to: " + buildPath + bankNameTmp);
return;
}
bankoutFile.write(bankHeader, sndh_fsbOffset[0]);
QVector<quint32> fsbSizes;
fsbSizes.resize(fsbCount);
fsbSizes[0] = 0;
QString fsbFileName = QCoreApplication::applicationDirPath() + "/fsb/" + bankNameTmp.replace(".bank", "");
for (quint32 i = 0; i < fsbCount; i++)
{
QString fsbFilePath = fsbFileName + "[" + QString::number(i) + "].fsb";
QFileInfo fileInfo(fsbFilePath);
if (fileInfo.exists()) {
fsbSizes[i] = (quint32)fileInfo.size(); // Returns the fsb size in bytes.
} else {
emit taskFinished("\nRebuilding Bank Error, fsb file does not exist " + fsbFilePath);
return;
}
}
if (fsbCount > 1)
{
for (quint32 i = 0; i < fsbCount - 1; i++)
{
sndh_fsbOffset[i + 1] = sndh_fsbOffset[i] + fsbSizes[i] + snd_buffer[i + 1] + 8; // Adding new fsb offsets, if more then 1 fsb in bank.
}
}
bankoutFile.seek(sndh_location);
for (quint32 i = 0; i < fsbCount; i++)
{
bankoutFile.write(reinterpret_cast<const char*>(&sndh_fsbOffset[i]), 4);
bankoutFile.write(reinterpret_cast<const char*>(&fsbSizes[i]), 4);
}
bankoutFile.flush();
bankoutFile.seek(snd_location[0]);
for (quint32 i = 0; i < fsbCount; i++)
{
QString fsbFilePath = fsbFileName + "[" + QString::number(i) + "].fsb";
QFile fsbInFile(fsbFilePath);
if (!fsbInFile.open(QIODevice::ReadOnly)) {
emit taskFinished("\nRebuilding Bank Error, reading: " + fsbFilePath);
return;
}
QDataStream fsbIn(&fsbInFile);
fsbIn.setVersion(QDataStream::Qt_DefaultCompiledVersion);
fsbIn.setByteOrder(QDataStream::LittleEndian);
bankoutFile.write("SND ");
quint32 fsbTmpSize = fsbSizes[i] + snd_buffer[i];
bankoutFile.write(reinterpret_cast<const char*>(&fsbTmpSize), 4);
quint32 bufferSize = snd_buffer[i];
QByteArray buffer(bufferSize, '\0');
if (bufferSize != 0)
bankoutFile.write(buffer);
quint32 chunkCount = fileio::chunkAmount(fsbSizes[i]);
std::vector<quint64> _chunkSizes = fileio::chunkSizes(fsbSizes[i], chunkCount);
for (unsigned int k = 0; k < chunkCount; k++) {
QByteArray fsbBuffer = readBytes(fsbIn, _chunkSizes[k]);
bankoutFile.write(fsbBuffer);
}
fsbInFile.close();
}
quint32 headerSize = (bankoutFile.size()) - 8;
bankoutFile.seek(4);
bankoutFile.write(reinterpret_cast<const char*>(&headerSize), 4);
bankoutFile.flush();
bankoutFile.close();
}
// Helper function to read bytes
QByteArray RebuildWorker::readBytes(QDataStream &in, int size) {
QByteArray buffer(size, 0);
in.readRawData(buffer.data(), size);
return buffer;
}
QStringList RebuildWorker::readTextFileToQStringList(const QString& filePath) {
QStringList stringList;
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
emit taskFinished("\nCould not open file: " + filePath);
return stringList; // Return empty list if file cannot be opened
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
stringList.append(line);
}
if (stringList.isEmpty()) // prevent's application crash if password is empty.
stringList.append("");
file.close();
return stringList;
}