Debian Codegraph @

Source/Core/DiscIO/WIABlob.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DiscIO/WIABlob.h"
5
6 #include <algorithm>
7 #include <array>
8 #include <cstring>
9 #include <expected>
10 #include <limits>
11 #include <map>
12 #include <memory>
13 #include <mutex>
14 #include <optional>
15 #include <type_traits>
16 #include <utility>
17
18 #include <fmt/format.h>
19 #include <zstd.h>
20
21 #include "Common/Align.h"
22 #include "Common/Assert.h"
23 #include "Common/BitUtils.h"
24 #include "Common/CommonTypes.h"
25 #include "Common/Crypto/SHA1.h"
26 #include "Common/FileUtil.h"
27 #include "Common/Logging/Log.h"
28 #include "Common/MsgHandler.h"
29 #include "Common/ScopeGuard.h"
30 #include "Common/Swap.h"
31
32 #include "DiscIO/Blob.h"
33 #include "DiscIO/DiscUtils.h"
34 #include "DiscIO/Filesystem.h"
35 #include "DiscIO/LaggedFibonacciGenerator.h"
36 #include "DiscIO/MultithreadedCompressor.h"
37 #include "DiscIO/Volume.h"
38 #include "DiscIO/VolumeWii.h"
39 #include "DiscIO/WIACompression.h"
40 #include "DiscIO/WiiEncryptionCache.h"
41
42 namespace DiscIO
43 {
44 static void PushBack(std::vector<u8>* vector, const u8* begin, const u8* end)
45 {
46 const size_t offset_in_vector = vector->size();
47 vector->resize(offset_in_vector + (end - begin));
48 std::copy(begin, end, vector->data() + offset_in_vector);
49 }
50
51 template <typename T>
52 static void PushBack(std::vector<u8>* vector, const T& x)
53 {
54 static_assert(std::is_trivially_copyable_v<T>);
55
56 const u8* x_ptr = reinterpret_cast<const u8*>(&x);
57 PushBack(vector, x_ptr, x_ptr + sizeof(T));
58 }
59
60 std::pair<int, int> GetAllowedCompressionLevels(WIARVZCompressionType compression_type, bool gui)
61 {
62 switch (compression_type)
63 {
64 case WIARVZCompressionType::Bzip2:
65 case WIARVZCompressionType::LZMA:
66 case WIARVZCompressionType::LZMA2:
67 return {1, 9};
68 case WIARVZCompressionType::Zstd:
69 // The actual minimum level can be gotten by calling ZSTD_minCLevel(). However, returning that
70 // would make the UI rather weird, because it is a negative number with very large magnitude.
71 // Note: Level 0 is a special number which means "default level" (level 3 as of this writing).
72 if (gui)
73 return {1, ZSTD_maxCLevel()};
74 else
75 return {ZSTD_minCLevel(), ZSTD_maxCLevel()};
76 default:
77 return {0, -1};
78 }
79 }
80
81 template <bool RVZ>
82 WIARVZFileReader<RVZ>::WIARVZFileReader(File::DirectIOFile file, const std::string& path)
83 : m_file(std::move(file)), m_path(path), m_encryption_cache(this)
84 {
85 m_valid = Initialize(path);
86 }
87
88 template <bool RVZ>
89 WIARVZFileReader<RVZ>::~WIARVZFileReader() = default;
90
91 template <bool RVZ>
92 bool WIARVZFileReader<RVZ>::Initialize(const std::string& path)
93 {
94 if (!m_file.Seek(0, File::SeekOrigin::Begin) ||
95 !m_file.Read(Common::AsWritableU8Span(m_header_1)))
96 {
97 return false;
98 }
99
100 if ((!RVZ && m_header_1.magic != WIA_MAGIC) || (RVZ && m_header_1.magic != RVZ_MAGIC))
101 return false;
102
103 const u32 version = RVZ ? RVZ_VERSION : WIA_VERSION;
104 const u32 version_read_compatible =
105 RVZ ? RVZ_VERSION_READ_COMPATIBLE : WIA_VERSION_READ_COMPATIBLE;
106
107 const u32 file_version = Common::swap32(m_header_1.version);
108 const u32 file_version_compatible = Common::swap32(m_header_1.version_compatible);
109
110 if (version < file_version_compatible || version_read_compatible > file_version)
111 {
112 ERROR_LOG_FMT(DISCIO, "Unsupported version {} in {}", VersionToString(file_version), path);
113 return false;
114 }
115
116 const auto header_1_actual_hash = Common::SHA1::CalculateDigest(
117 reinterpret_cast<const u8*>(&m_header_1), sizeof(m_header_1) - Common::SHA1::DIGEST_LEN);
118 if (m_header_1.header_1_hash != header_1_actual_hash)
119 return false;
120
121 if (Common::swap64(m_header_1.wia_file_size) != m_file.GetSize())
122 {
123 ERROR_LOG_FMT(DISCIO, "File size is incorrect for {}", path);
124 return false;
125 }
126
127 const u32 header_2_size = Common::swap32(m_header_1.header_2_size);
128 const u32 header_2_min_size = sizeof(WIAHeader2) - sizeof(WIAHeader2::compressor_data);
129 if (header_2_size < header_2_min_size)
130 return false;
131
132 std::vector<u8> header_2(header_2_size);
133 if (!m_file.Read(header_2))
134 return false;
135
136 const auto header_2_actual_hash = Common::SHA1::CalculateDigest(header_2);
137 if (m_header_1.header_2_hash != header_2_actual_hash)
138 return false;
139
140 std::memcpy(&m_header_2, header_2.data(), std::min(header_2.size(), sizeof(WIAHeader2)));
141
142 if (m_header_2.compressor_data_size > sizeof(WIAHeader2::compressor_data) ||
143 header_2_size < header_2_min_size + m_header_2.compressor_data_size)
144 {
145 return false;
146 }
147
148 const u32 chunk_size = Common::swap32(m_header_2.chunk_size);
149 const auto is_power_of_two = [](u32 x) { return (x & (x - 1)) == 0; };
150 if ((!RVZ || chunk_size < VolumeWii::BLOCK_TOTAL_SIZE || !is_power_of_two(chunk_size)) &&
151 chunk_size % VolumeWii::GROUP_TOTAL_SIZE != 0)
152 {
153 return false;
154 }
155
156 const u32 compression_type = Common::swap32(m_header_2.compression_type);
157 m_compression_type = static_cast<WIARVZCompressionType>(compression_type);
158 if (m_compression_type > (RVZ ? WIARVZCompressionType::Zstd : WIARVZCompressionType::LZMA2) ||
159 (RVZ && m_compression_type == WIARVZCompressionType::Purge))
160 {
161 ERROR_LOG_FMT(DISCIO, "Unsupported compression type {} in {}", compression_type, path);
162 return false;
163 }
164
165 const size_t number_of_partition_entries = Common::swap32(m_header_2.number_of_partition_entries);
166 const size_t partition_entry_size = Common::swap32(m_header_2.partition_entry_size);
167 std::vector<u8> partition_entries(partition_entry_size * number_of_partition_entries);
168 if (!m_file.OffsetRead(Common::swap64(m_header_2.partition_entries_offset), partition_entries))
169 {
170 return false;
171 }
172
173 const auto partition_entries_actual_hash = Common::SHA1::CalculateDigest(partition_entries);
174 if (m_header_2.partition_entries_hash != partition_entries_actual_hash)
175 return false;
176
177 const size_t copy_length = std::min(partition_entry_size, sizeof(PartitionEntry));
178 const size_t memset_length = sizeof(PartitionEntry) - copy_length;
179 u8* ptr = partition_entries.data();
180 m_partition_entries.resize(number_of_partition_entries);
181 for (size_t i = 0; i < number_of_partition_entries; ++i, ptr += partition_entry_size)
182 {
183 std::memcpy(&m_partition_entries[i], ptr, copy_length);
184 std::memset(reinterpret_cast<u8*>(&m_partition_entries[i]) + copy_length, 0, memset_length);
185 }
186
187 for (size_t i = 0; i < m_partition_entries.size(); ++i)
188 {
189 const std::array<PartitionDataEntry, 2>& entries = m_partition_entries[i].data_entries;
190
191 size_t non_empty_entries = 0;
192 for (size_t j = 0; j < entries.size(); ++j)
193 {
194 const u32 number_of_sectors = Common::swap32(entries[j].number_of_sectors);
195 if (number_of_sectors != 0)
196 {
197 ++non_empty_entries;
198
199 const u32 last_sector = Common::swap32(entries[j].first_sector) + number_of_sectors;
200 m_data_entries.emplace(last_sector * VolumeWii::BLOCK_TOTAL_SIZE, DataEntry(i, j));
201 }
202 }
203
204 if (non_empty_entries > 1)
205 {
206 if (Common::swap32(entries[0].first_sector) > Common::swap32(entries[1].first_sector))
207 return false;
208 }
209 }
210
211 const u32 number_of_raw_data_entries = Common::swap32(m_header_2.number_of_raw_data_entries);
212 m_raw_data_entries.resize(number_of_raw_data_entries);
213 Chunk& raw_data_entries =
214 ReadCompressedData(Common::swap64(m_header_2.raw_data_entries_offset),
215 Common::swap32(m_header_2.raw_data_entries_size),
216 number_of_raw_data_entries * sizeof(RawDataEntry), m_compression_type);
217 if (!raw_data_entries.ReadAll(&m_raw_data_entries))
218 return false;
219
220 for (size_t i = 0; i < m_raw_data_entries.size(); ++i)
221 {
222 const RawDataEntry& entry = m_raw_data_entries[i];
223 const u64 data_size = Common::swap64(entry.data_size);
224 if (data_size != 0)
225 m_data_entries.emplace(Common::swap64(entry.data_offset) + data_size, DataEntry(i));
226 }
227
228 const u32 number_of_group_entries = Common::swap32(m_header_2.number_of_group_entries);
229 m_group_entries.resize(number_of_group_entries);
230 Chunk& group_entries =
231 ReadCompressedData(Common::swap64(m_header_2.group_entries_offset),
232 Common::swap32(m_header_2.group_entries_size),
233 number_of_group_entries * sizeof(GroupEntry), m_compression_type);
234 if (!group_entries.ReadAll(&m_group_entries))
235 return false;
236
237 if (HasDataOverlap())
238 return false;
239
240 return true;
241 }
242
243 template <bool RVZ>
244 bool WIARVZFileReader<RVZ>::HasDataOverlap() const
245 {
246 for (size_t i = 0; i < m_partition_entries.size(); ++i)
247 {
248 const std::array<PartitionDataEntry, 2>& entries = m_partition_entries[i].data_entries;
249 for (size_t j = 0; j < entries.size(); ++j)
250 {
251 if (Common::swap32(entries[j].number_of_sectors) == 0)
252 continue;
253
254 const u64 data_offset = Common::swap32(entries[j].first_sector) * VolumeWii::BLOCK_TOTAL_SIZE;
255 const auto it = m_data_entries.upper_bound(data_offset);
256 if (it == m_data_entries.end())
257 return true; // Not an overlap, but an error nonetheless
258 if (!it->second.is_partition || it->second.index != i || it->second.partition_data_index != j)
259 return true; // Overlap
260 }
261 }
262
263 for (size_t i = 0; i < m_raw_data_entries.size(); ++i)
264 {
265 if (Common::swap64(m_raw_data_entries[i].data_size) == 0)
266 continue;
267
268 const u64 data_offset = Common::swap64(m_raw_data_entries[i].data_offset);
269 const auto it = m_data_entries.upper_bound(data_offset);
270 if (it == m_data_entries.end())
271 return true; // Not an overlap, but an error nonetheless
272 if (it->second.is_partition || it->second.index != i)
273 return true; // Overlap
274 }
275
276 return false;
277 }
278
279 template <bool RVZ>
280 std::unique_ptr<WIARVZFileReader<RVZ>> WIARVZFileReader<RVZ>::Create(File::DirectIOFile file,
281 const std::string& path)
282 {
283 std::unique_ptr<WIARVZFileReader> blob(new WIARVZFileReader(std::move(file), path));
284 return blob->m_valid ? std::move(blob) : nullptr;
285 }
286
287 template <bool RVZ>
288 BlobType WIARVZFileReader<RVZ>::GetBlobType() const
289 {
290 return RVZ ? BlobType::RVZ : BlobType::WIA;
291 }
292
293 template <bool RVZ>
294 std::unique_ptr<BlobReader> WIARVZFileReader<RVZ>::CopyReader() const
295 {
296 return Create(m_file, m_path);
297 }
298
299 template <bool RVZ>
300 std::string WIARVZFileReader<RVZ>::GetCompressionMethod() const
301 {
302 switch (m_compression_type)
303 {
304 case WIARVZCompressionType::Purge:
305 return "Purge";
306 case WIARVZCompressionType::Bzip2:
307 return "bzip2";
308 case WIARVZCompressionType::LZMA:
309 return "LZMA";
310 case WIARVZCompressionType::LZMA2:
311 return "LZMA2";
312 case WIARVZCompressionType::Zstd:
313 return "Zstandard";
314 default:
315 return {};
316 }
317 }
318
319 template <bool RVZ>
320 bool WIARVZFileReader<RVZ>::Read(u64 offset, u64 size, u8* out_ptr)
321 {
322 if (offset + size > Common::swap64(m_header_1.iso_file_size))
323 return false;
324
325 if (offset < sizeof(WIAHeader2::disc_header))
326 {
327 const u64 bytes_to_read = std::min(sizeof(WIAHeader2::disc_header) - offset, size);
328 std::memcpy(out_ptr, m_header_2.disc_header.data() + offset, bytes_to_read);
329 offset += bytes_to_read;
330 size -= bytes_to_read;
331 out_ptr += bytes_to_read;
332 }
333
334 const u32 chunk_size = Common::swap32(m_header_2.chunk_size);
335 while (size > 0)
336 {
337 const auto it = m_data_entries.upper_bound(offset);
338 if (it == m_data_entries.end())
339 return false;
340
341 const DataEntry& data = it->second;
342 if (data.is_partition)
343 {
344 const PartitionEntry& partition = m_partition_entries[it->second.index];
345
346 const u32 partition_first_sector = Common::swap32(partition.data_entries[0].first_sector);
347 const u64 partition_data_offset = partition_first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
348
349 const u32 second_number_of_sectors =
350 Common::swap32(partition.data_entries[1].number_of_sectors);
351 const u32 partition_total_sectors =
352 second_number_of_sectors ? Common::swap32(partition.data_entries[1].first_sector) -
353 partition_first_sector + second_number_of_sectors :
354 Common::swap32(partition.data_entries[0].number_of_sectors);
355
356 for (const PartitionDataEntry& partition_data : partition.data_entries)
357 {
358 if (size == 0)
359 return true;
360
361 const u32 first_sector = Common::swap32(partition_data.first_sector);
362 const u32 number_of_sectors = Common::swap32(partition_data.number_of_sectors);
363
364 const u64 data_offset = first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
365 const u64 data_size = number_of_sectors * VolumeWii::BLOCK_TOTAL_SIZE;
366
367 if (data_size == 0)
368 continue;
369
370 if (data_offset + data_size <= offset)
371 continue;
372
373 if (offset < data_offset)
374 return false;
375
376 const u64 bytes_to_read = std::min(data_size - (offset - data_offset), size);
377
378 m_exception_list.clear();
379 m_write_to_exception_list = true;
380 m_exception_list_last_group_index = std::numeric_limits<u64>::max();
381 Common::ScopeGuard guard([this] { m_write_to_exception_list = false; });
382
383 bool hash_exception_error = false;
384 if (!m_encryption_cache.EncryptGroups(
385 offset - partition_data_offset, bytes_to_read, out_ptr, partition_data_offset,
386 partition_total_sectors * VolumeWii::BLOCK_DATA_SIZE, partition.partition_key,
387 [this, &hash_exception_error](
388 VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP], u64 offset_) {
389 // EncryptGroups calls ReadWiiDecrypted, which calls ReadFromGroups,
390 // which populates m_exception_list when m_write_to_exception_list == true
391 if (!ApplyHashExceptions(m_exception_list, hash_blocks))
392 hash_exception_error = true;
393 }))
394 {
395 return false;
396 }
397 if (hash_exception_error)
398 return false;
399
400 offset += bytes_to_read;
401 size -= bytes_to_read;
402 out_ptr += bytes_to_read;
403 }
404 }
405 else
406 {
407 const RawDataEntry& raw_data = m_raw_data_entries[data.index];
408 if (!ReadFromGroups(&offset, &size, &out_ptr, chunk_size, VolumeWii::BLOCK_TOTAL_SIZE,
409 Common::swap64(raw_data.data_offset), Common::swap64(raw_data.data_size),
410 Common::swap32(raw_data.group_index),
411 Common::swap32(raw_data.number_of_groups), 0))
412 {
413 return false;
414 }
415 }
416 }
417
418 return true;
419 }
420
421 template <bool RVZ>
422 const typename WIARVZFileReader<RVZ>::PartitionEntry*
423 WIARVZFileReader<RVZ>::GetPartition(u64 partition_data_offset, u32* partition_first_sector) const
424 {
425 const auto it = m_data_entries.upper_bound(partition_data_offset);
426 if (it == m_data_entries.end() || !it->second.is_partition)
427 return nullptr;
428
429 const PartitionEntry* partition = &m_partition_entries[it->second.index];
430 *partition_first_sector = Common::swap32(partition->data_entries[0].first_sector);
431 if (partition_data_offset != *partition_first_sector * VolumeWii::BLOCK_TOTAL_SIZE)
432 return nullptr;
433
434 return partition;
435 }
436
437 template <bool RVZ>
438 bool WIARVZFileReader<RVZ>::SupportsReadWiiDecrypted(u64 offset, u64 size,
439 u64 partition_data_offset) const
440 {
441 u32 partition_first_sector;
442 const PartitionEntry* partition = GetPartition(partition_data_offset, &partition_first_sector);
443 if (!partition)
444 return false;
445
446 for (const PartitionDataEntry& data : partition->data_entries)
447 {
448 const u32 start_sector = Common::swap32(data.first_sector) - partition_first_sector;
449 const u32 end_sector = start_sector + Common::swap32(data.number_of_sectors);
450
451 if (offset + size <= end_sector * VolumeWii::BLOCK_DATA_SIZE)
452 return true;
453 }
454
455 return false;
456 }
457
458 template <bool RVZ>
459 bool WIARVZFileReader<RVZ>::ReadWiiDecrypted(u64 offset, u64 size, u8* out_ptr,
460 u64 partition_data_offset)
461 {
462 u32 partition_first_sector;
463 const PartitionEntry* partition = GetPartition(partition_data_offset, &partition_first_sector);
464 if (!partition)
465 return false;
466
467 const u64 chunk_size = Common::swap32(m_header_2.chunk_size) * VolumeWii::BLOCK_DATA_SIZE /
468 VolumeWii::BLOCK_TOTAL_SIZE;
469
470 for (const PartitionDataEntry& data : partition->data_entries)
471 {
472 if (size == 0)
473 return true;
474
475 const u64 data_offset =
476 (Common::swap32(data.first_sector) - partition_first_sector) * VolumeWii::BLOCK_DATA_SIZE;
477 const u64 data_size = Common::swap32(data.number_of_sectors) * VolumeWii::BLOCK_DATA_SIZE;
478
479 if (!ReadFromGroups(
480 &offset, &size, &out_ptr, chunk_size, VolumeWii::BLOCK_DATA_SIZE, data_offset,
481 data_size, Common::swap32(data.group_index), Common::swap32(data.number_of_groups),
482 std::max<u32>(1, static_cast<u32>(chunk_size / VolumeWii::GROUP_DATA_SIZE))))
483 {
484 return false;
485 }
486 }
487
488 return size == 0;
489 }
490
491 template <bool RVZ>
492 bool WIARVZFileReader<RVZ>::ReadFromGroups(u64* offset, u64* size, u8** out_ptr, u64 chunk_size,
493 u32 sector_size, u64 data_offset, u64 data_size,
494 u32 group_index, u32 number_of_groups,
495 u32 exception_lists)
496 {
497 if (data_offset + data_size <= *offset)
498 return true;
499
500 if (*offset < data_offset)
501 return false;
502
503 const u64 skipped_data = data_offset % sector_size;
504 data_offset -= skipped_data;
505 data_size += skipped_data;
506
507 const u64 start_group_index = (*offset - data_offset) / chunk_size;
508 for (u64 i = start_group_index; i < number_of_groups && (*size) > 0; ++i)
509 {
510 const u64 total_group_index = group_index + i;
511 if (total_group_index >= m_group_entries.size())
512 return false;
513
514 const GroupEntry group = m_group_entries[total_group_index];
515 const u64 group_offset_in_data = i * chunk_size;
516 const u64 offset_in_group = *offset - group_offset_in_data - data_offset;
517
518 chunk_size = std::min(chunk_size, data_size - group_offset_in_data);
519
520 const u64 bytes_to_read = std::min(chunk_size - offset_in_group, *size);
521 u32 group_data_size = Common::swap32(group.data_size);
522
523 WIARVZCompressionType compression_type = m_compression_type;
524 u32 rvz_packed_size = 0;
525 if constexpr (RVZ)
526 {
527 if ((group_data_size & 0x80000000) == 0)
528 compression_type = WIARVZCompressionType::None;
529
530 group_data_size &= 0x7FFFFFFF;
531
532 rvz_packed_size = Common::swap32(group.rvz_packed_size);
533 }
534
535 if (group_data_size == 0)
536 {
537 std::memset(*out_ptr, 0, bytes_to_read);
538 }
539 else
540 {
541 const u64 group_offset_in_file = static_cast<u64>(Common::swap32(group.data_offset)) << 2;
542
543 Chunk& chunk =
544 ReadCompressedData(group_offset_in_file, group_data_size, chunk_size, compression_type,
545 exception_lists, rvz_packed_size, group_offset_in_data);
546
547 if (!chunk.Read(offset_in_group, bytes_to_read, *out_ptr))
548 {
549 m_cached_chunk_offset = std::numeric_limits<u64>::max(); // Invalidate the cache
550 return false;
551 }
552
553 if (m_write_to_exception_list && m_exception_list_last_group_index != total_group_index)
554 {
555 const u64 exception_list_index = offset_in_group / VolumeWii::GROUP_DATA_SIZE;
556 const u16 additional_offset =
557 static_cast<u16>(group_offset_in_data % VolumeWii::GROUP_DATA_SIZE /
558 VolumeWii::BLOCK_DATA_SIZE * VolumeWii::BLOCK_HEADER_SIZE);
559 chunk.GetHashExceptions(&m_exception_list, exception_list_index, additional_offset);
560 m_exception_list_last_group_index = total_group_index;
561 }
562 }
563
564 *offset += bytes_to_read;
565 *size -= bytes_to_read;
566 *out_ptr += bytes_to_read;
567 }
568
569 return true;
570 }
571
572 template <bool RVZ>
573 typename WIARVZFileReader<RVZ>::Chunk&
574 WIARVZFileReader<RVZ>::ReadCompressedData(u64 offset_in_file, u64 compressed_size,
575 u64 decompressed_size,
576 WIARVZCompressionType compression_type,
577 u32 exception_lists, u32 rvz_packed_size, u64 data_offset)
578 {
579 if (offset_in_file == m_cached_chunk_offset)
580 return m_cached_chunk;
581
582 std::unique_ptr<Decompressor> decompressor;
583 switch (compression_type)
584 {
585 case WIARVZCompressionType::None:
586 decompressor = std::make_unique<NoneDecompressor>();
587 break;
588 case WIARVZCompressionType::Purge:
589 decompressor = std::make_unique<PurgeDecompressor>(rvz_packed_size == 0 ? decompressed_size :
590 rvz_packed_size);
591 break;
592 case WIARVZCompressionType::Bzip2:
593 decompressor = std::make_unique<Bzip2Decompressor>();
594 break;
595 case WIARVZCompressionType::LZMA:
596 decompressor = std::make_unique<LZMADecompressor>(false, m_header_2.compressor_data,
597 m_header_2.compressor_data_size);
598 break;
599 case WIARVZCompressionType::LZMA2:
600 decompressor = std::make_unique<LZMADecompressor>(true, m_header_2.compressor_data,
601 m_header_2.compressor_data_size);
602 break;
603 case WIARVZCompressionType::Zstd:
604 decompressor = std::make_unique<ZstdDecompressor>();
605 break;
606 }
607
608 const bool compressed_exception_lists = compression_type > WIARVZCompressionType::Purge;
609
610 m_cached_chunk =
611 Chunk(&m_file, offset_in_file, compressed_size, decompressed_size, exception_lists,
612 compressed_exception_lists, rvz_packed_size, data_offset, std::move(decompressor));
613 m_cached_chunk_offset = offset_in_file;
614 return m_cached_chunk;
615 }
616
617 template <bool RVZ>
618 std::string WIARVZFileReader<RVZ>::VersionToString(u32 version)
619 {
620 const u8 a = version >> 24;
621 const u8 b = (version >> 16) & 0xff;
622 const u8 c = (version >> 8) & 0xff;
623 const u8 d = version & 0xff;
624
625 if (d == 0 || d == 0xff)
626 return fmt::format("{}.{:02x}.{:02x}", a, b, c);
627 else
628 return fmt::format("{}.{:02x}.{:02x}.beta{}", a, b, c, d);
629 }
630
631 template <bool RVZ>
632 WIARVZFileReader<RVZ>::Chunk::Chunk() = default;
633
634 template <bool RVZ>
635 WIARVZFileReader<RVZ>::Chunk::Chunk(File::DirectIOFile* file, u64 offset_in_file,
636 u64 compressed_size, u64 decompressed_size, u32 exception_lists,
637 bool compressed_exception_lists, u32 rvz_packed_size,
638 u64 data_offset, std::unique_ptr<Decompressor> decompressor)
639 : m_decompressor(std::move(decompressor)), m_file(file), m_offset_in_file(offset_in_file),
640 m_exception_lists(exception_lists), m_compressed_exception_lists(compressed_exception_lists),
641 m_rvz_packed_size(rvz_packed_size), m_data_offset(data_offset)
642 {
643 constexpr size_t MAX_SIZE_PER_EXCEPTION_LIST =
644 Common::AlignUp(VolumeWii::BLOCK_HEADER_SIZE, Common::SHA1::DIGEST_LEN) /
645 Common::SHA1::DIGEST_LEN * VolumeWii::BLOCKS_PER_GROUP * sizeof(HashExceptionEntry) +
646 sizeof(u16);
647
648 m_out_bytes_allocated_for_exceptions =
649 m_compressed_exception_lists ? MAX_SIZE_PER_EXCEPTION_LIST * m_exception_lists : 0;
650
651 m_in.data.resize(compressed_size);
652 m_out.data.resize(decompressed_size + m_out_bytes_allocated_for_exceptions);
653 }
654
655 template <bool RVZ>
656 bool WIARVZFileReader<RVZ>::Chunk::Read(u64 offset, u64 size, u8* out_ptr)
657 {
658 if (!m_decompressor || !m_file ||
659 offset + size > m_out.data.size() - m_out_bytes_allocated_for_exceptions)
660 {
661 return false;
662 }
663
664 while (offset + size > GetOutBytesWrittenExcludingExceptions())
665 {
666 u64 bytes_to_read;
667 if (offset + size == m_out.data.size())
668 {
669 // Read all the remaining data.
670 bytes_to_read = m_in.data.size() - m_in.bytes_written;
671 }
672 else
673 {
674 // Pick a suitable amount of compressed data to read. We have to ensure that bytes_to_read
675 // is larger than 0 and smaller than or equal to the number of bytes available to read,
676 // but the rest is a bit arbitrary and could be changed.
677
678 // The compressed data is probably not much bigger than the decompressed data.
679 // Add a few bytes for possible compression overhead and for any hash exceptions.
680 bytes_to_read = offset + size - GetOutBytesWrittenExcludingExceptions() + 0x100;
681
682 // Align the access in an attempt to gain speed. But we don't actually know the
683 // block size of the underlying storage device, so we just use the Wii block size.
684 bytes_to_read =
685 Common::AlignUp(bytes_to_read + m_offset_in_file, VolumeWii::BLOCK_TOTAL_SIZE) -
686 m_offset_in_file;
687
688 // Ensure we don't read too much.
689 bytes_to_read = std::min<u64>(m_in.data.size() - m_in.bytes_written, bytes_to_read);
690 }
691
692 if (bytes_to_read == 0)
693 {
694 // Compressed size is larger than expected or decompressed size is smaller than expected
695 return false;
696 }
697
698 if (!m_file->OffsetRead(m_offset_in_file, m_in.data.data() + m_in.bytes_written, bytes_to_read))
699 return false;
700
701 m_offset_in_file += bytes_to_read;
702 m_in.bytes_written += bytes_to_read;
703
704 if (m_exception_lists > 0 && !m_compressed_exception_lists)
705 {
706 if (!HandleExceptions(m_in.data.data(), m_in.data.size(), m_in.bytes_written,
707 &m_in_bytes_used_for_exceptions, true))
708 {
709 return false;
710 }
711
712 m_in_bytes_read = m_in_bytes_used_for_exceptions;
713 }
714
715 if (m_exception_lists == 0 || m_compressed_exception_lists)
716 {
717 if (!Decompress())
718 return false;
719 }
720
721 if (m_exception_lists > 0 && m_compressed_exception_lists)
722 {
723 if (!HandleExceptions(m_out.data.data(), m_out_bytes_allocated_for_exceptions,
724 m_out.bytes_written, &m_out_bytes_used_for_exceptions, false))
725 {
726 return false;
727 }
728
729 if (m_rvz_packed_size != 0 && m_exception_lists == 0)
730 {
731 if (!Decompress())
732 return false;
733 }
734 }
735
736 if (m_exception_lists == 0)
737 {
738 const size_t expected_out_bytes = m_out.data.size() - m_out_bytes_allocated_for_exceptions +
739 m_out_bytes_used_for_exceptions;
740
741 if (m_out.bytes_written > expected_out_bytes)
742 return false; // Decompressed size is larger than expected
743
744 // The reason why we need the m_in.bytes_written == m_in.data.size() check as part of
745 // this conditional is because (for example) zstd can finish writing all data to m_out
746 // before becoming done if we've given it all input data except the checksum at the end.
747 if (m_out.bytes_written == expected_out_bytes && !m_decompressor->Done() &&
748 m_in.bytes_written == m_in.data.size())
749 {
750 return false; // Decompressed size is larger than expected
751 }
752
753 if (m_decompressor->Done() && m_in_bytes_read != m_in.data.size())
754 return false; // Compressed size is smaller than expected
755 }
756 }
757
758 std::memcpy(out_ptr, m_out.data.data() + offset + m_out_bytes_used_for_exceptions, size);
759 return true;
760 }
761
762 template <bool RVZ>
763 bool WIARVZFileReader<RVZ>::Chunk::Decompress()
764 {
765 if (m_rvz_packed_size != 0 && m_exception_lists == 0)
766 {
767 const size_t bytes_to_move = m_out.bytes_written - m_out_bytes_used_for_exceptions;
768
769 DecompressionBuffer in{std::vector<u8>(bytes_to_move), bytes_to_move};
770
771 // Copying to a null pointer is undefined behaviour, so only copy when we
772 // actually have data to copy.
773 if (bytes_to_move > 0)
774 {
775 std::memcpy(in.data.data(), m_out.data.data() + m_out_bytes_used_for_exceptions,
776 bytes_to_move);
777 }
778
779 m_out.bytes_written = m_out_bytes_used_for_exceptions;
780
781 m_decompressor = std::make_unique<RVZPackDecompressor>(std::move(m_decompressor), std::move(in),
782 m_data_offset, m_rvz_packed_size);
783
784 m_rvz_packed_size = 0;
785 }
786
787 return m_decompressor->Decompress(m_in, &m_out, &m_in_bytes_read);
788 }
789
790 template <bool RVZ>
791 bool WIARVZFileReader<RVZ>::Chunk::HandleExceptions(const u8* data, size_t bytes_allocated,
792 size_t bytes_written, size_t* bytes_used,
793 bool align)
794 {
795 while (m_exception_lists > 0)
796 {
797 if (sizeof(u16) + *bytes_used > bytes_allocated)
798 {
799 ERROR_LOG_FMT(DISCIO, "More hash exceptions than expected");
800 return false;
801 }
802 if (sizeof(u16) + *bytes_used > bytes_written)
803 return true;
804
805 const u16 exceptions = Common::swap16(data + *bytes_used);
806
807 size_t exception_list_size = exceptions * sizeof(HashExceptionEntry) + sizeof(u16);
808 if (align && m_exception_lists == 1)
809 exception_list_size = Common::AlignUp(*bytes_used + exception_list_size, 4) - *bytes_used;
810
811 if (exception_list_size + *bytes_used > bytes_allocated)
812 {
813 ERROR_LOG_FMT(DISCIO, "More hash exceptions than expected");
814 return false;
815 }
816 if (exception_list_size + *bytes_used > bytes_written)
817 return true;
818
819 *bytes_used += exception_list_size;
820 --m_exception_lists;
821 }
822
823 return true;
824 }
825
826 template <bool RVZ>
827 void WIARVZFileReader<RVZ>::Chunk::GetHashExceptions(
828 std::vector<HashExceptionEntry>* exception_list, u64 exception_list_index,
829 u16 additional_offset) const
830 {
831 ASSERT(m_exception_lists == 0);
832
833 const u8* data_start = m_compressed_exception_lists ? m_out.data.data() : m_in.data.data();
834 const u8* data = data_start;
835
836 for (u64 i = exception_list_index; i > 0; --i)
837 data += Common::swap16(data) * sizeof(HashExceptionEntry) + sizeof(u16);
838
839 const u16 exceptions = Common::swap16(data);
840 data += sizeof(u16);
841
842 for (size_t i = 0; i < exceptions; ++i)
843 {
844 std::memcpy(&exception_list->emplace_back(), data, sizeof(HashExceptionEntry));
845 data += sizeof(HashExceptionEntry);
846
847 u16& offset = exception_list->back().offset;
848 offset = Common::swap16(Common::swap16(offset) + additional_offset);
849 }
850
851 ASSERT(data <= data_start + (m_compressed_exception_lists ? m_out_bytes_used_for_exceptions :
852 m_in_bytes_used_for_exceptions));
853 }
854
855 template <bool RVZ>
856 size_t WIARVZFileReader<RVZ>::Chunk::GetOutBytesWrittenExcludingExceptions() const
857 {
858 return m_exception_lists == 0 ? m_out.bytes_written - m_out_bytes_used_for_exceptions : 0;
859 }
860
861 template <bool RVZ>
862 bool WIARVZFileReader<RVZ>::ApplyHashExceptions(
863 std::span<const HashExceptionEntry> exception_list,
864 VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP])
865 {
866 for (const HashExceptionEntry& exception : exception_list)
867 {
868 const u16 offset = Common::swap16(exception.offset);
869
870 const size_t block_index = offset / VolumeWii::BLOCK_HEADER_SIZE;
871 if (block_index > VolumeWii::BLOCKS_PER_GROUP)
872 return false;
873
874 const size_t offset_in_block = offset % VolumeWii::BLOCK_HEADER_SIZE;
875 if (offset_in_block + Common::SHA1::DIGEST_LEN > VolumeWii::BLOCK_HEADER_SIZE)
876 return false;
877
878 std::memcpy(reinterpret_cast<u8*>(&hash_blocks[block_index]) + offset_in_block, &exception.hash,
879 Common::SHA1::DIGEST_LEN);
880 }
881
882 return true;
883 }
884
885 template <bool RVZ>
886 bool WIARVZFileReader<RVZ>::PadTo4(File::DirectIOFile* file, u64* bytes_written)
887 {
888 constexpr u32 ZEROES = 0;
889 const u64 bytes_to_write = Common::AlignUp(*bytes_written, 4) - *bytes_written;
890 if (bytes_to_write == 0)
891 return true;
892
893 *bytes_written += bytes_to_write;
894 return file->Write(Common::AsU8Span(ZEROES).first(bytes_to_write));
895 }
896
897 template <bool RVZ>
898 void WIARVZFileReader<RVZ>::AddRawDataEntry(u64 offset, u64 size, int chunk_size, u32* total_groups,
899 std::vector<RawDataEntry>* raw_data_entries,
900 std::vector<DataEntry>* data_entries)
901 {
902 constexpr size_t SKIP_SIZE = sizeof(WIAHeader2::disc_header);
903 const u64 skip = offset < SKIP_SIZE ? std::min(SKIP_SIZE - offset, size) : 0;
904
905 offset += skip;
906 size -= skip;
907
908 if (size == 0)
909 return;
910
911 const u32 group_index = *total_groups;
912 const u32 groups = static_cast<u32>(Common::AlignUp(size, chunk_size) / chunk_size);
913 *total_groups += groups;
914
915 data_entries->emplace_back(raw_data_entries->size());
916 raw_data_entries->emplace_back(RawDataEntry{Common::swap64(offset), Common::swap64(size),
917 Common::swap32(group_index), Common::swap32(groups)});
918 }
919
920 template <bool RVZ>
921 typename WIARVZFileReader<RVZ>::PartitionDataEntry WIARVZFileReader<RVZ>::CreatePartitionDataEntry(
922 u64 offset, u64 size, u32 index, int chunk_size, u32* total_groups,
923 const std::vector<PartitionEntry>& partition_entries, std::vector<DataEntry>* data_entries)
924 {
925 const u32 group_index = *total_groups;
926 const u64 rounded_size = Common::AlignDown(size, VolumeWii::BLOCK_TOTAL_SIZE);
927 const u32 groups = static_cast<u32>(Common::AlignUp(rounded_size, chunk_size) / chunk_size);
928 *total_groups += groups;
929
930 data_entries->emplace_back(partition_entries.size(), index);
931 return PartitionDataEntry{Common::swap32(offset / VolumeWii::BLOCK_TOTAL_SIZE),
932 Common::swap32(size / VolumeWii::BLOCK_TOTAL_SIZE),
933 Common::swap32(group_index), Common::swap32(groups)};
934 }
935
936 template <bool RVZ>
937 ConversionResultCode WIARVZFileReader<RVZ>::SetUpDataEntriesForWriting(
938 const VolumeDisc* volume, int chunk_size, u64 iso_size, u32* total_groups,
939 std::vector<PartitionEntry>* partition_entries, std::vector<RawDataEntry>* raw_data_entries,
940 std::vector<DataEntry>* data_entries, std::vector<const FileSystem*>* partition_file_systems)
941 {
942 std::vector<Partition> partitions;
943 if (volume && volume->HasWiiHashes() && volume->HasWiiEncryption())
944 partitions = volume->GetPartitions();
945
946 std::ranges::sort(partitions, {}, &Partition::offset);
947
948 *total_groups = 0;
949
950 u64 last_partition_end_offset = 0;
951
952 const auto add_raw_data_entry = [&](u64 offset, u64 size) {
953 return AddRawDataEntry(offset, size, chunk_size, total_groups, raw_data_entries, data_entries);
954 };
955
956 const auto create_partition_data_entry = [&](u64 offset, u64 size, u32 index) {
957 return CreatePartitionDataEntry(offset, size, index, chunk_size, total_groups,
958 *partition_entries, data_entries);
959 };
960
961 for (const Partition& partition : partitions)
962 {
963 // If a partition is odd in some way that prevents us from encoding it as a partition,
964 // we encode it as raw data instead by skipping the current loop iteration.
965 // Partitions can always be encoded as raw data, but it is less space efficient.
966
967 if (partition.offset < last_partition_end_offset)
968 {
969 WARN_LOG_FMT(DISCIO, "Overlapping partitions at {:x}", partition.offset);
970 continue;
971 }
972
973 if (volume->ReadSwapped<u32>(partition.offset, PARTITION_NONE) != 0x10001U)
974 {
975 // This looks more like garbage data than an actual partition.
976 // The values of data_offset and data_size will very likely also be garbage.
977 // Some WBFS writing programs scrub the SSBB Masterpiece partitions without
978 // removing them from the partition table, causing this problem.
979 WARN_LOG_FMT(DISCIO, "Invalid partition at {:x}", partition.offset);
980 continue;
981 }
982
983 std::optional<u64> data_offset =
984 volume->ReadSwappedAndShifted(partition.offset + 0x2b8, PARTITION_NONE);
985 std::optional<u64> data_size =
986 volume->ReadSwappedAndShifted(partition.offset + 0x2bc, PARTITION_NONE);
987
988 if (!data_offset || !data_size)
989 return ConversionResultCode::ReadFailed;
990
991 const u64 data_start = partition.offset + *data_offset;
992 const u64 data_end = data_start + *data_size;
993
994 if (data_start % VolumeWii::BLOCK_TOTAL_SIZE != 0)
995 {
996 WARN_LOG_FMT(DISCIO, "Misaligned partition at {:x}", partition.offset);
997 continue;
998 }
999
1000 if (*data_size < VolumeWii::BLOCK_TOTAL_SIZE)
1001 {
1002 WARN_LOG_FMT(DISCIO, "Very small partition at {:x}", partition.offset);
1003 continue;
1004 }
1005
1006 if (data_end > iso_size)
1007 {
1008 WARN_LOG_FMT(DISCIO, "Too large partition at {:x}", partition.offset);
1009 *data_size = iso_size - *data_offset - partition.offset;
1010 }
1011
1012 const std::optional<u64> fst_offset = GetFSTOffset(*volume, partition);
1013 const std::optional<u64> fst_size = GetFSTSize(*volume, partition);
1014
1015 if (!fst_offset || !fst_size)
1016 return ConversionResultCode::ReadFailed;
1017
1018 const IOS::ES::TicketReader& ticket = volume->GetTicket(partition);
1019 if (!ticket.IsValid())
1020 return ConversionResultCode::ReadFailed;
1021
1022 add_raw_data_entry(last_partition_end_offset, partition.offset - last_partition_end_offset);
1023
1024 add_raw_data_entry(partition.offset, *data_offset);
1025
1026 const u64 fst_end = volume->PartitionOffsetToRawOffset(*fst_offset + *fst_size, partition);
1027 const u64 split_point = std::min(
1028 data_end, Common::AlignUp(fst_end - data_start, VolumeWii::GROUP_TOTAL_SIZE) + data_start);
1029
1030 PartitionEntry partition_entry;
1031 partition_entry.partition_key = ticket.GetTitleKey();
1032 partition_entry.data_entries[0] =
1033 create_partition_data_entry(data_start, split_point - data_start, 0);
1034 partition_entry.data_entries[1] =
1035 create_partition_data_entry(split_point, data_end - split_point, 1);
1036
1037 // Note: We can't simply set last_partition_end_offset to data_end,
1038 // because construct_partition_data_entry may have rounded it
1039 last_partition_end_offset =
1040 (Common::swap32(partition_entry.data_entries[1].first_sector) +
1041 Common::swap32(partition_entry.data_entries[1].number_of_sectors)) *
1042 VolumeWii::BLOCK_TOTAL_SIZE;
1043
1044 partition_entries->emplace_back(std::move(partition_entry));
1045 partition_file_systems->emplace_back(volume->GetFileSystem(partition));
1046 }
1047
1048 add_raw_data_entry(last_partition_end_offset, iso_size - last_partition_end_offset);
1049
1050 return ConversionResultCode::Success;
1051 }
1052
1053 template <bool RVZ>
1054 std::optional<std::vector<u8>> WIARVZFileReader<RVZ>::Compress(Compressor* compressor,
1055 const u8* data, size_t size)
1056 {
1057 if (compressor)
1058 {
1059 if (!compressor->Start(size) || !compressor->Compress(data, size) || !compressor->End())
1060 return std::nullopt;
1061
1062 data = compressor->GetData();
1063 size = compressor->GetSize();
1064 }
1065
1066 return std::vector<u8>(data, data + size);
1067 }
1068
1069 template <bool RVZ>
1070 void WIARVZFileReader<RVZ>::SetUpCompressor(std::unique_ptr<Compressor>* compressor,
1071 WIARVZCompressionType compression_type,
1072 int compression_level, WIAHeader2* header_2)
1073 {
1074 switch (compression_type)
1075 {
1076 case WIARVZCompressionType::None:
1077 *compressor = nullptr;
1078 break;
1079 case WIARVZCompressionType::Purge:
1080 *compressor = std::make_unique<PurgeCompressor>();
1081 break;
1082 case WIARVZCompressionType::Bzip2:
1083 *compressor = std::make_unique<Bzip2Compressor>(compression_level);
1084 break;
1085 case WIARVZCompressionType::LZMA:
1086 case WIARVZCompressionType::LZMA2:
1087 {
1088 u8* compressor_data = nullptr;
1089 u8* compressor_data_size = nullptr;
1090
1091 if (header_2)
1092 {
1093 compressor_data = header_2->compressor_data;
1094 compressor_data_size = &header_2->compressor_data_size;
1095 }
1096
1097 const bool lzma2 = compression_type == WIARVZCompressionType::LZMA2;
1098 *compressor = std::make_unique<LZMACompressor>(lzma2, compression_level, compressor_data,
1099 compressor_data_size);
1100 break;
1101 }
1102 case WIARVZCompressionType::Zstd:
1103 *compressor = std::make_unique<ZstdCompressor>(compression_level);
1104 break;
1105 }
1106 }
1107
1108 template <bool RVZ>
1109 bool WIARVZFileReader<RVZ>::TryReuse(std::map<ReuseID, GroupEntry>* reusable_groups,
1110 std::mutex* reusable_groups_mutex,
1111 OutputParametersEntry* entry)
1112 {
1113 if (entry->reused_group)
1114 return true;
1115
1116 if (!entry->reuse_id)
1117 return false;
1118
1119 std::lock_guard guard(*reusable_groups_mutex);
1120 const auto it = reusable_groups->find(*entry->reuse_id);
1121 if (it == reusable_groups->end())
1122 return false;
1123
1124 entry->reused_group = it->second;
1125 return true;
1126 }
1127
1128 static bool AllAre(const std::vector<u8>& data, u8 x)
1129 {
1130 return std::ranges::all_of(data, [x](u8 y) { return x == y; });
1131 }
1132
1133 static bool AllAre(const u8* begin, const u8* end, u8 x)
1134 {
1135 return std::all_of(begin, end, [x](u8 y) { return x == y; });
1136 }
1137
1138 static bool AllZero(const std::vector<u8>& data)
1139 {
1140 return AllAre(data, 0);
1141 }
1142
1143 static bool AllSame(const std::vector<u8>& data)
1144 {
1145 return AllAre(data, data.front());
1146 }
1147
1148 static bool AllSame(const u8* begin, const u8* end)
1149 {
1150 return AllAre(begin, end, *begin);
1151 }
1152
1153 template <typename OutputParametersEntry>
1154 static void RVZPack(const u8* in, OutputParametersEntry* out, u64 bytes_per_chunk, size_t chunks,
1155 u64 total_size, u64 data_offset, bool multipart, bool allow_junk_reuse,
1156 bool compression, const FileSystem* file_system)
1157 {
1158 using Seed = std::array<u32, LaggedFibonacciGenerator::SEED_SIZE>;
1159 struct JunkInfo
1160 {
1161 size_t start_offset;
1162 Seed seed;
1163 };
1164
1165 constexpr size_t SEED_SIZE = LaggedFibonacciGenerator::SEED_SIZE * sizeof(u32);
1166
1167 // Maps end_offset -> (start_offset, seed)
1168 std::map<size_t, JunkInfo> junk_info;
1169
1170 size_t position = 0;
1171 while (position < total_size)
1172 {
1173 // Skip the 0 to 32 zero bytes that typically come after a file
1174 size_t zeroes = 0;
1175 while (position + zeroes < total_size && in[position + zeroes] == 0)
1176 ++zeroes;
1177
1178 // If there are very many zero bytes (perhaps the PRNG junk data has been scrubbed?)
1179 // and we aren't using compression, it makes sense to encode the zero bytes as junk.
1180 // If we are using compression, the compressor will likely encode zeroes better than we can
1181 if (!compression && zeroes > SEED_SIZE)
1182 junk_info.emplace(position + zeroes, JunkInfo{position, {}});
1183
1184 position += zeroes;
1185 data_offset += zeroes;
1186
1187 const size_t bytes_to_read =
1188 std::min(Common::AlignUp(data_offset + 1, VolumeWii::BLOCK_TOTAL_SIZE) - data_offset,
1189 total_size - position);
1190
1191 const size_t data_offset_mod = static_cast<size_t>(data_offset % VolumeWii::BLOCK_TOTAL_SIZE);
1192
1193 Seed seed;
1194 const size_t bytes_reconstructed = LaggedFibonacciGenerator::GetSeed(
1195 in + position, bytes_to_read, data_offset_mod, seed.data());
1196
1197 if (bytes_reconstructed > 0)
1198 junk_info.emplace(position + bytes_reconstructed, JunkInfo{position, seed});
1199
1200 if (file_system)
1201 {
1202 const std::unique_ptr<DiscIO::FileInfo> file_info =
1203 file_system->FindFileInfo(data_offset + bytes_reconstructed);
1204
1205 // If we're at a file and there's more space in this block after the file,
1206 // continue after the file instead of skipping to the next block
1207 if (file_info)
1208 {
1209 const u64 file_end_offset = file_info->GetOffset() + file_info->GetSize();
1210 if (file_end_offset < data_offset + bytes_to_read)
1211 {
1212 position += file_end_offset - data_offset;
1213 data_offset = file_end_offset;
1214 continue;
1215 }
1216 }
1217 }
1218
1219 position += bytes_to_read;
1220 data_offset += bytes_to_read;
1221 }
1222
1223 for (size_t i = 0; i < chunks; ++i)
1224 {
1225 OutputParametersEntry& entry = out[i];
1226 if (entry.reused_group)
1227 continue;
1228
1229 u64 current_offset = i * bytes_per_chunk;
1230 const u64 end_offset = std::min(current_offset + bytes_per_chunk, total_size);
1231
1232 const bool store_junk_efficiently = allow_junk_reuse || !entry.reuse_id;
1233
1234 // TODO: It would be possible to support skipping RVZ packing even when the chunk size is larger
1235 // than 2 MiB (multipart == true), but it would be more effort than it's worth since Dolphin's
1236 // converter doesn't expose chunk sizes larger than 2 MiB to the user anyway
1237 bool first_loop_iteration = !multipart;
1238
1239 while (current_offset < end_offset)
1240 {
1241 u64 next_junk_start = end_offset;
1242 u64 next_junk_end = end_offset;
1243 Seed* seed = nullptr;
1244 if (store_junk_efficiently && end_offset - current_offset > SEED_SIZE)
1245 {
1246 const auto next_junk_it = junk_info.upper_bound(current_offset + SEED_SIZE);
1247 if (next_junk_it != junk_info.end() &&
1248 next_junk_it->second.start_offset + SEED_SIZE < end_offset)
1249 {
1250 next_junk_start = std::max<u64>(current_offset, next_junk_it->second.start_offset);
1251 next_junk_end = std::min<u64>(end_offset, next_junk_it->first);
1252 seed = &next_junk_it->second.seed;
1253 }
1254 }
1255
1256 if (first_loop_iteration)
1257 {
1258 if (next_junk_start == end_offset)
1259 {
1260 // Storing this chunk with RVZ packing would be inefficient, so store it without
1261 PushBack(&entry.main_data, in + current_offset, in + end_offset);
1262 break;
1263 }
1264
1265 first_loop_iteration = false;
1266 }
1267
1268 const u64 non_junk_bytes = next_junk_start - current_offset;
1269 if (non_junk_bytes > 0)
1270 {
1271 const u8* ptr = in + current_offset;
1272
1273 PushBack(&entry.main_data, Common::swap32(static_cast<u32>(non_junk_bytes)));
1274 PushBack(&entry.main_data, ptr, ptr + non_junk_bytes);
1275
1276 current_offset += non_junk_bytes;
1277 entry.rvz_packed_size += sizeof(u32) + non_junk_bytes;
1278 }
1279
1280 const u64 junk_bytes = next_junk_end - current_offset;
1281 if (junk_bytes > 0)
1282 {
1283 PushBack(&entry.main_data, Common::swap32(static_cast<u32>(junk_bytes) | 0x80000000));
1284 PushBack(&entry.main_data, *seed);
1285
1286 current_offset += junk_bytes;
1287 entry.rvz_packed_size += sizeof(u32) + SEED_SIZE;
1288 }
1289 }
1290 }
1291 }
1292
1293 template <typename OutputParametersEntry>
1294 static void RVZPack(const u8* in, OutputParametersEntry* out, u64 size, u64 data_offset,
1295 bool allow_junk_reuse, bool compression, const FileSystem* file_system)
1296 {
1297 RVZPack(in, out, size, 1, size, data_offset, false, allow_junk_reuse, compression, file_system);
1298 }
1299
1300 template <bool RVZ>
1301 ConversionResult<typename WIARVZFileReader<RVZ>::OutputParameters>
1302 WIARVZFileReader<RVZ>::ProcessAndCompress(CompressThreadState* state, CompressParameters parameters,
1303 const std::vector<PartitionEntry>& partition_entries,
1304 const std::vector<DataEntry>& data_entries,
1305 const FileSystem* file_system,
1306 std::map<ReuseID, GroupEntry>* reusable_groups,
1307 std::mutex* reusable_groups_mutex,
1308 u64 chunks_per_wii_group, u64 exception_lists_per_chunk,
1309 bool compressed_exception_lists, bool compression)
1310 {
1311 std::vector<OutputParametersEntry> output_entries;
1312
1313 if (!parameters.data_entry->is_partition)
1314 {
1315 OutputParametersEntry& entry = output_entries.emplace_back();
1316 std::vector<u8>& data = parameters.data;
1317
1318 if (AllSame(data))
1319 entry.reuse_id = ReuseID{WiiKey{}, data.size(), false, data.front()};
1320
1321 if constexpr (RVZ)
1322 {
1323 RVZPack(data.data(), output_entries.data(), data.size(), parameters.data_offset, true,
1324 compression, file_system);
1325 }
1326 else
1327 {
1328 entry.main_data = std::move(data);
1329 }
1330 }
1331 else
1332 {
1333 const PartitionEntry& partition_entry = partition_entries[parameters.data_entry->index];
1334
1335 auto aes_context = Common::AES::CreateContextDecrypt(partition_entry.partition_key.data());
1336
1337 const u64 groups = Common::AlignUp(parameters.data.size(), VolumeWii::GROUP_TOTAL_SIZE) /
1338 VolumeWii::GROUP_TOTAL_SIZE;
1339
1340 ASSERT(parameters.data.size() % VolumeWii::BLOCK_TOTAL_SIZE == 0);
1341 const u64 blocks = parameters.data.size() / VolumeWii::BLOCK_TOTAL_SIZE;
1342
1343 const u64 blocks_per_chunk = chunks_per_wii_group == 1 ?
1344 exception_lists_per_chunk * VolumeWii::BLOCKS_PER_GROUP :
1345 VolumeWii::BLOCKS_PER_GROUP / chunks_per_wii_group;
1346
1347 const u64 chunks = Common::AlignUp(blocks, blocks_per_chunk) / blocks_per_chunk;
1348
1349 const u64 in_data_per_chunk = blocks_per_chunk * VolumeWii::BLOCK_TOTAL_SIZE;
1350 const u64 out_data_per_chunk = blocks_per_chunk * VolumeWii::BLOCK_DATA_SIZE;
1351
1352 const size_t first_chunk = output_entries.size();
1353
1354 const auto create_reuse_id = [&partition_entry, blocks,
1355 blocks_per_chunk](u8 value, bool encrypted, u64 block) {
1356 const u64 size = std::min(blocks - block, blocks_per_chunk) * VolumeWii::BLOCK_DATA_SIZE;
1357 return ReuseID{partition_entry.partition_key, size, encrypted, value};
1358 };
1359
1360 const u8* parameters_data_end = parameters.data.data() + parameters.data.size();
1361 for (u64 i = 0; i < chunks; ++i)
1362 {
1363 const u64 block_index = i * blocks_per_chunk;
1364
1365 OutputParametersEntry& entry = output_entries.emplace_back();
1366 std::optional<ReuseID>& reuse_id = entry.reuse_id;
1367
1368 // Set this chunk as reusable if the encrypted data is AllSame
1369 const u8* data = parameters.data.data() + block_index * VolumeWii::BLOCK_TOTAL_SIZE;
1370 if (AllSame(data, std::min(parameters_data_end, data + in_data_per_chunk)))
1371 reuse_id = create_reuse_id(parameters.data.front(), true, i * blocks_per_chunk);
1372
1373 TryReuse(reusable_groups, reusable_groups_mutex, &entry);
1374 if (!entry.reused_group && reuse_id)
1375 {
1376 const auto it = std::ranges::find(output_entries.begin(), output_entries.begin() + i,
1377 reuse_id, &OutputParametersEntry::reuse_id);
1378 if (it != output_entries.begin() + i)
1379 entry.reused_group = it->reused_group;
1380 }
1381 }
1382
1383 if (!std::ranges::all_of(output_entries,
1384 [](const auto& entry) { return entry.reused_group.has_value(); }))
1385 {
1386 const u64 number_of_exception_lists =
1387 chunks_per_wii_group == 1 ? exception_lists_per_chunk : chunks;
1388 std::vector<std::vector<HashExceptionEntry>> exception_lists(number_of_exception_lists);
1389
1390 for (u64 i = 0; i < groups; ++i)
1391 {
1392 const u64 offset_of_group = i * VolumeWii::GROUP_TOTAL_SIZE;
1393 const u64 write_offset_of_group = i * VolumeWii::GROUP_DATA_SIZE;
1394
1395 const u64 blocks_in_this_group =
1396 std::min<u64>(VolumeWii::BLOCKS_PER_GROUP, blocks - i * VolumeWii::BLOCKS_PER_GROUP);
1397
1398 for (u32 j = 0; j < VolumeWii::BLOCKS_PER_GROUP; ++j)
1399 {
1400 if (j < blocks_in_this_group)
1401 {
1402 const u64 offset_of_block = offset_of_group + j * VolumeWii::BLOCK_TOTAL_SIZE;
1403 VolumeWii::DecryptBlockData(parameters.data.data() + offset_of_block,
1404 state->decryption_buffer[j].data(), aes_context.get());
1405 }
1406 else
1407 {
1408 state->decryption_buffer[j].fill(0);
1409 }
1410 }
1411
1412 VolumeWii::HashGroup(state->decryption_buffer.data(), state->hash_buffer.data());
1413
1414 for (u64 j = 0; j < blocks_in_this_group; ++j)
1415 {
1416 const u64 chunk_index = j / blocks_per_chunk;
1417 const u64 block_index_in_chunk = j % blocks_per_chunk;
1418
1419 if (output_entries[chunk_index].reused_group)
1420 continue;
1421
1422 const u64 exception_list_index = chunks_per_wii_group == 1 ? i : chunk_index;
1423
1424 const u64 offset_of_block = offset_of_group + j * VolumeWii::BLOCK_TOTAL_SIZE;
1425 const u64 hash_offset_of_block = block_index_in_chunk * VolumeWii::BLOCK_HEADER_SIZE;
1426
1427 VolumeWii::HashBlock hashes;
1428 VolumeWii::DecryptBlockHashes(parameters.data.data() + offset_of_block, &hashes,
1429 aes_context.get());
1430
1431 const auto compare_hash = [&](size_t offset_in_block) {
1432 ASSERT(offset_in_block + Common::SHA1::DIGEST_LEN <= VolumeWii::BLOCK_HEADER_SIZE);
1433
1434 const u8* desired_hash = reinterpret_cast<u8*>(&hashes) + offset_in_block;
1435 const u8* computed_hash =
1436 reinterpret_cast<u8*>(&state->hash_buffer[j]) + offset_in_block;
1437
1438 // We want to store a hash exception either if there is a hash mismatch, or if this
1439 // chunk might get reused in a context where it is paired up (within a 2 MiB Wii group)
1440 // with chunks that are different from the chunks it currently is paired up with, since
1441 // that affects the recalculated hashes. Chunks which have been marked as reusable at
1442 // this point normally have zero matching hashes anyway, so this shouldn't waste space.
1443 if ((chunks_per_wii_group != 1 && output_entries[chunk_index].reuse_id) ||
1444 !std::equal(desired_hash, desired_hash + Common::SHA1::DIGEST_LEN, computed_hash))
1445 {
1446 const u64 hash_offset = hash_offset_of_block + offset_in_block;
1447 ASSERT(hash_offset <= std::numeric_limits<u16>::max());
1448
1449 HashExceptionEntry& exception = exception_lists[exception_list_index].emplace_back();
1450 exception.offset = Common::swap16(static_cast<u16>(hash_offset));
1451 std::memcpy(exception.hash.data(), desired_hash, Common::SHA1::DIGEST_LEN);
1452 }
1453 };
1454
1455 const auto compare_hashes = [&compare_hash](size_t offset, size_t size) {
1456 for (size_t l = 0; l < size; l += Common::SHA1::DIGEST_LEN)
1457 // The std::min is to ensure that we don't go beyond the end of HashBlock with
1458 // padding_2, which is 32 bytes long (not divisible by SHA1::DIGEST_LEN, which is 20).
1459 compare_hash(offset + std::min(l, size - Common::SHA1::DIGEST_LEN));
1460 };
1461
1462 using HashBlock = VolumeWii::HashBlock;
1463 compare_hashes(offsetof(HashBlock, h0), sizeof(HashBlock::h0));
1464 compare_hashes(offsetof(HashBlock, padding_0), sizeof(HashBlock::padding_0));
1465 compare_hashes(offsetof(HashBlock, h1), sizeof(HashBlock::h1));
1466 compare_hashes(offsetof(HashBlock, padding_1), sizeof(HashBlock::padding_1));
1467 compare_hashes(offsetof(HashBlock, h2), sizeof(HashBlock::h2));
1468 compare_hashes(offsetof(HashBlock, padding_2), sizeof(HashBlock::padding_2));
1469 }
1470
1471 static_assert(std::is_trivially_copyable_v<
1472 typename decltype(CompressThreadState::decryption_buffer)::value_type>);
1473 if constexpr (RVZ)
1474 {
1475 // We must not store junk efficiently for chunks that may get reused at a position
1476 // which has a different value of data_offset % VolumeWii::BLOCK_TOTAL_SIZE
1477 const bool allow_junk_reuse = chunks_per_wii_group == 1;
1478
1479 const u64 bytes_per_chunk = std::min(out_data_per_chunk, VolumeWii::GROUP_DATA_SIZE);
1480 const u64 total_size = blocks_in_this_group * VolumeWii::BLOCK_DATA_SIZE;
1481 const u64 data_offset = parameters.data_offset + write_offset_of_group;
1482
1483 RVZPack(state->decryption_buffer[0].data(), output_entries.data() + first_chunk,
1484 bytes_per_chunk, chunks, total_size, data_offset, groups > 1, allow_junk_reuse,
1485 compression, file_system);
1486 }
1487 else
1488 {
1489 const u8* in_ptr = state->decryption_buffer[0].data();
1490 for (u64 j = 0; j < chunks; ++j)
1491 {
1492 OutputParametersEntry& entry = output_entries[first_chunk + j];
1493
1494 if (!entry.reused_group)
1495 {
1496 const u64 bytes_left = (blocks - j * blocks_per_chunk) * VolumeWii::BLOCK_DATA_SIZE;
1497 const u64 bytes_to_write_total = std::min(out_data_per_chunk, bytes_left);
1498
1499 if (i == 0)
1500 entry.main_data.resize(bytes_to_write_total);
1501
1502 const u64 bytes_to_write = std::min(bytes_to_write_total, VolumeWii::GROUP_DATA_SIZE);
1503
1504 std::memcpy(entry.main_data.data() + write_offset_of_group, in_ptr, bytes_to_write);
1505
1506 // Set this chunk as reusable if the decrypted data is AllSame.
1507 // There is also a requirement that it lacks exceptions, but this is checked later
1508 if (i == 0 && !entry.reuse_id)
1509 {
1510 if (AllSame(in_ptr, in_ptr + bytes_to_write))
1511 entry.reuse_id = create_reuse_id(*in_ptr, false, j * blocks_per_chunk);
1512 }
1513 else
1514 {
1515 if (entry.reuse_id && !entry.reuse_id->encrypted &&
1516 (!AllSame(in_ptr, in_ptr + bytes_to_write) || entry.reuse_id->value != *in_ptr))
1517 {
1518 entry.reuse_id.reset();
1519 }
1520 }
1521 }
1522
1523 in_ptr += out_data_per_chunk;
1524 }
1525 }
1526 }
1527
1528 for (size_t i = 0; i < exception_lists.size(); ++i)
1529 {
1530 OutputParametersEntry& entry = output_entries[chunks_per_wii_group == 1 ? 0 : i];
1531 if (entry.reused_group)
1532 continue;
1533
1534 const std::vector<HashExceptionEntry>& in = exception_lists[i];
1535 std::vector<u8>& out = entry.exception_lists;
1536
1537 const u16 exceptions = Common::swap16(static_cast<u16>(in.size()));
1538 PushBack(&out, exceptions);
1539 for (const HashExceptionEntry& exception : in)
1540 PushBack(&out, exception);
1541 }
1542
1543 for (u64 i = 0; i < output_entries.size(); ++i)
1544 {
1545 OutputParametersEntry& entry = output_entries[i];
1546
1547 // If this chunk was set as reusable because the decrypted data is AllSame,
1548 // but it has exceptions, unmark it as reusable
1549 if (entry.reuse_id && !entry.reuse_id->encrypted && !AllZero(entry.exception_lists))
1550 entry.reuse_id.reset();
1551 }
1552 }
1553 }
1554
1555 for (OutputParametersEntry& entry : output_entries)
1556 {
1557 TryReuse(reusable_groups, reusable_groups_mutex, &entry);
1558 if (entry.reused_group)
1559 continue;
1560
1561 // Special case - a compressed size of zero is treated by WIA as meaning the data is all zeroes
1562 if (entry.reuse_id && !entry.reuse_id->encrypted && entry.reuse_id->value == 0)
1563 {
1564 entry.exception_lists.clear();
1565 entry.main_data.clear();
1566 if constexpr (RVZ)
1567 {
1568 entry.rvz_packed_size = 0;
1569 entry.compressed = false;
1570 }
1571 continue;
1572 }
1573
1574 const auto pad_exception_lists = [&entry] {
1575 while (entry.exception_lists.size() % 4 != 0)
1576 entry.exception_lists.push_back(0);
1577 };
1578
1579 if (state->compressor)
1580 {
1581 if (!state->compressor->Start(entry.exception_lists.size() + entry.main_data.size()))
1582 return std::unexpected{ConversionResultCode::InternalError};
1583 }
1584
1585 if (!entry.exception_lists.empty())
1586 {
1587 if (compressed_exception_lists && state->compressor)
1588 {
1589 if (!state->compressor->Compress(entry.exception_lists.data(),
1590 entry.exception_lists.size()))
1591 {
1592 return std::unexpected{ConversionResultCode::InternalError};
1593 }
1594 }
1595 else
1596 {
1597 if (!compressed_exception_lists)
1598 pad_exception_lists();
1599
1600 if (state->compressor)
1601 {
1602 if (!state->compressor->AddPrecedingDataOnlyForPurgeHashing(entry.exception_lists.data(),
1603 entry.exception_lists.size()))
1604 {
1605 return std::unexpected{ConversionResultCode::InternalError};
1606 }
1607 }
1608 }
1609 }
1610
1611 if (state->compressor)
1612 {
1613 if (!state->compressor->Compress(entry.main_data.data(), entry.main_data.size()))
1614 return std::unexpected{ConversionResultCode::InternalError};
1615 if (!state->compressor->End())
1616 return std::unexpected{ConversionResultCode::InternalError};
1617 }
1618
1619 bool compressed = !!state->compressor;
1620 if constexpr (RVZ)
1621 {
1622 size_t uncompressed_size = entry.main_data.size();
1623 if (compressed_exception_lists)
1624 uncompressed_size += Common::AlignUp(entry.exception_lists.size(), 4);
1625
1626 compressed = state->compressor && state->compressor->GetSize() < uncompressed_size;
1627 entry.compressed = compressed;
1628
1629 if (!compressed)
1630 pad_exception_lists();
1631 }
1632
1633 if (compressed)
1634 {
1635 const u8* data = state->compressor->GetData();
1636 const size_t size = state->compressor->GetSize();
1637
1638 entry.main_data.resize(size);
1639 std::copy_n(data, size, entry.main_data.data());
1640
1641 if (compressed_exception_lists)
1642 entry.exception_lists.clear();
1643 }
1644 }
1645
1646 return OutputParameters{std::move(output_entries), parameters.bytes_read, parameters.group_index};
1647 }
1648
1649 template <bool RVZ>
1650 ConversionResultCode WIARVZFileReader<RVZ>::Output(std::vector<OutputParametersEntry>* entries,
1651 File::DirectIOFile* outfile,
1652 std::map<ReuseID, GroupEntry>* reusable_groups,
1653 std::mutex* reusable_groups_mutex,
1654 GroupEntry* group_entry, u64* bytes_written)
1655 {
1656 for (OutputParametersEntry& entry : *entries)
1657 {
1658 TryReuse(reusable_groups, reusable_groups_mutex, &entry);
1659 if (entry.reused_group)
1660 {
1661 *group_entry = *entry.reused_group;
1662 ++group_entry;
1663 continue;
1664 }
1665
1666 if (*bytes_written >> 2 > std::numeric_limits<u32>::max())
1667 return ConversionResultCode::InternalError;
1668
1669 ASSERT((*bytes_written & 3) == 0);
1670 group_entry->data_offset = Common::swap32(static_cast<u32>(*bytes_written >> 2));
1671
1672 u32 data_size = static_cast<u32>(entry.exception_lists.size() + entry.main_data.size());
1673 if constexpr (RVZ)
1674 {
1675 data_size = (data_size & 0x7FFFFFFF) | (static_cast<u32>(entry.compressed) << 31);
1676 group_entry->rvz_packed_size = Common::swap32(static_cast<u32>(entry.rvz_packed_size));
1677 }
1678 group_entry->data_size = Common::swap32(data_size);
1679
1680 if (!outfile->Write(entry.exception_lists))
1681 return ConversionResultCode::WriteFailed;
1682 if (!outfile->Write(entry.main_data))
1683 return ConversionResultCode::WriteFailed;
1684
1685 *bytes_written += entry.exception_lists.size() + entry.main_data.size();
1686
1687 if (entry.reuse_id)
1688 {
1689 std::lock_guard guard(*reusable_groups_mutex);
1690 reusable_groups->emplace(*entry.reuse_id, *group_entry);
1691 }
1692
1693 if (!PadTo4(outfile, bytes_written))
1694 return ConversionResultCode::WriteFailed;
1695
1696 ++group_entry;
1697 }
1698
1699 return ConversionResultCode::Success;
1700 }
1701
1702 template <bool RVZ>
1703 ConversionResultCode WIARVZFileReader<RVZ>::RunCallback(size_t groups_written, u64 bytes_read,
1704 u64 bytes_written, u32 total_groups,
1705 u64 iso_size, const CompressCB& callback)
1706 {
1707 int ratio = 0;
1708 if (bytes_read != 0)
1709 ratio = static_cast<int>(100 * bytes_written / bytes_read);
1710
1711 const std::string text = Common::FmtFormatT("{0} of {1} blocks. Compression ratio {2}%",
1712 groups_written, total_groups, ratio);
1713
1714 const float completion = static_cast<float>(bytes_read) / iso_size;
1715
1716 return callback(text, completion) ? ConversionResultCode::Success :
1717 ConversionResultCode::Canceled;
1718 }
1719
1720 template <bool RVZ>
1721 bool WIARVZFileReader<RVZ>::WriteHeader(File::DirectIOFile* file, const u8* data, size_t size,
1722 u64 upper_bound, u64* bytes_written, u64* offset_out)
1723 {
1724 // The first part of the check is to prevent this from running more than once. If *bytes_written
1725 // is past the upper bound, we are already at the end of the file, so we don't need to do anything
1726 if (*bytes_written <= upper_bound && *bytes_written + size > upper_bound)
1727 {
1728 WARN_LOG_FMT(DISCIO,
1729 "Headers did not fit in the allocated space. Writing to end of file instead");
1730 if (!file->Seek(0, File::SeekOrigin::End))
1731 return false;
1732 *bytes_written = file->Tell();
1733 }
1734
1735 *offset_out = *bytes_written;
1736 if (!file->Write(data, size))
1737 return false;
1738 *bytes_written += size;
1739 return PadTo4(file, bytes_written);
1740 }
1741
1742 template <bool RVZ>
1743 ConversionResultCode
1744 WIARVZFileReader<RVZ>::Convert(BlobReader* infile, const VolumeDisc* infile_volume,
1745 File::DirectIOFile* outfile, WIARVZCompressionType compression_type,
1746 int compression_level, int chunk_size, CompressCB callback)
1747 {
1748 ASSERT(infile->GetDataSizeType() == DataSizeType::Accurate);
1749 ASSERT(chunk_size > 0);
1750
1751 const u64 iso_size = infile->GetDataSize();
1752 const u64 chunks_per_wii_group = std::max<u64>(1, VolumeWii::GROUP_TOTAL_SIZE / chunk_size);
1753 const u64 exception_lists_per_chunk = std::max<u64>(1, chunk_size / VolumeWii::GROUP_TOTAL_SIZE);
1754 const bool compressed_exception_lists = compression_type > WIARVZCompressionType::Purge;
1755
1756 u64 bytes_read = 0;
1757 u64 bytes_written = 0;
1758 size_t groups_processed = 0;
1759
1760 WIAHeader1 header_1{};
1761 WIAHeader2 header_2{};
1762
1763 std::vector<PartitionEntry> partition_entries;
1764 std::vector<RawDataEntry> raw_data_entries;
1765 std::vector<GroupEntry> group_entries;
1766
1767 u32 total_groups;
1768 std::vector<DataEntry> data_entries;
1769
1770 const FileSystem* non_partition_file_system =
1771 infile_volume ? infile_volume->GetFileSystem(PARTITION_NONE) : nullptr;
1772 std::vector<const FileSystem*> partition_file_systems;
1773
1774 const ConversionResultCode set_up_data_entries_result = SetUpDataEntriesForWriting(
1775 infile_volume, chunk_size, iso_size, &total_groups, &partition_entries, &raw_data_entries,
1776 &data_entries, &partition_file_systems);
1777 if (set_up_data_entries_result != ConversionResultCode::Success)
1778 return set_up_data_entries_result;
1779
1780 group_entries.resize(total_groups);
1781
1782 const size_t partition_entries_size = partition_entries.size() * sizeof(PartitionEntry);
1783 const size_t raw_data_entries_size = raw_data_entries.size() * sizeof(RawDataEntry);
1784 const size_t group_entries_size = group_entries.size() * sizeof(GroupEntry);
1785
1786 // An estimate for how much space will be taken up by headers.
1787 // We will reserve this much space at the beginning of the file, and if the headers don't
1788 // fit in that space, we will need to write them at the end of the file instead.
1789 const u64 headers_size_upper_bound = [&] {
1790 // 0x100 is added to account for compression overhead (in particular for Purge).
1791 u64 upper_bound = sizeof(WIAHeader1) + sizeof(WIAHeader2) + partition_entries_size +
1792 raw_data_entries_size + 0x100;
1793
1794 // Compared to WIA, RVZ adds an extra member to the GroupEntry struct. This added data usually
1795 // compresses well, so we'll assume the compression ratio for RVZ GroupEntries is 9 / 16 or
1796 // better. This constant is somewhat arbitrarily chosen, but no games were found that get a
1797 // worse compression ratio than that. There are some games that get a worse ratio than 1 / 2,
1798 // such as Metroid: Other M (PAL) with the default settings.
1799 if (RVZ && compression_type > WIARVZCompressionType::Purge)
1800 upper_bound += static_cast<u64>(group_entries_size) * 9 / 16;
1801 else
1802 upper_bound += group_entries_size;
1803
1804 // This alignment is also somewhat arbitrary.
1805 return Common::AlignUp(upper_bound, VolumeWii::BLOCK_TOTAL_SIZE);
1806 }();
1807
1808 std::vector<u8> buffer;
1809
1810 buffer.resize(headers_size_upper_bound);
1811 outfile->Write(buffer);
1812 bytes_written = headers_size_upper_bound;
1813
1814 if (!infile->Read(0, header_2.disc_header.size(), header_2.disc_header.data()))
1815 return ConversionResultCode::ReadFailed;
1816 // We intentionally do not increment bytes_read here, since these bytes will be read again
1817
1818 std::map<ReuseID, GroupEntry> reusable_groups;
1819 std::mutex reusable_groups_mutex;
1820
1821 const auto set_up_compress_thread_state = [&](CompressThreadState* state) {
1822 SetUpCompressor(&state->compressor, compression_type, compression_level, nullptr);
1823 return ConversionResultCode::Success;
1824 };
1825
1826 const auto process_and_compress = [&](CompressThreadState* state, CompressParameters parameters) {
1827 const DataEntry& data_entry = *parameters.data_entry;
1828 const FileSystem* file_system = data_entry.is_partition ?
1829 partition_file_systems[data_entry.index] :
1830 non_partition_file_system;
1831
1832 const bool compression = compression_type != WIARVZCompressionType::None;
1833
1834 return ProcessAndCompress(state, std::move(parameters), partition_entries, data_entries,
1835 file_system, &reusable_groups, &reusable_groups_mutex,
1836 chunks_per_wii_group, exception_lists_per_chunk,
1837 compressed_exception_lists, compression);
1838 };
1839
1840 const auto output = [&](OutputParameters parameters) {
1841 const ConversionResultCode result =
1842 Output(&parameters.entries, outfile, &reusable_groups, &reusable_groups_mutex,
1843 &group_entries[parameters.group_index], &bytes_written);
1844
1845 if (result != ConversionResultCode::Success)
1846 return result;
1847
1848 return RunCallback(parameters.group_index + parameters.entries.size(), parameters.bytes_read,
1849 bytes_written, total_groups, iso_size, callback);
1850 };
1851
1852 MultithreadedCompressor<CompressThreadState, CompressParameters, OutputParameters> mt_compressor(
1853 set_up_compress_thread_state, process_and_compress, output);
1854
1855 for (const DataEntry& data_entry : data_entries)
1856 {
1857 u32 first_group;
1858 u32 last_group;
1859
1860 u64 data_offset;
1861 u64 data_size;
1862
1863 u64 data_offset_in_partition;
1864
1865 if (data_entry.is_partition)
1866 {
1867 const PartitionEntry& partition_entry = partition_entries[data_entry.index];
1868 const PartitionDataEntry& partition_data_entry =
1869 partition_entry.data_entries[data_entry.partition_data_index];
1870
1871 first_group = Common::swap32(partition_data_entry.group_index);
1872 last_group = first_group + Common::swap32(partition_data_entry.number_of_groups);
1873
1874 const u32 first_sector = Common::swap32(partition_data_entry.first_sector);
1875 data_offset = first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
1876 data_size =
1877 Common::swap32(partition_data_entry.number_of_sectors) * VolumeWii::BLOCK_TOTAL_SIZE;
1878
1879 const u32 block_in_partition =
1880 first_sector - Common::swap32(partition_entry.data_entries[0].first_sector);
1881 data_offset_in_partition = block_in_partition * VolumeWii::BLOCK_DATA_SIZE;
1882 }
1883 else
1884 {
1885 const RawDataEntry& raw_data_entry = raw_data_entries[data_entry.index];
1886
1887 first_group = Common::swap32(raw_data_entry.group_index);
1888 last_group = first_group + Common::swap32(raw_data_entry.number_of_groups);
1889
1890 data_offset = Common::swap64(raw_data_entry.data_offset);
1891 data_size = Common::swap64(raw_data_entry.data_size);
1892
1893 const u64 skipped_data = data_offset % VolumeWii::BLOCK_TOTAL_SIZE;
1894 data_offset -= skipped_data;
1895 data_size += skipped_data;
1896
1897 data_offset_in_partition = data_offset;
1898 }
1899
1900 ASSERT(groups_processed == first_group);
1901 ASSERT(bytes_read == data_offset);
1902
1903 while (groups_processed < last_group)
1904 {
1905 const ConversionResultCode status = mt_compressor.GetStatus();
1906 if (status != ConversionResultCode::Success)
1907 return status;
1908
1909 u64 bytes_to_read = chunk_size;
1910 if (data_entry.is_partition)
1911 bytes_to_read = std::max<u64>(bytes_to_read, VolumeWii::GROUP_TOTAL_SIZE);
1912 bytes_to_read = std::min<u64>(bytes_to_read, data_offset + data_size - bytes_read);
1913
1914 buffer.resize(bytes_to_read);
1915 if (!infile->Read(bytes_read, bytes_to_read, buffer.data()))
1916 return ConversionResultCode::ReadFailed;
1917 bytes_read += bytes_to_read;
1918
1919 mt_compressor.CompressAndWrite(CompressParameters{
1920 buffer, &data_entry, data_offset_in_partition, bytes_read, groups_processed});
1921
1922 data_offset += bytes_to_read;
1923 data_size -= bytes_to_read;
1924
1925 if (data_entry.is_partition)
1926 {
1927 data_offset_in_partition +=
1928 bytes_to_read / VolumeWii::BLOCK_TOTAL_SIZE * VolumeWii::BLOCK_DATA_SIZE;
1929 }
1930 else
1931 {
1932 data_offset_in_partition += bytes_to_read;
1933 }
1934
1935 groups_processed += Common::AlignUp(bytes_to_read, chunk_size) / chunk_size;
1936 }
1937
1938 ASSERT(data_size == 0);
1939 }
1940
1941 ASSERT(groups_processed == total_groups);
1942 ASSERT(bytes_read == iso_size);
1943
1944 mt_compressor.Shutdown();
1945
1946 const ConversionResultCode status = mt_compressor.GetStatus();
1947 if (status != ConversionResultCode::Success)
1948 return status;
1949
1950 std::unique_ptr<Compressor> compressor;
1951 SetUpCompressor(&compressor, compression_type, compression_level, &header_2);
1952
1953 const std::optional<std::vector<u8>> compressed_raw_data_entries = Compress(
1954 compressor.get(), reinterpret_cast<u8*>(raw_data_entries.data()), raw_data_entries_size);
1955 if (!compressed_raw_data_entries)
1956 return ConversionResultCode::InternalError;
1957
1958 const std::optional<std::vector<u8>> compressed_group_entries =
1959 Compress(compressor.get(), reinterpret_cast<u8*>(group_entries.data()), group_entries_size);
1960 if (!compressed_group_entries)
1961 return ConversionResultCode::InternalError;
1962
1963 bytes_written = sizeof(WIAHeader1) + sizeof(WIAHeader2);
1964 if (!outfile->Seek(sizeof(WIAHeader1) + sizeof(WIAHeader2), File::SeekOrigin::Begin))
1965 return ConversionResultCode::WriteFailed;
1966
1967 u64 partition_entries_offset;
1968 if (!WriteHeader(outfile, reinterpret_cast<u8*>(partition_entries.data()), partition_entries_size,
1969 headers_size_upper_bound, &bytes_written, &partition_entries_offset))
1970 {
1971 return ConversionResultCode::WriteFailed;
1972 }
1973
1974 u64 raw_data_entries_offset;
1975 if (!WriteHeader(outfile, compressed_raw_data_entries->data(),
1976 compressed_raw_data_entries->size(), headers_size_upper_bound, &bytes_written,
1977 &raw_data_entries_offset))
1978 {
1979 return ConversionResultCode::WriteFailed;
1980 }
1981
1982 u64 group_entries_offset;
1983 if (!WriteHeader(outfile, compressed_group_entries->data(), compressed_group_entries->size(),
1984 headers_size_upper_bound, &bytes_written, &group_entries_offset))
1985 {
1986 return ConversionResultCode::WriteFailed;
1987 }
1988
1989 u32 disc_type = 0;
1990 if (infile_volume)
1991 {
1992 if (infile_volume->GetVolumeType() == Platform::GameCubeDisc)
1993 disc_type = 1;
1994 else if (infile_volume->GetVolumeType() == Platform::WiiDisc)
1995 disc_type = 2;
1996 }
1997
1998 header_2.disc_type = Common::swap32(disc_type);
1999 header_2.compression_type = Common::swap32(static_cast<u32>(compression_type));
2000 header_2.compression_level =
2001 static_cast<s32>(Common::swap32(static_cast<u32>(compression_level)));
2002 header_2.chunk_size = Common::swap32(static_cast<u32>(chunk_size));
2003
2004 header_2.number_of_partition_entries = Common::swap32(static_cast<u32>(partition_entries.size()));
2005 header_2.partition_entry_size = Common::swap32(sizeof(PartitionEntry));
2006 header_2.partition_entries_offset = Common::swap64(partition_entries_offset);
2007
2008 header_2.partition_entries_hash = Common::SHA1::CalculateDigest(partition_entries);
2009
2010 header_2.number_of_raw_data_entries = Common::swap32(static_cast<u32>(raw_data_entries.size()));
2011 header_2.raw_data_entries_offset = Common::swap64(raw_data_entries_offset);
2012 header_2.raw_data_entries_size =
2013 Common::swap32(static_cast<u32>(compressed_raw_data_entries->size()));
2014
2015 header_2.number_of_group_entries = Common::swap32(static_cast<u32>(group_entries.size()));
2016 header_2.group_entries_offset = Common::swap64(group_entries_offset);
2017 header_2.group_entries_size = Common::swap32(static_cast<u32>(compressed_group_entries->size()));
2018
2019 header_1.magic = RVZ ? RVZ_MAGIC : WIA_MAGIC;
2020 header_1.version = Common::swap32(RVZ ? RVZ_VERSION : WIA_VERSION);
2021 header_1.version_compatible =
2022 Common::swap32(RVZ ? RVZ_VERSION_WRITE_COMPATIBLE : WIA_VERSION_WRITE_COMPATIBLE);
2023 header_1.header_2_size = Common::swap32(sizeof(WIAHeader2));
2024 header_1.header_2_hash =
2025 Common::SHA1::CalculateDigest(reinterpret_cast<const u8*>(&header_2), sizeof(header_2));
2026 header_1.iso_file_size = Common::swap64(infile->GetDataSize());
2027 header_1.wia_file_size = Common::swap64(outfile->GetSize());
2028 header_1.header_1_hash = Common::SHA1::CalculateDigest(reinterpret_cast<const u8*>(&header_1),
2029 offsetof(WIAHeader1, header_1_hash));
2030
2031 if (!outfile->Seek(0, File::SeekOrigin::Begin))
2032 return ConversionResultCode::WriteFailed;
2033
2034 if (!outfile->Write(Common::AsU8Span(header_1)))
2035 return ConversionResultCode::WriteFailed;
2036 if (!outfile->Write(Common::AsU8Span(header_2)))
2037 return ConversionResultCode::WriteFailed;
2038
2039 return ConversionResultCode::Success;
2040 }
2041
2042 bool ConvertToWIAOrRVZ(BlobReader* infile, const std::string& infile_path,
2043 const std::string& outfile_path, bool rvz,
2044 WIARVZCompressionType compression_type, int compression_level,
2045 int chunk_size, const CompressCB& callback)
2046 {
2047 File::DirectIOFile outfile(outfile_path, File::AccessMode::Write);
2048 if (!outfile.IsOpen())
2049 {
2050 PanicAlertFmtT(
2051 "Failed to open the output file \"{0}\".\n"
2052 "Check that you have permissions to write the target folder and that the media can "
2053 "be written.",
2054 outfile_path);
2055 return false;
2056 }
2057
2058 std::unique_ptr<VolumeDisc> infile_volume = CreateDisc(infile_path);
2059
2060 const auto convert = rvz ? RVZFileReader::Convert : WIAFileReader::Convert;
2061 const ConversionResultCode result =
2062 convert(infile, infile_volume.get(), &outfile, compression_type, compression_level,
2063 chunk_size, callback);
2064
2065 if (result == ConversionResultCode::ReadFailed)
2066 PanicAlertFmtT("Failed to read from the input file \"{0}\".", infile_path);
2067
2068 if (result == ConversionResultCode::WriteFailed)
2069 {
2070 PanicAlertFmtT("Failed to write the output file \"{0}\".\n"
2071 "Check that you have enough space available on the target drive.",
2072 outfile_path);
2073 }
2074
2075 if (result != ConversionResultCode::Success)
2076 {
2077 // Remove the incomplete output file
2078 outfile.Close();
2079 File::Delete(outfile_path);
2080 }
2081
2082 return result == ConversionResultCode::Success;
2083 }
2084
2085 template class WIARVZFileReader<false>;
2086 template class WIARVZFileReader<true>;
2087
2088 } // namespace DiscIO