Repository navigation
Expand file tree
/
Copy pathencode.cpp
More file actions
357 lines (305 loc) · 15.3 KB
/
Copy pathencode.cpp
File metadata and controls
357 lines (305 loc) · 15.3 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
#include "common.h"
#include <filesystem>
#include <set>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <array>
Result<int> RunEncode(const std::string& input_path, const std::string& output_path, bool verbose, int num_threads,
const std::vector<int32_t>& m_ids, const std::vector<int32_t>& opt_levels, bool opt_auto, bool opt_force,
const std::vector<uint8_t>& aesKey, bool useAES, uint32_t tradeoff_bytes, bool quantum_crc) {
std::vector<int32_t> effective_m_ids = m_ids;
if (effective_m_ids.empty()) {
if (opt_auto) {
for (int32_t m : Config::ALL_METHODS) effective_m_ids.push_back(m);
} else {
effective_m_ids.push_back(8);
}
}
ThreadSafeReader reader(input_path);
if (!reader.is_open()) {
return Result<int>(ErrorCode::ERR_FILE_NOT_FOUND, "Failed to open input payload file: " + input_path);
}
uint64_t fSize = reader.get_size();
std::cout << "[ENC] Encoding " << fSize / 1024 / 1024 << " MB using " << num_threads << " threads." << std::endl;
FastStreamWriter fast_out;
if (!fast_out.open(output_path)) {
return Result<int>(ErrorCode::ERR_FILE_NOT_FOUND, "Failed to open output.");
}
PreHeader hdr{};
hdr.magic = 0x50524546;
hdr.version = 34;
hdr.original_size = fSize;
hdr.block_count = 0;
hdr.use_aes = 0;
hdr.space_speed_tradeoff_bytes = tradeoff_bytes;
hdr.quantum_crc = quantum_crc ? 1 : 0;
if (useAES) {
hdr.use_aes = 1;
std::copy(aesKey.begin(), aesKey.end(), hdr.aes_key);
}
try {
fast_out.write(reinterpret_cast<const char*>(&hdr), sizeof(hdr));
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Failed to write header: " + fast_out.get_last_error());
}
} catch(const std::exception& e) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Initial file structure setup failed: " + std::string(e.what()));
}
uint64_t total_out_bytes = sizeof(hdr);
UI ui(fSize, 0, verbose);
BlockScanner scanner(reader, fSize, useAES, aesKey, Config::WIN_SIZE_LARGE);
uint64_t pos = 0;
uint64_t last_out = 0;
std::vector<PreBlock> blocks;
std::deque<std::future<std::shared_ptr<BlockTask>>> pipeline;
uint32_t good_matches_count = 0;
uint32_t fail_count = 0;
std::array<std::atomic<int32_t>, 14> detected_auto_level_by_method;
for (auto& v : detected_auto_level_by_method) v.store(-1);
std::vector<uint32_t> usizes_vec(std::begin(Config::TEST_USIZES), std::end(Config::TEST_USIZES));
ObjectPool<char> gap_pool(num_threads * 2, Config::GAP_POOL_CHUNK);
OodleLZ_CompressOptions opts = {};
opts.version = 232;
opts.spaceSpeedTradeoffBytes = tradeoff_bytes;
opts.sendQuantumCRCs = quantum_crc ? 1 : 0;
std::atomic<bool> fatal_io_error{false};
ThreadPool pool(num_threads);
auto process_single_task = [&](std::shared_ptr<BlockTask> task) -> bool {
try {
if (task->pos > last_out) {
uint64_t gap_size = task->pos - last_out;
if (!write_gap(reader, fast_out, gap_pool, last_out, gap_size)) {
fatal_io_error = true; return false;
}
if (fast_out.has_error()) { fatal_io_error = true; return false; }
total_out_bytes += gap_size;
}
if (task->exact_match_found) {
good_matches_count++;
BlockHeader bh{task->usize};
fast_out.write(reinterpret_cast<const char*>(&bh), sizeof(bh));
if (fast_out.has_error()) { fatal_io_error = true; return false; }
fast_out.write(reinterpret_cast<const char*>(task->dec_data.data()), task->usize);
if (fast_out.has_error()) { fatal_io_error = true; return false; }
total_out_bytes += sizeof(bh) + task->usize;
std::vector<uint8_t> written(sizeof(BlockHeader) + task->usize);
std::memcpy(written.data(), &bh, sizeof(BlockHeader));
std::memcpy(written.data() + sizeof(BlockHeader), task->dec_data.data(), task->usize);
uint32_t crc = CalculateCRC32(written.data(), written.size());
blocks.push_back({
task->pos, static_cast<uint32_t>(sizeof(bh) + bh.stored_size), task->usize, task->csize,
static_cast<uint32_t>(task->matched_method | (task->matched_level << 8)), 1,
static_cast<uint8_t>(task->is_encrypted ? 1 : 0), 0, crc
});
if (verbose) {
std::ostringstream ss;
ss << "Match Found at 0x" << std::hex << task->pos << std::dec
<< " | " << task->usize << " -> " << task->csize
<< " [Lvl " << task->matched_level << " Mth:" << task->matched_method << "]";
ui.log(ss.str());
}
} else {
fail_count++;
fast_out.write(reinterpret_cast<const char*>(task->raw_win_buf.data()), task->csize);
if (fast_out.has_error()) { fatal_io_error = true; return false; }
total_out_bytes += task->csize;
uint32_t crc = CalculateCRC32(task->raw_win_buf.data(), task->csize);
blocks.push_back({
task->pos, task->csize, task->usize, task->csize,
static_cast<uint32_t>(effective_m_ids[0]), 0,
static_cast<uint8_t>(task->is_encrypted ? 1 : 0), 0, crc
});
if (verbose) {
std::ostringstream ss;
ss << "Match Failed at 0x" << std::hex << task->pos << std::dec << " | Tracked and stored verbatim.";
ui.log(ss.str());
}
}
} catch(const std::exception& e) {
std::cerr << "\n[FATAL] I/O error writing output: " << e.what() << std::endl;
fatal_io_error = true;
return false;
}
last_out = task->pos + task->csize;
task->raw_win_buf.clear();
task->dec_data.clear();
return true;
};
auto last_ui_time = std::chrono::steady_clock::now();
while (true) {
auto task = scanner.extract_next_block(pos, fSize, usizes_vec);
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_ui_time).count() >= 500) {
ui.set_stats(good_matches_count, fail_count);
ui.update(pos, static_cast<uint32_t>(blocks.size()), "ENC", total_out_bytes);
last_ui_time = now;
}
if (!task) break;
pipeline.push_back(pool.enqueue([&effective_m_ids, opt_levels, opt_auto, opt_force, &detected_auto_level_by_method, &opts, task]() {
static ReusableBufferPool<uint8_t> g_enc_scratch_pool;
static ReusableBufferPool<uint8_t> g_enc_buf_pool;
PooledBuffer<uint8_t> scratch_mem(g_enc_scratch_pool, 8 * 1024 * 1024);
size_t required_size = static_cast<size_t>(task->usize) * 2 + 65536;
PooledBuffer<uint8_t> local_buf_vec(g_enc_buf_pool, required_size);
uint8_t* local_buf = local_buf_vec.data();
int32_t static_levels[10];
int static_num_levels = 0;
bool use_static_levels = !opt_auto;
if (!opt_levels.empty()) {
for (int32_t l : opt_levels) static_levels[static_num_levels++] = l;
use_static_levels = true;
} else if (opt_auto) {
// handled per-method
} else if (opt_force) {
int32_t def_lvls[] = {3, 4, 5, 6, 7, 8, 9};
for (int32_t l : def_lvls) static_levels[static_num_levels++] = l;
} else {
int32_t def_lvls[] = {4, 5, 6, 7};
for (int32_t l : def_lvls) static_levels[static_num_levels++] = l;
}
auto try_method = [&](int32_t method) -> bool {
if (static_num_levels > 0) {
for (int i = 0; i < static_num_levels; ++i) {
int32_t test_level = static_levels[i];
int64_t res = OodleLZ_Compress(method, task->dec_data.data(), task->usize,
local_buf, test_level, &opts, nullptr, nullptr, scratch_mem.data(), scratch_mem.size());
if (res > 0 && res == static_cast<int64_t>(task->csize) &&
std::memcmp(task->raw_win_buf.data(), local_buf, task->csize) == 0) {
task->exact_match_found = true;
task->matched_level = test_level;
task->matched_method = method;
return true;
}
}
return false;
}
if (opt_auto) {
int32_t cached = (method >= 0 && method < (int32_t)detected_auto_level_by_method.size())
? detected_auto_level_by_method[method].load() : -1;
std::vector<int32_t> levels_to_try = (cached != -1) ? std::vector<int32_t>{cached} : std::vector<int32_t>{4, 6, 7};
for (int32_t test_level : levels_to_try) {
int64_t res = OodleLZ_Compress(method, task->dec_data.data(), task->usize,
local_buf, test_level, &opts, nullptr, nullptr, scratch_mem.data(), scratch_mem.size());
if (res > 0 && res == static_cast<int64_t>(task->csize) && std::memcmp(task->raw_win_buf.data(), local_buf, task->csize) == 0) {
task->exact_match_found = true;
task->matched_level = test_level;
task->matched_method = method;
if (cached == -1 && method >= 0 && method < (int32_t)detected_auto_level_by_method.size()) {
detected_auto_level_by_method[method].store(test_level);
}
return true;
}
}
}
return false;
};
int32_t known_method = task->matched_method;
bool is_allowed = false;
for (int32_t m : effective_m_ids) {
if (m == known_method) { is_allowed = true; break; }
}
if (is_allowed && try_method(known_method)) {
return task;
}
for (int32_t method : effective_m_ids) {
if (is_allowed && method == known_method) continue;
if (try_method(method)) return task;
}
return task;
}));
while (pipeline.size() >= static_cast<size_t>(num_threads) * 2) {
std::shared_ptr<BlockTask> completed;
try {
completed = pipeline.front().get();
} catch (const std::exception& e) {
std::cerr << "[FATAL] Task exception: " << e.what() << std::endl;
fatal_io_error = true;
break;
}
pipeline.pop_front();
if (fatal_io_error) break;
if (!process_single_task(completed)) {
break;
}
}
if (fatal_io_error) break;
}
while (!pipeline.empty() && !fatal_io_error) {
std::shared_ptr<BlockTask> completed;
try {
completed = pipeline.front().get();
} catch (const std::exception& e) {
std::cerr << "[FATAL] Task exception: " << e.what() << std::endl;
fatal_io_error = true;
break;
}
pipeline.pop_front();
if (!process_single_task(completed)) break;
}
if (fatal_io_error) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "I/O error during encoding. Output may be incomplete.");
}
try {
if (fSize > last_out) {
uint64_t final_gap_size = fSize - last_out;
if (!write_gap(reader, fast_out, gap_pool, last_out, final_gap_size)) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Failed to write final gap.");
}
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Final gap write failed: " + fast_out.get_last_error());
}
total_out_bytes += final_gap_size;
fast_out.flush();
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Flush failed: " + fast_out.get_last_error());
}
}
hdr.block_count = static_cast<uint32_t>(blocks.size());
uint64_t metadata_size = blocks.size() * sizeof(PreBlock);
fast_out.write(reinterpret_cast<const char*>(blocks.data()), metadata_size);
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Failed to write block metadata: " + fast_out.get_last_error());
}
total_out_bytes += metadata_size;
fast_out.seekp(0);
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Seek failed: " + fast_out.get_last_error());
}
fast_out.write(reinterpret_cast<const char*>(&hdr), sizeof(hdr));
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Failed to rewrite header: " + fast_out.get_last_error());
}
fast_out.flush();
if (fast_out.has_error()) {
return Result<int>(ErrorCode::ERR_UNKNOWN, "Final flush failed: " + fast_out.get_last_error());
}
} catch (const std::exception& e) {
return Result<int>(ErrorCode::ERR_UNKNOWN, std::string("Finalization I/O write failed: ") + e.what());
}
uint32_t total = good_matches_count + fail_count;
double match_pct = total > 0 ? static_cast<double>(good_matches_count) / total * 100.0 : 0.0;
std::set<int32_t> u_methods, u_levels;
for (const auto& b : blocks) {
if (b.exact_match) {
u_methods.insert(b.compressor & 0xFF);
u_levels.insert(b.compressor >> 8);
}
}
std::string method_str, level_str;
for (int m : u_methods) method_str += std::to_string(m) + "+";
for (int l : u_levels) level_str += std::to_string(l) + "+";
if (!method_str.empty()) method_str.pop_back();
if (!level_str.empty()) level_str.pop_back();
uint64_t final_size = total_out_bytes;
std::cout << std::endl << "--- Encoder Processing Metrics ---" << std::endl
<< "Input File Size: " << fSize / 1024.0 / 1024.0 << " MB" << std::endl
<< "Processed Output Size: " << final_size / 1048576.0 << " MB" << std::endl
<< "Exact Matches: " << good_matches_count << " (" << std::fixed << std::setprecision(2) << match_pct << "%)" << std::endl
<< "Full Fails: " << fail_count << std::endl
<< "Methods Used: " << (method_str.empty() ? "None" : method_str) << std::endl
<< "Levels Used: " << (level_str.empty() ? "None" : level_str) << std::endl
<< "Total Duration: " << ui.format_time(ui.get_elapsed()) << std::endl
<< "Mode: Async Buffered I/O (32MB Ring - Safe)" << std::endl;
return Result<int>(0);
}