summaryrefslogtreecommitdiff
path: root/Source/Core/DiscIO/WIABlob.cpp
blob: 31000deb0271db724464fc5ad6f75296d5bd87a2 (plain)
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
// Copyright 2018 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "DiscIO/WIABlob.h"

#include <algorithm>
#include <array>
#include <cstring>
#include <expected>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <type_traits>
#include <utility>

#include <fmt/format.h>
#include <zstd.h>

#include "Common/Align.h"
#include "Common/Assert.h"
#include "Common/BitUtils.h"
#include "Common/CommonTypes.h"
#include "Common/Crypto/SHA1.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/ScopeGuard.h"
#include "Common/Swap.h"

#include "DiscIO/Blob.h"
#include "DiscIO/DiscUtils.h"
#include "DiscIO/Filesystem.h"
#include "DiscIO/LaggedFibonacciGenerator.h"
#include "DiscIO/MultithreadedCompressor.h"
#include "DiscIO/Volume.h"
#include "DiscIO/VolumeWii.h"
#include "DiscIO/WIACompression.h"
#include "DiscIO/WiiEncryptionCache.h"

namespace DiscIO
{
static void PushBack(std::vector<u8>* vector, const u8* begin, const u8* end)
{
  const size_t offset_in_vector = vector->size();
  vector->resize(offset_in_vector + (end - begin));
  std::copy(begin, end, vector->data() + offset_in_vector);
}

template <typename T>
static void PushBack(std::vector<u8>* vector, const T& x)
{
  static_assert(std::is_trivially_copyable_v<T>);

  const u8* x_ptr = reinterpret_cast<const u8*>(&x);
  PushBack(vector, x_ptr, x_ptr + sizeof(T));
}

std::pair<int, int> GetAllowedCompressionLevels(WIARVZCompressionType compression_type, bool gui)
{
  switch (compression_type)
  {
  case WIARVZCompressionType::Bzip2:
  case WIARVZCompressionType::LZMA:
  case WIARVZCompressionType::LZMA2:
    return {1, 9};
  case WIARVZCompressionType::Zstd:
    // The actual minimum level can be gotten by calling ZSTD_minCLevel(). However, returning that
    // would make the UI rather weird, because it is a negative number with very large magnitude.
    // Note: Level 0 is a special number which means "default level" (level 3 as of this writing).
    if (gui)
      return {1, ZSTD_maxCLevel()};
    else
      return {ZSTD_minCLevel(), ZSTD_maxCLevel()};
  default:
    return {0, -1};
  }
}

template <bool RVZ>
WIARVZFileReader<RVZ>::WIARVZFileReader(File::DirectIOFile file, const std::string& path)
    : m_file(std::move(file)), m_path(path), m_encryption_cache(this)
{
  m_valid = Initialize(path);
}

template <bool RVZ>
WIARVZFileReader<RVZ>::~WIARVZFileReader() = default;

template <bool RVZ>
bool WIARVZFileReader<RVZ>::Initialize(const std::string& path)
{
  if (!m_file.Seek(0, File::SeekOrigin::Begin) ||
      !m_file.Read(Common::AsWritableU8Span(m_header_1)))
  {
    return false;
  }

  if ((!RVZ && m_header_1.magic != WIA_MAGIC) || (RVZ && m_header_1.magic != RVZ_MAGIC))
    return false;

  const u32 version = RVZ ? RVZ_VERSION : WIA_VERSION;
  const u32 version_read_compatible =
      RVZ ? RVZ_VERSION_READ_COMPATIBLE : WIA_VERSION_READ_COMPATIBLE;

  const u32 file_version = Common::swap32(m_header_1.version);
  const u32 file_version_compatible = Common::swap32(m_header_1.version_compatible);

  if (version < file_version_compatible || version_read_compatible > file_version)
  {
    ERROR_LOG_FMT(DISCIO, "Unsupported version {} in {}", VersionToString(file_version), path);
    return false;
  }

  const auto header_1_actual_hash = Common::SHA1::CalculateDigest(
      reinterpret_cast<const u8*>(&m_header_1), sizeof(m_header_1) - Common::SHA1::DIGEST_LEN);
  if (m_header_1.header_1_hash != header_1_actual_hash)
    return false;

  if (Common::swap64(m_header_1.wia_file_size) != m_file.GetSize())
  {
    ERROR_LOG_FMT(DISCIO, "File size is incorrect for {}", path);
    return false;
  }

  const u32 header_2_size = Common::swap32(m_header_1.header_2_size);
  const u32 header_2_min_size = sizeof(WIAHeader2) - sizeof(WIAHeader2::compressor_data);
  if (header_2_size < header_2_min_size)
    return false;

  std::vector<u8> header_2(header_2_size);
  if (!m_file.Read(header_2))
    return false;

  const auto header_2_actual_hash = Common::SHA1::CalculateDigest(header_2);
  if (m_header_1.header_2_hash != header_2_actual_hash)
    return false;

  std::memcpy(&m_header_2, header_2.data(), std::min(header_2.size(), sizeof(WIAHeader2)));

  if (m_header_2.compressor_data_size > sizeof(WIAHeader2::compressor_data) ||
      header_2_size < header_2_min_size + m_header_2.compressor_data_size)
  {
    return false;
  }

  const u32 chunk_size = Common::swap32(m_header_2.chunk_size);
  const auto is_power_of_two = [](u32 x) { return (x & (x - 1)) == 0; };
  if ((!RVZ || chunk_size < VolumeWii::BLOCK_TOTAL_SIZE || !is_power_of_two(chunk_size)) &&
      chunk_size % VolumeWii::GROUP_TOTAL_SIZE != 0)
  {
    return false;
  }

  const u32 compression_type = Common::swap32(m_header_2.compression_type);
  m_compression_type = static_cast<WIARVZCompressionType>(compression_type);
  if (m_compression_type > (RVZ ? WIARVZCompressionType::Zstd : WIARVZCompressionType::LZMA2) ||
      (RVZ && m_compression_type == WIARVZCompressionType::Purge))
  {
    ERROR_LOG_FMT(DISCIO, "Unsupported compression type {} in {}", compression_type, path);
    return false;
  }

  const size_t number_of_partition_entries = Common::swap32(m_header_2.number_of_partition_entries);
  const size_t partition_entry_size = Common::swap32(m_header_2.partition_entry_size);
  std::vector<u8> partition_entries(partition_entry_size * number_of_partition_entries);
  if (!m_file.OffsetRead(Common::swap64(m_header_2.partition_entries_offset), partition_entries))
  {
    return false;
  }

  const auto partition_entries_actual_hash = Common::SHA1::CalculateDigest(partition_entries);
  if (m_header_2.partition_entries_hash != partition_entries_actual_hash)
    return false;

  const size_t copy_length = std::min(partition_entry_size, sizeof(PartitionEntry));
  const size_t memset_length = sizeof(PartitionEntry) - copy_length;
  u8* ptr = partition_entries.data();
  m_partition_entries.resize(number_of_partition_entries);
  for (size_t i = 0; i < number_of_partition_entries; ++i, ptr += partition_entry_size)
  {
    std::memcpy(&m_partition_entries[i], ptr, copy_length);
    std::memset(reinterpret_cast<u8*>(&m_partition_entries[i]) + copy_length, 0, memset_length);
  }

  for (size_t i = 0; i < m_partition_entries.size(); ++i)
  {
    const std::array<PartitionDataEntry, 2>& entries = m_partition_entries[i].data_entries;

    size_t non_empty_entries = 0;
    for (size_t j = 0; j < entries.size(); ++j)
    {
      const u32 number_of_sectors = Common::swap32(entries[j].number_of_sectors);
      if (number_of_sectors != 0)
      {
        ++non_empty_entries;

        const u32 last_sector = Common::swap32(entries[j].first_sector) + number_of_sectors;
        m_data_entries.emplace(last_sector * VolumeWii::BLOCK_TOTAL_SIZE, DataEntry(i, j));
      }
    }

    if (non_empty_entries > 1)
    {
      if (Common::swap32(entries[0].first_sector) > Common::swap32(entries[1].first_sector))
        return false;
    }
  }

  const u32 number_of_raw_data_entries = Common::swap32(m_header_2.number_of_raw_data_entries);
  m_raw_data_entries.resize(number_of_raw_data_entries);
  Chunk& raw_data_entries =
      ReadCompressedData(Common::swap64(m_header_2.raw_data_entries_offset),
                         Common::swap32(m_header_2.raw_data_entries_size),
                         number_of_raw_data_entries * sizeof(RawDataEntry), m_compression_type);
  if (!raw_data_entries.ReadAll(&m_raw_data_entries))
    return false;

  for (size_t i = 0; i < m_raw_data_entries.size(); ++i)
  {
    const RawDataEntry& entry = m_raw_data_entries[i];
    const u64 data_size = Common::swap64(entry.data_size);
    if (data_size != 0)
      m_data_entries.emplace(Common::swap64(entry.data_offset) + data_size, DataEntry(i));
  }

  const u32 number_of_group_entries = Common::swap32(m_header_2.number_of_group_entries);
  m_group_entries.resize(number_of_group_entries);
  Chunk& group_entries =
      ReadCompressedData(Common::swap64(m_header_2.group_entries_offset),
                         Common::swap32(m_header_2.group_entries_size),
                         number_of_group_entries * sizeof(GroupEntry), m_compression_type);
  if (!group_entries.ReadAll(&m_group_entries))
    return false;

  if (HasDataOverlap())
    return false;

  return true;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::HasDataOverlap() const
{
  for (size_t i = 0; i < m_partition_entries.size(); ++i)
  {
    const std::array<PartitionDataEntry, 2>& entries = m_partition_entries[i].data_entries;
    for (size_t j = 0; j < entries.size(); ++j)
    {
      if (Common::swap32(entries[j].number_of_sectors) == 0)
        continue;

      const u64 data_offset = Common::swap32(entries[j].first_sector) * VolumeWii::BLOCK_TOTAL_SIZE;
      const auto it = m_data_entries.upper_bound(data_offset);
      if (it == m_data_entries.end())
        return true;  // Not an overlap, but an error nonetheless
      if (!it->second.is_partition || it->second.index != i || it->second.partition_data_index != j)
        return true;  // Overlap
    }
  }

  for (size_t i = 0; i < m_raw_data_entries.size(); ++i)
  {
    if (Common::swap64(m_raw_data_entries[i].data_size) == 0)
      continue;

    const u64 data_offset = Common::swap64(m_raw_data_entries[i].data_offset);
    const auto it = m_data_entries.upper_bound(data_offset);
    if (it == m_data_entries.end())
      return true;  // Not an overlap, but an error nonetheless
    if (it->second.is_partition || it->second.index != i)
      return true;  // Overlap
  }

  return false;
}

template <bool RVZ>
std::unique_ptr<WIARVZFileReader<RVZ>> WIARVZFileReader<RVZ>::Create(File::DirectIOFile file,
                                                                     const std::string& path)
{
  std::unique_ptr<WIARVZFileReader> blob(new WIARVZFileReader(std::move(file), path));
  return blob->m_valid ? std::move(blob) : nullptr;
}

template <bool RVZ>
BlobType WIARVZFileReader<RVZ>::GetBlobType() const
{
  return RVZ ? BlobType::RVZ : BlobType::WIA;
}

template <bool RVZ>
std::unique_ptr<BlobReader> WIARVZFileReader<RVZ>::CopyReader() const
{
  return Create(m_file, m_path);
}

template <bool RVZ>
std::string WIARVZFileReader<RVZ>::GetCompressionMethod() const
{
  switch (m_compression_type)
  {
  case WIARVZCompressionType::Purge:
    return "Purge";
  case WIARVZCompressionType::Bzip2:
    return "bzip2";
  case WIARVZCompressionType::LZMA:
    return "LZMA";
  case WIARVZCompressionType::LZMA2:
    return "LZMA2";
  case WIARVZCompressionType::Zstd:
    return "Zstandard";
  default:
    return {};
  }
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::Read(u64 offset, u64 size, u8* out_ptr)
{
  if (offset + size > Common::swap64(m_header_1.iso_file_size))
    return false;

  if (offset < sizeof(WIAHeader2::disc_header))
  {
    const u64 bytes_to_read = std::min(sizeof(WIAHeader2::disc_header) - offset, size);
    std::memcpy(out_ptr, m_header_2.disc_header.data() + offset, bytes_to_read);
    offset += bytes_to_read;
    size -= bytes_to_read;
    out_ptr += bytes_to_read;
  }

  const u32 chunk_size = Common::swap32(m_header_2.chunk_size);
  while (size > 0)
  {
    const auto it = m_data_entries.upper_bound(offset);
    if (it == m_data_entries.end())
      return false;

    const DataEntry& data = it->second;
    if (data.is_partition)
    {
      const PartitionEntry& partition = m_partition_entries[it->second.index];

      const u32 partition_first_sector = Common::swap32(partition.data_entries[0].first_sector);
      const u64 partition_data_offset = partition_first_sector * VolumeWii::BLOCK_TOTAL_SIZE;

      const u32 second_number_of_sectors =
          Common::swap32(partition.data_entries[1].number_of_sectors);
      const u32 partition_total_sectors =
          second_number_of_sectors ? Common::swap32(partition.data_entries[1].first_sector) -
                                         partition_first_sector + second_number_of_sectors :
                                     Common::swap32(partition.data_entries[0].number_of_sectors);

      for (const PartitionDataEntry& partition_data : partition.data_entries)
      {
        if (size == 0)
          return true;

        const u32 first_sector = Common::swap32(partition_data.first_sector);
        const u32 number_of_sectors = Common::swap32(partition_data.number_of_sectors);

        const u64 data_offset = first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
        const u64 data_size = number_of_sectors * VolumeWii::BLOCK_TOTAL_SIZE;

        if (data_size == 0)
          continue;

        if (data_offset + data_size <= offset)
          continue;

        if (offset < data_offset)
          return false;

        const u64 bytes_to_read = std::min(data_size - (offset - data_offset), size);

        m_exception_list.clear();
        m_write_to_exception_list = true;
        m_exception_list_last_group_index = std::numeric_limits<u64>::max();
        Common::ScopeGuard guard([this] { m_write_to_exception_list = false; });

        bool hash_exception_error = false;
        if (!m_encryption_cache.EncryptGroups(
                offset - partition_data_offset, bytes_to_read, out_ptr, partition_data_offset,
                partition_total_sectors * VolumeWii::BLOCK_DATA_SIZE, partition.partition_key,
                [this, &hash_exception_error](
                    VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP], u64 offset_) {
                  // EncryptGroups calls ReadWiiDecrypted, which calls ReadFromGroups,
                  // which populates m_exception_list when m_write_to_exception_list == true
                  if (!ApplyHashExceptions(m_exception_list, hash_blocks))
                    hash_exception_error = true;
                }))
        {
          return false;
        }
        if (hash_exception_error)
          return false;

        offset += bytes_to_read;
        size -= bytes_to_read;
        out_ptr += bytes_to_read;
      }
    }
    else
    {
      const RawDataEntry& raw_data = m_raw_data_entries[data.index];
      if (!ReadFromGroups(&offset, &size, &out_ptr, chunk_size, VolumeWii::BLOCK_TOTAL_SIZE,
                          Common::swap64(raw_data.data_offset), Common::swap64(raw_data.data_size),
                          Common::swap32(raw_data.group_index),
                          Common::swap32(raw_data.number_of_groups), 0))
      {
        return false;
      }
    }
  }

  return true;
}

template <bool RVZ>
const typename WIARVZFileReader<RVZ>::PartitionEntry*
WIARVZFileReader<RVZ>::GetPartition(u64 partition_data_offset, u32* partition_first_sector) const
{
  const auto it = m_data_entries.upper_bound(partition_data_offset);
  if (it == m_data_entries.end() || !it->second.is_partition)
    return nullptr;

  const PartitionEntry* partition = &m_partition_entries[it->second.index];
  *partition_first_sector = Common::swap32(partition->data_entries[0].first_sector);
  if (partition_data_offset != *partition_first_sector * VolumeWii::BLOCK_TOTAL_SIZE)
    return nullptr;

  return partition;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::SupportsReadWiiDecrypted(u64 offset, u64 size,
                                                     u64 partition_data_offset) const
{
  u32 partition_first_sector;
  const PartitionEntry* partition = GetPartition(partition_data_offset, &partition_first_sector);
  if (!partition)
    return false;

  for (const PartitionDataEntry& data : partition->data_entries)
  {
    const u32 start_sector = Common::swap32(data.first_sector) - partition_first_sector;
    const u32 end_sector = start_sector + Common::swap32(data.number_of_sectors);

    if (offset + size <= end_sector * VolumeWii::BLOCK_DATA_SIZE)
      return true;
  }

  return false;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::ReadWiiDecrypted(u64 offset, u64 size, u8* out_ptr,
                                             u64 partition_data_offset)
{
  u32 partition_first_sector;
  const PartitionEntry* partition = GetPartition(partition_data_offset, &partition_first_sector);
  if (!partition)
    return false;

  const u64 chunk_size = Common::swap32(m_header_2.chunk_size) * VolumeWii::BLOCK_DATA_SIZE /
                         VolumeWii::BLOCK_TOTAL_SIZE;

  for (const PartitionDataEntry& data : partition->data_entries)
  {
    if (size == 0)
      return true;

    const u64 data_offset =
        (Common::swap32(data.first_sector) - partition_first_sector) * VolumeWii::BLOCK_DATA_SIZE;
    const u64 data_size = Common::swap32(data.number_of_sectors) * VolumeWii::BLOCK_DATA_SIZE;

    if (!ReadFromGroups(
            &offset, &size, &out_ptr, chunk_size, VolumeWii::BLOCK_DATA_SIZE, data_offset,
            data_size, Common::swap32(data.group_index), Common::swap32(data.number_of_groups),
            std::max<u32>(1, static_cast<u32>(chunk_size / VolumeWii::GROUP_DATA_SIZE))))
    {
      return false;
    }
  }

  return size == 0;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::ReadFromGroups(u64* offset, u64* size, u8** out_ptr, u64 chunk_size,
                                           u32 sector_size, u64 data_offset, u64 data_size,
                                           u32 group_index, u32 number_of_groups,
                                           u32 exception_lists)
{
  if (data_offset + data_size <= *offset)
    return true;

  if (*offset < data_offset)
    return false;

  const u64 skipped_data = data_offset % sector_size;
  data_offset -= skipped_data;
  data_size += skipped_data;

  const u64 start_group_index = (*offset - data_offset) / chunk_size;
  for (u64 i = start_group_index; i < number_of_groups && (*size) > 0; ++i)
  {
    const u64 total_group_index = group_index + i;
    if (total_group_index >= m_group_entries.size())
      return false;

    const GroupEntry group = m_group_entries[total_group_index];
    const u64 group_offset_in_data = i * chunk_size;
    const u64 offset_in_group = *offset - group_offset_in_data - data_offset;

    chunk_size = std::min(chunk_size, data_size - group_offset_in_data);

    const u64 bytes_to_read = std::min(chunk_size - offset_in_group, *size);
    u32 group_data_size = Common::swap32(group.data_size);

    WIARVZCompressionType compression_type = m_compression_type;
    u32 rvz_packed_size = 0;
    if constexpr (RVZ)
    {
      if ((group_data_size & 0x80000000) == 0)
        compression_type = WIARVZCompressionType::None;

      group_data_size &= 0x7FFFFFFF;

      rvz_packed_size = Common::swap32(group.rvz_packed_size);
    }

    if (group_data_size == 0)
    {
      std::memset(*out_ptr, 0, bytes_to_read);
    }
    else
    {
      const u64 group_offset_in_file = static_cast<u64>(Common::swap32(group.data_offset)) << 2;

      Chunk& chunk =
          ReadCompressedData(group_offset_in_file, group_data_size, chunk_size, compression_type,
                             exception_lists, rvz_packed_size, group_offset_in_data);

      if (!chunk.Read(offset_in_group, bytes_to_read, *out_ptr))
      {
        m_cached_chunk_offset = std::numeric_limits<u64>::max();  // Invalidate the cache
        return false;
      }

      if (m_write_to_exception_list && m_exception_list_last_group_index != total_group_index)
      {
        const u64 exception_list_index = offset_in_group / VolumeWii::GROUP_DATA_SIZE;
        const u16 additional_offset =
            static_cast<u16>(group_offset_in_data % VolumeWii::GROUP_DATA_SIZE /
                             VolumeWii::BLOCK_DATA_SIZE * VolumeWii::BLOCK_HEADER_SIZE);
        chunk.GetHashExceptions(&m_exception_list, exception_list_index, additional_offset);
        m_exception_list_last_group_index = total_group_index;
      }
    }

    *offset += bytes_to_read;
    *size -= bytes_to_read;
    *out_ptr += bytes_to_read;
  }

  return true;
}

template <bool RVZ>
typename WIARVZFileReader<RVZ>::Chunk&
WIARVZFileReader<RVZ>::ReadCompressedData(u64 offset_in_file, u64 compressed_size,
                                          u64 decompressed_size,
                                          WIARVZCompressionType compression_type,
                                          u32 exception_lists, u32 rvz_packed_size, u64 data_offset)
{
  if (offset_in_file == m_cached_chunk_offset)
    return m_cached_chunk;

  std::unique_ptr<Decompressor> decompressor;
  switch (compression_type)
  {
  case WIARVZCompressionType::None:
    decompressor = std::make_unique<NoneDecompressor>();
    break;
  case WIARVZCompressionType::Purge:
    decompressor = std::make_unique<PurgeDecompressor>(rvz_packed_size == 0 ? decompressed_size :
                                                                              rvz_packed_size);
    break;
  case WIARVZCompressionType::Bzip2:
    decompressor = std::make_unique<Bzip2Decompressor>();
    break;
  case WIARVZCompressionType::LZMA:
    decompressor = std::make_unique<LZMADecompressor>(false, m_header_2.compressor_data,
                                                      m_header_2.compressor_data_size);
    break;
  case WIARVZCompressionType::LZMA2:
    decompressor = std::make_unique<LZMADecompressor>(true, m_header_2.compressor_data,
                                                      m_header_2.compressor_data_size);
    break;
  case WIARVZCompressionType::Zstd:
    decompressor = std::make_unique<ZstdDecompressor>();
    break;
  }

  const bool compressed_exception_lists = compression_type > WIARVZCompressionType::Purge;

  m_cached_chunk =
      Chunk(&m_file, offset_in_file, compressed_size, decompressed_size, exception_lists,
            compressed_exception_lists, rvz_packed_size, data_offset, std::move(decompressor));
  m_cached_chunk_offset = offset_in_file;
  return m_cached_chunk;
}

template <bool RVZ>
std::string WIARVZFileReader<RVZ>::VersionToString(u32 version)
{
  const u8 a = version >> 24;
  const u8 b = (version >> 16) & 0xff;
  const u8 c = (version >> 8) & 0xff;
  const u8 d = version & 0xff;

  if (d == 0 || d == 0xff)
    return fmt::format("{}.{:02x}.{:02x}", a, b, c);
  else
    return fmt::format("{}.{:02x}.{:02x}.beta{}", a, b, c, d);
}

template <bool RVZ>
WIARVZFileReader<RVZ>::Chunk::Chunk() = default;

template <bool RVZ>
WIARVZFileReader<RVZ>::Chunk::Chunk(File::DirectIOFile* file, u64 offset_in_file,
                                    u64 compressed_size, u64 decompressed_size, u32 exception_lists,
                                    bool compressed_exception_lists, u32 rvz_packed_size,
                                    u64 data_offset, std::unique_ptr<Decompressor> decompressor)
    : m_decompressor(std::move(decompressor)), m_file(file), m_offset_in_file(offset_in_file),
      m_exception_lists(exception_lists), m_compressed_exception_lists(compressed_exception_lists),
      m_rvz_packed_size(rvz_packed_size), m_data_offset(data_offset)
{
  constexpr size_t MAX_SIZE_PER_EXCEPTION_LIST =
      Common::AlignUp(VolumeWii::BLOCK_HEADER_SIZE, Common::SHA1::DIGEST_LEN) /
          Common::SHA1::DIGEST_LEN * VolumeWii::BLOCKS_PER_GROUP * sizeof(HashExceptionEntry) +
      sizeof(u16);

  m_out_bytes_allocated_for_exceptions =
      m_compressed_exception_lists ? MAX_SIZE_PER_EXCEPTION_LIST * m_exception_lists : 0;

  m_in.data.resize(compressed_size);
  m_out.data.resize(decompressed_size + m_out_bytes_allocated_for_exceptions);
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::Chunk::Read(u64 offset, u64 size, u8* out_ptr)
{
  if (!m_decompressor || !m_file ||
      offset + size > m_out.data.size() - m_out_bytes_allocated_for_exceptions)
  {
    return false;
  }

  while (offset + size > GetOutBytesWrittenExcludingExceptions())
  {
    u64 bytes_to_read;
    if (offset + size == m_out.data.size())
    {
      // Read all the remaining data.
      bytes_to_read = m_in.data.size() - m_in.bytes_written;
    }
    else
    {
      // Pick a suitable amount of compressed data to read. We have to ensure that bytes_to_read
      // is larger than 0 and smaller than or equal to the number of bytes available to read,
      // but the rest is a bit arbitrary and could be changed.

      // The compressed data is probably not much bigger than the decompressed data.
      // Add a few bytes for possible compression overhead and for any hash exceptions.
      bytes_to_read = offset + size - GetOutBytesWrittenExcludingExceptions() + 0x100;

      // Align the access in an attempt to gain speed. But we don't actually know the
      // block size of the underlying storage device, so we just use the Wii block size.
      bytes_to_read =
          Common::AlignUp(bytes_to_read + m_offset_in_file, VolumeWii::BLOCK_TOTAL_SIZE) -
          m_offset_in_file;

      // Ensure we don't read too much.
      bytes_to_read = std::min<u64>(m_in.data.size() - m_in.bytes_written, bytes_to_read);
    }

    if (bytes_to_read == 0)
    {
      // Compressed size is larger than expected or decompressed size is smaller than expected
      return false;
    }

    if (!m_file->OffsetRead(m_offset_in_file, m_in.data.data() + m_in.bytes_written, bytes_to_read))
      return false;

    m_offset_in_file += bytes_to_read;
    m_in.bytes_written += bytes_to_read;

    if (m_exception_lists > 0 && !m_compressed_exception_lists)
    {
      if (!HandleExceptions(m_in.data.data(), m_in.data.size(), m_in.bytes_written,
                            &m_in_bytes_used_for_exceptions, true))
      {
        return false;
      }

      m_in_bytes_read = m_in_bytes_used_for_exceptions;
    }

    if (m_exception_lists == 0 || m_compressed_exception_lists)
    {
      if (!Decompress())
        return false;
    }

    if (m_exception_lists > 0 && m_compressed_exception_lists)
    {
      if (!HandleExceptions(m_out.data.data(), m_out_bytes_allocated_for_exceptions,
                            m_out.bytes_written, &m_out_bytes_used_for_exceptions, false))
      {
        return false;
      }

      if (m_rvz_packed_size != 0 && m_exception_lists == 0)
      {
        if (!Decompress())
          return false;
      }
    }

    if (m_exception_lists == 0)
    {
      const size_t expected_out_bytes = m_out.data.size() - m_out_bytes_allocated_for_exceptions +
                                        m_out_bytes_used_for_exceptions;

      if (m_out.bytes_written > expected_out_bytes)
        return false;  // Decompressed size is larger than expected

      // The reason why we need the m_in.bytes_written == m_in.data.size() check as part of
      // this conditional is because (for example) zstd can finish writing all data to m_out
      // before becoming done if we've given it all input data except the checksum at the end.
      if (m_out.bytes_written == expected_out_bytes && !m_decompressor->Done() &&
          m_in.bytes_written == m_in.data.size())
      {
        return false;  // Decompressed size is larger than expected
      }

      if (m_decompressor->Done() && m_in_bytes_read != m_in.data.size())
        return false;  // Compressed size is smaller than expected
    }
  }

  std::memcpy(out_ptr, m_out.data.data() + offset + m_out_bytes_used_for_exceptions, size);
  return true;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::Chunk::Decompress()
{
  if (m_rvz_packed_size != 0 && m_exception_lists == 0)
  {
    const size_t bytes_to_move = m_out.bytes_written - m_out_bytes_used_for_exceptions;

    DecompressionBuffer in{std::vector<u8>(bytes_to_move), bytes_to_move};

    // Copying to a null pointer is undefined behaviour, so only copy when we
    // actually have data to copy.
    if (bytes_to_move > 0)
    {
      std::memcpy(in.data.data(), m_out.data.data() + m_out_bytes_used_for_exceptions,
                  bytes_to_move);
    }

    m_out.bytes_written = m_out_bytes_used_for_exceptions;

    m_decompressor = std::make_unique<RVZPackDecompressor>(std::move(m_decompressor), std::move(in),
                                                           m_data_offset, m_rvz_packed_size);

    m_rvz_packed_size = 0;
  }

  return m_decompressor->Decompress(m_in, &m_out, &m_in_bytes_read);
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::Chunk::HandleExceptions(const u8* data, size_t bytes_allocated,
                                                    size_t bytes_written, size_t* bytes_used,
                                                    bool align)
{
  while (m_exception_lists > 0)
  {
    if (sizeof(u16) + *bytes_used > bytes_allocated)
    {
      ERROR_LOG_FMT(DISCIO, "More hash exceptions than expected");
      return false;
    }
    if (sizeof(u16) + *bytes_used > bytes_written)
      return true;

    const u16 exceptions = Common::swap16(data + *bytes_used);

    size_t exception_list_size = exceptions * sizeof(HashExceptionEntry) + sizeof(u16);
    if (align && m_exception_lists == 1)
      exception_list_size = Common::AlignUp(*bytes_used + exception_list_size, 4) - *bytes_used;

    if (exception_list_size + *bytes_used > bytes_allocated)
    {
      ERROR_LOG_FMT(DISCIO, "More hash exceptions than expected");
      return false;
    }
    if (exception_list_size + *bytes_used > bytes_written)
      return true;

    *bytes_used += exception_list_size;
    --m_exception_lists;
  }

  return true;
}

template <bool RVZ>
void WIARVZFileReader<RVZ>::Chunk::GetHashExceptions(
    std::vector<HashExceptionEntry>* exception_list, u64 exception_list_index,
    u16 additional_offset) const
{
  ASSERT(m_exception_lists == 0);

  const u8* data_start = m_compressed_exception_lists ? m_out.data.data() : m_in.data.data();
  const u8* data = data_start;

  for (u64 i = exception_list_index; i > 0; --i)
    data += Common::swap16(data) * sizeof(HashExceptionEntry) + sizeof(u16);

  const u16 exceptions = Common::swap16(data);
  data += sizeof(u16);

  for (size_t i = 0; i < exceptions; ++i)
  {
    std::memcpy(&exception_list->emplace_back(), data, sizeof(HashExceptionEntry));
    data += sizeof(HashExceptionEntry);

    u16& offset = exception_list->back().offset;
    offset = Common::swap16(Common::swap16(offset) + additional_offset);
  }

  ASSERT(data <= data_start + (m_compressed_exception_lists ? m_out_bytes_used_for_exceptions :
                                                              m_in_bytes_used_for_exceptions));
}

template <bool RVZ>
size_t WIARVZFileReader<RVZ>::Chunk::GetOutBytesWrittenExcludingExceptions() const
{
  return m_exception_lists == 0 ? m_out.bytes_written - m_out_bytes_used_for_exceptions : 0;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::ApplyHashExceptions(
    const std::vector<HashExceptionEntry>& exception_list,
    VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP])
{
  for (const HashExceptionEntry& exception : exception_list)
  {
    const u16 offset = Common::swap16(exception.offset);

    const size_t block_index = offset / VolumeWii::BLOCK_HEADER_SIZE;
    if (block_index > VolumeWii::BLOCKS_PER_GROUP)
      return false;

    const size_t offset_in_block = offset % VolumeWii::BLOCK_HEADER_SIZE;
    if (offset_in_block + Common::SHA1::DIGEST_LEN > VolumeWii::BLOCK_HEADER_SIZE)
      return false;

    std::memcpy(reinterpret_cast<u8*>(&hash_blocks[block_index]) + offset_in_block, &exception.hash,
                Common::SHA1::DIGEST_LEN);
  }

  return true;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::PadTo4(File::DirectIOFile* file, u64* bytes_written)
{
  constexpr u32 ZEROES = 0;
  const u64 bytes_to_write = Common::AlignUp(*bytes_written, 4) - *bytes_written;
  if (bytes_to_write == 0)
    return true;

  *bytes_written += bytes_to_write;
  return file->Write(Common::AsU8Span(ZEROES).first(bytes_to_write));
}

template <bool RVZ>
void WIARVZFileReader<RVZ>::AddRawDataEntry(u64 offset, u64 size, int chunk_size, u32* total_groups,
                                            std::vector<RawDataEntry>* raw_data_entries,
                                            std::vector<DataEntry>* data_entries)
{
  constexpr size_t SKIP_SIZE = sizeof(WIAHeader2::disc_header);
  const u64 skip = offset < SKIP_SIZE ? std::min(SKIP_SIZE - offset, size) : 0;

  offset += skip;
  size -= skip;

  if (size == 0)
    return;

  const u32 group_index = *total_groups;
  const u32 groups = static_cast<u32>(Common::AlignUp(size, chunk_size) / chunk_size);
  *total_groups += groups;

  data_entries->emplace_back(raw_data_entries->size());
  raw_data_entries->emplace_back(RawDataEntry{Common::swap64(offset), Common::swap64(size),
                                              Common::swap32(group_index), Common::swap32(groups)});
}

template <bool RVZ>
typename WIARVZFileReader<RVZ>::PartitionDataEntry WIARVZFileReader<RVZ>::CreatePartitionDataEntry(
    u64 offset, u64 size, u32 index, int chunk_size, u32* total_groups,
    const std::vector<PartitionEntry>& partition_entries, std::vector<DataEntry>* data_entries)
{
  const u32 group_index = *total_groups;
  const u64 rounded_size = Common::AlignDown(size, VolumeWii::BLOCK_TOTAL_SIZE);
  const u32 groups = static_cast<u32>(Common::AlignUp(rounded_size, chunk_size) / chunk_size);
  *total_groups += groups;

  data_entries->emplace_back(partition_entries.size(), index);
  return PartitionDataEntry{Common::swap32(offset / VolumeWii::BLOCK_TOTAL_SIZE),
                            Common::swap32(size / VolumeWii::BLOCK_TOTAL_SIZE),
                            Common::swap32(group_index), Common::swap32(groups)};
}

template <bool RVZ>
ConversionResultCode WIARVZFileReader<RVZ>::SetUpDataEntriesForWriting(
    const VolumeDisc* volume, int chunk_size, u64 iso_size, u32* total_groups,
    std::vector<PartitionEntry>* partition_entries, std::vector<RawDataEntry>* raw_data_entries,
    std::vector<DataEntry>* data_entries, std::vector<const FileSystem*>* partition_file_systems)
{
  std::vector<Partition> partitions;
  if (volume && volume->HasWiiHashes() && volume->HasWiiEncryption())
    partitions = volume->GetPartitions();

  std::ranges::sort(partitions, {}, &Partition::offset);

  *total_groups = 0;

  u64 last_partition_end_offset = 0;

  const auto add_raw_data_entry = [&](u64 offset, u64 size) {
    return AddRawDataEntry(offset, size, chunk_size, total_groups, raw_data_entries, data_entries);
  };

  const auto create_partition_data_entry = [&](u64 offset, u64 size, u32 index) {
    return CreatePartitionDataEntry(offset, size, index, chunk_size, total_groups,
                                    *partition_entries, data_entries);
  };

  for (const Partition& partition : partitions)
  {
    // If a partition is odd in some way that prevents us from encoding it as a partition,
    // we encode it as raw data instead by skipping the current loop iteration.
    // Partitions can always be encoded as raw data, but it is less space efficient.

    if (partition.offset < last_partition_end_offset)
    {
      WARN_LOG_FMT(DISCIO, "Overlapping partitions at {:x}", partition.offset);
      continue;
    }

    if (volume->ReadSwapped<u32>(partition.offset, PARTITION_NONE) != 0x10001U)
    {
      // This looks more like garbage data than an actual partition.
      // The values of data_offset and data_size will very likely also be garbage.
      // Some WBFS writing programs scrub the SSBB Masterpiece partitions without
      // removing them from the partition table, causing this problem.
      WARN_LOG_FMT(DISCIO, "Invalid partition at {:x}", partition.offset);
      continue;
    }

    std::optional<u64> data_offset =
        volume->ReadSwappedAndShifted(partition.offset + 0x2b8, PARTITION_NONE);
    std::optional<u64> data_size =
        volume->ReadSwappedAndShifted(partition.offset + 0x2bc, PARTITION_NONE);

    if (!data_offset || !data_size)
      return ConversionResultCode::ReadFailed;

    const u64 data_start = partition.offset + *data_offset;
    const u64 data_end = data_start + *data_size;

    if (data_start % VolumeWii::BLOCK_TOTAL_SIZE != 0)
    {
      WARN_LOG_FMT(DISCIO, "Misaligned partition at {:x}", partition.offset);
      continue;
    }

    if (*data_size < VolumeWii::BLOCK_TOTAL_SIZE)
    {
      WARN_LOG_FMT(DISCIO, "Very small partition at {:x}", partition.offset);
      continue;
    }

    if (data_end > iso_size)
    {
      WARN_LOG_FMT(DISCIO, "Too large partition at {:x}", partition.offset);
      *data_size = iso_size - *data_offset - partition.offset;
    }

    const std::optional<u64> fst_offset = GetFSTOffset(*volume, partition);
    const std::optional<u64> fst_size = GetFSTSize(*volume, partition);

    if (!fst_offset || !fst_size)
      return ConversionResultCode::ReadFailed;

    const IOS::ES::TicketReader& ticket = volume->GetTicket(partition);
    if (!ticket.IsValid())
      return ConversionResultCode::ReadFailed;

    add_raw_data_entry(last_partition_end_offset, partition.offset - last_partition_end_offset);

    add_raw_data_entry(partition.offset, *data_offset);

    const u64 fst_end = volume->PartitionOffsetToRawOffset(*fst_offset + *fst_size, partition);
    const u64 split_point = std::min(
        data_end, Common::AlignUp(fst_end - data_start, VolumeWii::GROUP_TOTAL_SIZE) + data_start);

    PartitionEntry partition_entry;
    partition_entry.partition_key = ticket.GetTitleKey();
    partition_entry.data_entries[0] =
        create_partition_data_entry(data_start, split_point - data_start, 0);
    partition_entry.data_entries[1] =
        create_partition_data_entry(split_point, data_end - split_point, 1);

    // Note: We can't simply set last_partition_end_offset to data_end,
    // because construct_partition_data_entry may have rounded it
    last_partition_end_offset =
        (Common::swap32(partition_entry.data_entries[1].first_sector) +
         Common::swap32(partition_entry.data_entries[1].number_of_sectors)) *
        VolumeWii::BLOCK_TOTAL_SIZE;

    partition_entries->emplace_back(std::move(partition_entry));
    partition_file_systems->emplace_back(volume->GetFileSystem(partition));
  }

  add_raw_data_entry(last_partition_end_offset, iso_size - last_partition_end_offset);

  return ConversionResultCode::Success;
}

template <bool RVZ>
std::optional<std::vector<u8>> WIARVZFileReader<RVZ>::Compress(Compressor* compressor,
                                                               const u8* data, size_t size)
{
  if (compressor)
  {
    if (!compressor->Start(size) || !compressor->Compress(data, size) || !compressor->End())
      return std::nullopt;

    data = compressor->GetData();
    size = compressor->GetSize();
  }

  return std::vector<u8>(data, data + size);
}

template <bool RVZ>
void WIARVZFileReader<RVZ>::SetUpCompressor(std::unique_ptr<Compressor>* compressor,
                                            WIARVZCompressionType compression_type,
                                            int compression_level, WIAHeader2* header_2)
{
  switch (compression_type)
  {
  case WIARVZCompressionType::None:
    *compressor = nullptr;
    break;
  case WIARVZCompressionType::Purge:
    *compressor = std::make_unique<PurgeCompressor>();
    break;
  case WIARVZCompressionType::Bzip2:
    *compressor = std::make_unique<Bzip2Compressor>(compression_level);
    break;
  case WIARVZCompressionType::LZMA:
  case WIARVZCompressionType::LZMA2:
  {
    u8* compressor_data = nullptr;
    u8* compressor_data_size = nullptr;

    if (header_2)
    {
      compressor_data = header_2->compressor_data;
      compressor_data_size = &header_2->compressor_data_size;
    }

    const bool lzma2 = compression_type == WIARVZCompressionType::LZMA2;
    *compressor = std::make_unique<LZMACompressor>(lzma2, compression_level, compressor_data,
                                                   compressor_data_size);
    break;
  }
  case WIARVZCompressionType::Zstd:
    *compressor = std::make_unique<ZstdCompressor>(compression_level);
    break;
  }
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::TryReuse(std::map<ReuseID, GroupEntry>* reusable_groups,
                                     std::mutex* reusable_groups_mutex,
                                     OutputParametersEntry* entry)
{
  if (entry->reused_group)
    return true;

  if (!entry->reuse_id)
    return false;

  std::lock_guard guard(*reusable_groups_mutex);
  const auto it = reusable_groups->find(*entry->reuse_id);
  if (it == reusable_groups->end())
    return false;

  entry->reused_group = it->second;
  return true;
}

static bool AllAre(const std::vector<u8>& data, u8 x)
{
  return std::ranges::all_of(data, [x](u8 y) { return x == y; });
}

static bool AllAre(const u8* begin, const u8* end, u8 x)
{
  return std::all_of(begin, end, [x](u8 y) { return x == y; });
}

static bool AllZero(const std::vector<u8>& data)
{
  return AllAre(data, 0);
}

static bool AllSame(const std::vector<u8>& data)
{
  return AllAre(data, data.front());
}

static bool AllSame(const u8* begin, const u8* end)
{
  return AllAre(begin, end, *begin);
}

template <typename OutputParametersEntry>
static void RVZPack(const u8* in, OutputParametersEntry* out, u64 bytes_per_chunk, size_t chunks,
                    u64 total_size, u64 data_offset, bool multipart, bool allow_junk_reuse,
                    bool compression, const FileSystem* file_system)
{
  using Seed = std::array<u32, LaggedFibonacciGenerator::SEED_SIZE>;
  struct JunkInfo
  {
    size_t start_offset;
    Seed seed;
  };

  constexpr size_t SEED_SIZE = LaggedFibonacciGenerator::SEED_SIZE * sizeof(u32);

  // Maps end_offset -> (start_offset, seed)
  std::map<size_t, JunkInfo> junk_info;

  size_t position = 0;
  while (position < total_size)
  {
    // Skip the 0 to 32 zero bytes that typically come after a file
    size_t zeroes = 0;
    while (position + zeroes < total_size && in[position + zeroes] == 0)
      ++zeroes;

    // If there are very many zero bytes (perhaps the PRNG junk data has been scrubbed?)
    // and we aren't using compression, it makes sense to encode the zero bytes as junk.
    // If we are using compression, the compressor will likely encode zeroes better than we can
    if (!compression && zeroes > SEED_SIZE)
      junk_info.emplace(position + zeroes, JunkInfo{position, {}});

    position += zeroes;
    data_offset += zeroes;

    const size_t bytes_to_read =
        std::min(Common::AlignUp(data_offset + 1, VolumeWii::BLOCK_TOTAL_SIZE) - data_offset,
                 total_size - position);

    const size_t data_offset_mod = static_cast<size_t>(data_offset % VolumeWii::BLOCK_TOTAL_SIZE);

    Seed seed;
    const size_t bytes_reconstructed = LaggedFibonacciGenerator::GetSeed(
        in + position, bytes_to_read, data_offset_mod, seed.data());

    if (bytes_reconstructed > 0)
      junk_info.emplace(position + bytes_reconstructed, JunkInfo{position, seed});

    if (file_system)
    {
      const std::unique_ptr<DiscIO::FileInfo> file_info =
          file_system->FindFileInfo(data_offset + bytes_reconstructed);

      // If we're at a file and there's more space in this block after the file,
      // continue after the file instead of skipping to the next block
      if (file_info)
      {
        const u64 file_end_offset = file_info->GetOffset() + file_info->GetSize();
        if (file_end_offset < data_offset + bytes_to_read)
        {
          position += file_end_offset - data_offset;
          data_offset = file_end_offset;
          continue;
        }
      }
    }

    position += bytes_to_read;
    data_offset += bytes_to_read;
  }

  for (size_t i = 0; i < chunks; ++i)
  {
    OutputParametersEntry& entry = out[i];
    if (entry.reused_group)
      continue;

    u64 current_offset = i * bytes_per_chunk;
    const u64 end_offset = std::min(current_offset + bytes_per_chunk, total_size);

    const bool store_junk_efficiently = allow_junk_reuse || !entry.reuse_id;

    // TODO: It would be possible to support skipping RVZ packing even when the chunk size is larger
    // than 2 MiB (multipart == true), but it would be more effort than it's worth since Dolphin's
    // converter doesn't expose chunk sizes larger than 2 MiB to the user anyway
    bool first_loop_iteration = !multipart;

    while (current_offset < end_offset)
    {
      u64 next_junk_start = end_offset;
      u64 next_junk_end = end_offset;
      Seed* seed = nullptr;
      if (store_junk_efficiently && end_offset - current_offset > SEED_SIZE)
      {
        const auto next_junk_it = junk_info.upper_bound(current_offset + SEED_SIZE);
        if (next_junk_it != junk_info.end() &&
            next_junk_it->second.start_offset + SEED_SIZE < end_offset)
        {
          next_junk_start = std::max<u64>(current_offset, next_junk_it->second.start_offset);
          next_junk_end = std::min<u64>(end_offset, next_junk_it->first);
          seed = &next_junk_it->second.seed;
        }
      }

      if (first_loop_iteration)
      {
        if (next_junk_start == end_offset)
        {
          // Storing this chunk with RVZ packing would be inefficient, so store it without
          PushBack(&entry.main_data, in + current_offset, in + end_offset);
          break;
        }

        first_loop_iteration = false;
      }

      const u64 non_junk_bytes = next_junk_start - current_offset;
      if (non_junk_bytes > 0)
      {
        const u8* ptr = in + current_offset;

        PushBack(&entry.main_data, Common::swap32(static_cast<u32>(non_junk_bytes)));
        PushBack(&entry.main_data, ptr, ptr + non_junk_bytes);

        current_offset += non_junk_bytes;
        entry.rvz_packed_size += sizeof(u32) + non_junk_bytes;
      }

      const u64 junk_bytes = next_junk_end - current_offset;
      if (junk_bytes > 0)
      {
        PushBack(&entry.main_data, Common::swap32(static_cast<u32>(junk_bytes) | 0x80000000));
        PushBack(&entry.main_data, *seed);

        current_offset += junk_bytes;
        entry.rvz_packed_size += sizeof(u32) + SEED_SIZE;
      }
    }
  }
}

template <typename OutputParametersEntry>
static void RVZPack(const u8* in, OutputParametersEntry* out, u64 size, u64 data_offset,
                    bool allow_junk_reuse, bool compression, const FileSystem* file_system)
{
  RVZPack(in, out, size, 1, size, data_offset, false, allow_junk_reuse, compression, file_system);
}

template <bool RVZ>
ConversionResult<typename WIARVZFileReader<RVZ>::OutputParameters>
WIARVZFileReader<RVZ>::ProcessAndCompress(CompressThreadState* state, CompressParameters parameters,
                                          const std::vector<PartitionEntry>& partition_entries,
                                          const std::vector<DataEntry>& data_entries,
                                          const FileSystem* file_system,
                                          std::map<ReuseID, GroupEntry>* reusable_groups,
                                          std::mutex* reusable_groups_mutex,
                                          u64 chunks_per_wii_group, u64 exception_lists_per_chunk,
                                          bool compressed_exception_lists, bool compression)
{
  std::vector<OutputParametersEntry> output_entries;

  if (!parameters.data_entry->is_partition)
  {
    OutputParametersEntry& entry = output_entries.emplace_back();
    std::vector<u8>& data = parameters.data;

    if (AllSame(data))
      entry.reuse_id = ReuseID{WiiKey{}, data.size(), false, data.front()};

    if constexpr (RVZ)
    {
      RVZPack(data.data(), output_entries.data(), data.size(), parameters.data_offset, true,
              compression, file_system);
    }
    else
    {
      entry.main_data = std::move(data);
    }
  }
  else
  {
    const PartitionEntry& partition_entry = partition_entries[parameters.data_entry->index];

    auto aes_context = Common::AES::CreateContextDecrypt(partition_entry.partition_key.data());

    const u64 groups = Common::AlignUp(parameters.data.size(), VolumeWii::GROUP_TOTAL_SIZE) /
                       VolumeWii::GROUP_TOTAL_SIZE;

    ASSERT(parameters.data.size() % VolumeWii::BLOCK_TOTAL_SIZE == 0);
    const u64 blocks = parameters.data.size() / VolumeWii::BLOCK_TOTAL_SIZE;

    const u64 blocks_per_chunk = chunks_per_wii_group == 1 ?
                                     exception_lists_per_chunk * VolumeWii::BLOCKS_PER_GROUP :
                                     VolumeWii::BLOCKS_PER_GROUP / chunks_per_wii_group;

    const u64 chunks = Common::AlignUp(blocks, blocks_per_chunk) / blocks_per_chunk;

    const u64 in_data_per_chunk = blocks_per_chunk * VolumeWii::BLOCK_TOTAL_SIZE;
    const u64 out_data_per_chunk = blocks_per_chunk * VolumeWii::BLOCK_DATA_SIZE;

    const size_t first_chunk = output_entries.size();

    const auto create_reuse_id = [&partition_entry, blocks,
                                  blocks_per_chunk](u8 value, bool encrypted, u64 block) {
      const u64 size = std::min(blocks - block, blocks_per_chunk) * VolumeWii::BLOCK_DATA_SIZE;
      return ReuseID{partition_entry.partition_key, size, encrypted, value};
    };

    const u8* parameters_data_end = parameters.data.data() + parameters.data.size();
    for (u64 i = 0; i < chunks; ++i)
    {
      const u64 block_index = i * blocks_per_chunk;

      OutputParametersEntry& entry = output_entries.emplace_back();
      std::optional<ReuseID>& reuse_id = entry.reuse_id;

      // Set this chunk as reusable if the encrypted data is AllSame
      const u8* data = parameters.data.data() + block_index * VolumeWii::BLOCK_TOTAL_SIZE;
      if (AllSame(data, std::min(parameters_data_end, data + in_data_per_chunk)))
        reuse_id = create_reuse_id(parameters.data.front(), true, i * blocks_per_chunk);

      TryReuse(reusable_groups, reusable_groups_mutex, &entry);
      if (!entry.reused_group && reuse_id)
      {
        const auto it = std::ranges::find(output_entries.begin(), output_entries.begin() + i,
                                          reuse_id, &OutputParametersEntry::reuse_id);
        if (it != output_entries.begin() + i)
          entry.reused_group = it->reused_group;
      }
    }

    if (!std::ranges::all_of(output_entries,
                             [](const auto& entry) { return entry.reused_group.has_value(); }))
    {
      const u64 number_of_exception_lists =
          chunks_per_wii_group == 1 ? exception_lists_per_chunk : chunks;
      std::vector<std::vector<HashExceptionEntry>> exception_lists(number_of_exception_lists);

      for (u64 i = 0; i < groups; ++i)
      {
        const u64 offset_of_group = i * VolumeWii::GROUP_TOTAL_SIZE;
        const u64 write_offset_of_group = i * VolumeWii::GROUP_DATA_SIZE;

        const u64 blocks_in_this_group =
            std::min<u64>(VolumeWii::BLOCKS_PER_GROUP, blocks - i * VolumeWii::BLOCKS_PER_GROUP);

        for (u32 j = 0; j < VolumeWii::BLOCKS_PER_GROUP; ++j)
        {
          if (j < blocks_in_this_group)
          {
            const u64 offset_of_block = offset_of_group + j * VolumeWii::BLOCK_TOTAL_SIZE;
            VolumeWii::DecryptBlockData(parameters.data.data() + offset_of_block,
                                        state->decryption_buffer[j].data(), aes_context.get());
          }
          else
          {
            state->decryption_buffer[j].fill(0);
          }
        }

        VolumeWii::HashGroup(state->decryption_buffer.data(), state->hash_buffer.data());

        for (u64 j = 0; j < blocks_in_this_group; ++j)
        {
          const u64 chunk_index = j / blocks_per_chunk;
          const u64 block_index_in_chunk = j % blocks_per_chunk;

          if (output_entries[chunk_index].reused_group)
            continue;

          const u64 exception_list_index = chunks_per_wii_group == 1 ? i : chunk_index;

          const u64 offset_of_block = offset_of_group + j * VolumeWii::BLOCK_TOTAL_SIZE;
          const u64 hash_offset_of_block = block_index_in_chunk * VolumeWii::BLOCK_HEADER_SIZE;

          VolumeWii::HashBlock hashes;
          VolumeWii::DecryptBlockHashes(parameters.data.data() + offset_of_block, &hashes,
                                        aes_context.get());

          const auto compare_hash = [&](size_t offset_in_block) {
            ASSERT(offset_in_block + Common::SHA1::DIGEST_LEN <= VolumeWii::BLOCK_HEADER_SIZE);

            const u8* desired_hash = reinterpret_cast<u8*>(&hashes) + offset_in_block;
            const u8* computed_hash =
                reinterpret_cast<u8*>(&state->hash_buffer[j]) + offset_in_block;

            // We want to store a hash exception either if there is a hash mismatch, or if this
            // chunk might get reused in a context where it is paired up (within a 2 MiB Wii group)
            // with chunks that are different from the chunks it currently is paired up with, since
            // that affects the recalculated hashes. Chunks which have been marked as reusable at
            // this point normally have zero matching hashes anyway, so this shouldn't waste space.
            if ((chunks_per_wii_group != 1 && output_entries[chunk_index].reuse_id) ||
                !std::equal(desired_hash, desired_hash + Common::SHA1::DIGEST_LEN, computed_hash))
            {
              const u64 hash_offset = hash_offset_of_block + offset_in_block;
              ASSERT(hash_offset <= std::numeric_limits<u16>::max());

              HashExceptionEntry& exception = exception_lists[exception_list_index].emplace_back();
              exception.offset = Common::swap16(static_cast<u16>(hash_offset));
              std::memcpy(exception.hash.data(), desired_hash, Common::SHA1::DIGEST_LEN);
            }
          };

          const auto compare_hashes = [&compare_hash](size_t offset, size_t size) {
            for (size_t l = 0; l < size; l += Common::SHA1::DIGEST_LEN)
              // The std::min is to ensure that we don't go beyond the end of HashBlock with
              // padding_2, which is 32 bytes long (not divisible by SHA1::DIGEST_LEN, which is 20).
              compare_hash(offset + std::min(l, size - Common::SHA1::DIGEST_LEN));
          };

          using HashBlock = VolumeWii::HashBlock;
          compare_hashes(offsetof(HashBlock, h0), sizeof(HashBlock::h0));
          compare_hashes(offsetof(HashBlock, padding_0), sizeof(HashBlock::padding_0));
          compare_hashes(offsetof(HashBlock, h1), sizeof(HashBlock::h1));
          compare_hashes(offsetof(HashBlock, padding_1), sizeof(HashBlock::padding_1));
          compare_hashes(offsetof(HashBlock, h2), sizeof(HashBlock::h2));
          compare_hashes(offsetof(HashBlock, padding_2), sizeof(HashBlock::padding_2));
        }

        static_assert(std::is_trivially_copyable_v<
                      typename decltype(CompressThreadState::decryption_buffer)::value_type>);
        if constexpr (RVZ)
        {
          // We must not store junk efficiently for chunks that may get reused at a position
          // which has a different value of data_offset % VolumeWii::BLOCK_TOTAL_SIZE
          const bool allow_junk_reuse = chunks_per_wii_group == 1;

          const u64 bytes_per_chunk = std::min(out_data_per_chunk, VolumeWii::GROUP_DATA_SIZE);
          const u64 total_size = blocks_in_this_group * VolumeWii::BLOCK_DATA_SIZE;
          const u64 data_offset = parameters.data_offset + write_offset_of_group;

          RVZPack(state->decryption_buffer[0].data(), output_entries.data() + first_chunk,
                  bytes_per_chunk, chunks, total_size, data_offset, groups > 1, allow_junk_reuse,
                  compression, file_system);
        }
        else
        {
          const u8* in_ptr = state->decryption_buffer[0].data();
          for (u64 j = 0; j < chunks; ++j)
          {
            OutputParametersEntry& entry = output_entries[first_chunk + j];

            if (!entry.reused_group)
            {
              const u64 bytes_left = (blocks - j * blocks_per_chunk) * VolumeWii::BLOCK_DATA_SIZE;
              const u64 bytes_to_write_total = std::min(out_data_per_chunk, bytes_left);

              if (i == 0)
                entry.main_data.resize(bytes_to_write_total);

              const u64 bytes_to_write = std::min(bytes_to_write_total, VolumeWii::GROUP_DATA_SIZE);

              std::memcpy(entry.main_data.data() + write_offset_of_group, in_ptr, bytes_to_write);

              // Set this chunk as reusable if the decrypted data is AllSame.
              // There is also a requirement that it lacks exceptions, but this is checked later
              if (i == 0 && !entry.reuse_id)
              {
                if (AllSame(in_ptr, in_ptr + bytes_to_write))
                  entry.reuse_id = create_reuse_id(*in_ptr, false, j * blocks_per_chunk);
              }
              else
              {
                if (entry.reuse_id && !entry.reuse_id->encrypted &&
                    (!AllSame(in_ptr, in_ptr + bytes_to_write) || entry.reuse_id->value != *in_ptr))
                {
                  entry.reuse_id.reset();
                }
              }
            }

            in_ptr += out_data_per_chunk;
          }
        }
      }

      for (size_t i = 0; i < exception_lists.size(); ++i)
      {
        OutputParametersEntry& entry = output_entries[chunks_per_wii_group == 1 ? 0 : i];
        if (entry.reused_group)
          continue;

        const std::vector<HashExceptionEntry>& in = exception_lists[i];
        std::vector<u8>& out = entry.exception_lists;

        const u16 exceptions = Common::swap16(static_cast<u16>(in.size()));
        PushBack(&out, exceptions);
        for (const HashExceptionEntry& exception : in)
          PushBack(&out, exception);
      }

      for (u64 i = 0; i < output_entries.size(); ++i)
      {
        OutputParametersEntry& entry = output_entries[i];

        // If this chunk was set as reusable because the decrypted data is AllSame,
        // but it has exceptions, unmark it as reusable
        if (entry.reuse_id && !entry.reuse_id->encrypted && !AllZero(entry.exception_lists))
          entry.reuse_id.reset();
      }
    }
  }

  for (OutputParametersEntry& entry : output_entries)
  {
    TryReuse(reusable_groups, reusable_groups_mutex, &entry);
    if (entry.reused_group)
      continue;

    // Special case - a compressed size of zero is treated by WIA as meaning the data is all zeroes
    if (entry.reuse_id && !entry.reuse_id->encrypted && entry.reuse_id->value == 0)
    {
      entry.exception_lists.clear();
      entry.main_data.clear();
      if constexpr (RVZ)
      {
        entry.rvz_packed_size = 0;
        entry.compressed = false;
      }
      continue;
    }

    const auto pad_exception_lists = [&entry] {
      while (entry.exception_lists.size() % 4 != 0)
        entry.exception_lists.push_back(0);
    };

    if (state->compressor)
    {
      if (!state->compressor->Start(entry.exception_lists.size() + entry.main_data.size()))
        return std::unexpected{ConversionResultCode::InternalError};
    }

    if (!entry.exception_lists.empty())
    {
      if (compressed_exception_lists && state->compressor)
      {
        if (!state->compressor->Compress(entry.exception_lists.data(),
                                         entry.exception_lists.size()))
        {
          return std::unexpected{ConversionResultCode::InternalError};
        }
      }
      else
      {
        if (!compressed_exception_lists)
          pad_exception_lists();

        if (state->compressor)
        {
          if (!state->compressor->AddPrecedingDataOnlyForPurgeHashing(entry.exception_lists.data(),
                                                                      entry.exception_lists.size()))
          {
            return std::unexpected{ConversionResultCode::InternalError};
          }
        }
      }
    }

    if (state->compressor)
    {
      if (!state->compressor->Compress(entry.main_data.data(), entry.main_data.size()))
        return std::unexpected{ConversionResultCode::InternalError};
      if (!state->compressor->End())
        return std::unexpected{ConversionResultCode::InternalError};
    }

    bool compressed = !!state->compressor;
    if constexpr (RVZ)
    {
      size_t uncompressed_size = entry.main_data.size();
      if (compressed_exception_lists)
        uncompressed_size += Common::AlignUp(entry.exception_lists.size(), 4);

      compressed = state->compressor && state->compressor->GetSize() < uncompressed_size;
      entry.compressed = compressed;

      if (!compressed)
        pad_exception_lists();
    }

    if (compressed)
    {
      const u8* data = state->compressor->GetData();
      const size_t size = state->compressor->GetSize();

      entry.main_data.resize(size);
      std::copy_n(data, size, entry.main_data.data());

      if (compressed_exception_lists)
        entry.exception_lists.clear();
    }
  }

  return OutputParameters{std::move(output_entries), parameters.bytes_read, parameters.group_index};
}

template <bool RVZ>
ConversionResultCode WIARVZFileReader<RVZ>::Output(std::vector<OutputParametersEntry>* entries,
                                                   File::DirectIOFile* outfile,
                                                   std::map<ReuseID, GroupEntry>* reusable_groups,
                                                   std::mutex* reusable_groups_mutex,
                                                   GroupEntry* group_entry, u64* bytes_written)
{
  for (OutputParametersEntry& entry : *entries)
  {
    TryReuse(reusable_groups, reusable_groups_mutex, &entry);
    if (entry.reused_group)
    {
      *group_entry = *entry.reused_group;
      ++group_entry;
      continue;
    }

    if (*bytes_written >> 2 > std::numeric_limits<u32>::max())
      return ConversionResultCode::InternalError;

    ASSERT((*bytes_written & 3) == 0);
    group_entry->data_offset = Common::swap32(static_cast<u32>(*bytes_written >> 2));

    u32 data_size = static_cast<u32>(entry.exception_lists.size() + entry.main_data.size());
    if constexpr (RVZ)
    {
      data_size = (data_size & 0x7FFFFFFF) | (static_cast<u32>(entry.compressed) << 31);
      group_entry->rvz_packed_size = Common::swap32(static_cast<u32>(entry.rvz_packed_size));
    }
    group_entry->data_size = Common::swap32(data_size);

    if (!outfile->Write(entry.exception_lists))
      return ConversionResultCode::WriteFailed;
    if (!outfile->Write(entry.main_data))
      return ConversionResultCode::WriteFailed;

    *bytes_written += entry.exception_lists.size() + entry.main_data.size();

    if (entry.reuse_id)
    {
      std::lock_guard guard(*reusable_groups_mutex);
      reusable_groups->emplace(*entry.reuse_id, *group_entry);
    }

    if (!PadTo4(outfile, bytes_written))
      return ConversionResultCode::WriteFailed;

    ++group_entry;
  }

  return ConversionResultCode::Success;
}

template <bool RVZ>
ConversionResultCode WIARVZFileReader<RVZ>::RunCallback(size_t groups_written, u64 bytes_read,
                                                        u64 bytes_written, u32 total_groups,
                                                        u64 iso_size, const CompressCB& callback)
{
  int ratio = 0;
  if (bytes_read != 0)
    ratio = static_cast<int>(100 * bytes_written / bytes_read);

  const std::string text = Common::FmtFormatT("{0} of {1} blocks. Compression ratio {2}%",
                                              groups_written, total_groups, ratio);

  const float completion = static_cast<float>(bytes_read) / iso_size;

  return callback(text, completion) ? ConversionResultCode::Success :
                                      ConversionResultCode::Canceled;
}

template <bool RVZ>
bool WIARVZFileReader<RVZ>::WriteHeader(File::DirectIOFile* file, const u8* data, size_t size,
                                        u64 upper_bound, u64* bytes_written, u64* offset_out)
{
  // The first part of the check is to prevent this from running more than once. If *bytes_written
  // is past the upper bound, we are already at the end of the file, so we don't need to do anything
  if (*bytes_written <= upper_bound && *bytes_written + size > upper_bound)
  {
    WARN_LOG_FMT(DISCIO,
                 "Headers did not fit in the allocated space. Writing to end of file instead");
    if (!file->Seek(0, File::SeekOrigin::End))
      return false;
    *bytes_written = file->Tell();
  }

  *offset_out = *bytes_written;
  if (!file->Write(data, size))
    return false;
  *bytes_written += size;
  return PadTo4(file, bytes_written);
}

template <bool RVZ>
ConversionResultCode
WIARVZFileReader<RVZ>::Convert(BlobReader* infile, const VolumeDisc* infile_volume,
                               File::DirectIOFile* outfile, WIARVZCompressionType compression_type,
                               int compression_level, int chunk_size, CompressCB callback)
{
  ASSERT(infile->GetDataSizeType() == DataSizeType::Accurate);
  ASSERT(chunk_size > 0);

  const u64 iso_size = infile->GetDataSize();
  const u64 chunks_per_wii_group = std::max<u64>(1, VolumeWii::GROUP_TOTAL_SIZE / chunk_size);
  const u64 exception_lists_per_chunk = std::max<u64>(1, chunk_size / VolumeWii::GROUP_TOTAL_SIZE);
  const bool compressed_exception_lists = compression_type > WIARVZCompressionType::Purge;

  u64 bytes_read = 0;
  u64 bytes_written = 0;
  size_t groups_processed = 0;

  WIAHeader1 header_1{};
  WIAHeader2 header_2{};

  std::vector<PartitionEntry> partition_entries;
  std::vector<RawDataEntry> raw_data_entries;
  std::vector<GroupEntry> group_entries;

  u32 total_groups;
  std::vector<DataEntry> data_entries;

  const FileSystem* non_partition_file_system =
      infile_volume ? infile_volume->GetFileSystem(PARTITION_NONE) : nullptr;
  std::vector<const FileSystem*> partition_file_systems;

  const ConversionResultCode set_up_data_entries_result = SetUpDataEntriesForWriting(
      infile_volume, chunk_size, iso_size, &total_groups, &partition_entries, &raw_data_entries,
      &data_entries, &partition_file_systems);
  if (set_up_data_entries_result != ConversionResultCode::Success)
    return set_up_data_entries_result;

  group_entries.resize(total_groups);

  const size_t partition_entries_size = partition_entries.size() * sizeof(PartitionEntry);
  const size_t raw_data_entries_size = raw_data_entries.size() * sizeof(RawDataEntry);
  const size_t group_entries_size = group_entries.size() * sizeof(GroupEntry);

  // An estimate for how much space will be taken up by headers.
  // We will reserve this much space at the beginning of the file, and if the headers don't
  // fit in that space, we will need to write them at the end of the file instead.
  const u64 headers_size_upper_bound = [&] {
    // 0x100 is added to account for compression overhead (in particular for Purge).
    u64 upper_bound = sizeof(WIAHeader1) + sizeof(WIAHeader2) + partition_entries_size +
                      raw_data_entries_size + 0x100;

    // Compared to WIA, RVZ adds an extra member to the GroupEntry struct. This added data usually
    // compresses well, so we'll assume the compression ratio for RVZ GroupEntries is 9 / 16 or
    // better. This constant is somewhat arbitrarily chosen, but no games were found that get a
    // worse compression ratio than that. There are some games that get a worse ratio than 1 / 2,
    // such as Metroid: Other M (PAL) with the default settings.
    if (RVZ && compression_type > WIARVZCompressionType::Purge)
      upper_bound += static_cast<u64>(group_entries_size) * 9 / 16;
    else
      upper_bound += group_entries_size;

    // This alignment is also somewhat arbitrary.
    return Common::AlignUp(upper_bound, VolumeWii::BLOCK_TOTAL_SIZE);
  }();

  std::vector<u8> buffer;

  buffer.resize(headers_size_upper_bound);
  outfile->Write(buffer);
  bytes_written = headers_size_upper_bound;

  if (!infile->Read(0, header_2.disc_header.size(), header_2.disc_header.data()))
    return ConversionResultCode::ReadFailed;
  // We intentionally do not increment bytes_read here, since these bytes will be read again

  std::map<ReuseID, GroupEntry> reusable_groups;
  std::mutex reusable_groups_mutex;

  const auto set_up_compress_thread_state = [&](CompressThreadState* state) {
    SetUpCompressor(&state->compressor, compression_type, compression_level, nullptr);
    return ConversionResultCode::Success;
  };

  const auto process_and_compress = [&](CompressThreadState* state, CompressParameters parameters) {
    const DataEntry& data_entry = *parameters.data_entry;
    const FileSystem* file_system = data_entry.is_partition ?
                                        partition_file_systems[data_entry.index] :
                                        non_partition_file_system;

    const bool compression = compression_type != WIARVZCompressionType::None;

    return ProcessAndCompress(state, std::move(parameters), partition_entries, data_entries,
                              file_system, &reusable_groups, &reusable_groups_mutex,
                              chunks_per_wii_group, exception_lists_per_chunk,
                              compressed_exception_lists, compression);
  };

  const auto output = [&](OutputParameters parameters) {
    const ConversionResultCode result =
        Output(&parameters.entries, outfile, &reusable_groups, &reusable_groups_mutex,
               &group_entries[parameters.group_index], &bytes_written);

    if (result != ConversionResultCode::Success)
      return result;

    return RunCallback(parameters.group_index + parameters.entries.size(), parameters.bytes_read,
                       bytes_written, total_groups, iso_size, callback);
  };

  MultithreadedCompressor<CompressThreadState, CompressParameters, OutputParameters> mt_compressor(
      set_up_compress_thread_state, process_and_compress, output);

  for (const DataEntry& data_entry : data_entries)
  {
    u32 first_group;
    u32 last_group;

    u64 data_offset;
    u64 data_size;

    u64 data_offset_in_partition;

    if (data_entry.is_partition)
    {
      const PartitionEntry& partition_entry = partition_entries[data_entry.index];
      const PartitionDataEntry& partition_data_entry =
          partition_entry.data_entries[data_entry.partition_data_index];

      first_group = Common::swap32(partition_data_entry.group_index);
      last_group = first_group + Common::swap32(partition_data_entry.number_of_groups);

      const u32 first_sector = Common::swap32(partition_data_entry.first_sector);
      data_offset = first_sector * VolumeWii::BLOCK_TOTAL_SIZE;
      data_size =
          Common::swap32(partition_data_entry.number_of_sectors) * VolumeWii::BLOCK_TOTAL_SIZE;

      const u32 block_in_partition =
          first_sector - Common::swap32(partition_entry.data_entries[0].first_sector);
      data_offset_in_partition = block_in_partition * VolumeWii::BLOCK_DATA_SIZE;
    }
    else
    {
      const RawDataEntry& raw_data_entry = raw_data_entries[data_entry.index];

      first_group = Common::swap32(raw_data_entry.group_index);
      last_group = first_group + Common::swap32(raw_data_entry.number_of_groups);

      data_offset = Common::swap64(raw_data_entry.data_offset);
      data_size = Common::swap64(raw_data_entry.data_size);

      const u64 skipped_data = data_offset % VolumeWii::BLOCK_TOTAL_SIZE;
      data_offset -= skipped_data;
      data_size += skipped_data;

      data_offset_in_partition = data_offset;
    }

    ASSERT(groups_processed == first_group);
    ASSERT(bytes_read == data_offset);

    while (groups_processed < last_group)
    {
      const ConversionResultCode status = mt_compressor.GetStatus();
      if (status != ConversionResultCode::Success)
        return status;

      u64 bytes_to_read = chunk_size;
      if (data_entry.is_partition)
        bytes_to_read = std::max<u64>(bytes_to_read, VolumeWii::GROUP_TOTAL_SIZE);
      bytes_to_read = std::min<u64>(bytes_to_read, data_offset + data_size - bytes_read);

      buffer.resize(bytes_to_read);
      if (!infile->Read(bytes_read, bytes_to_read, buffer.data()))
        return ConversionResultCode::ReadFailed;
      bytes_read += bytes_to_read;

      mt_compressor.CompressAndWrite(CompressParameters{
          buffer, &data_entry, data_offset_in_partition, bytes_read, groups_processed});

      data_offset += bytes_to_read;
      data_size -= bytes_to_read;

      if (data_entry.is_partition)
      {
        data_offset_in_partition +=
            bytes_to_read / VolumeWii::BLOCK_TOTAL_SIZE * VolumeWii::BLOCK_DATA_SIZE;
      }
      else
      {
        data_offset_in_partition += bytes_to_read;
      }

      groups_processed += Common::AlignUp(bytes_to_read, chunk_size) / chunk_size;
    }

    ASSERT(data_size == 0);
  }

  ASSERT(groups_processed == total_groups);
  ASSERT(bytes_read == iso_size);

  mt_compressor.Shutdown();

  const ConversionResultCode status = mt_compressor.GetStatus();
  if (status != ConversionResultCode::Success)
    return status;

  std::unique_ptr<Compressor> compressor;
  SetUpCompressor(&compressor, compression_type, compression_level, &header_2);

  const std::optional<std::vector<u8>> compressed_raw_data_entries = Compress(
      compressor.get(), reinterpret_cast<u8*>(raw_data_entries.data()), raw_data_entries_size);
  if (!compressed_raw_data_entries)
    return ConversionResultCode::InternalError;

  const std::optional<std::vector<u8>> compressed_group_entries =
      Compress(compressor.get(), reinterpret_cast<u8*>(group_entries.data()), group_entries_size);
  if (!compressed_group_entries)
    return ConversionResultCode::InternalError;

  bytes_written = sizeof(WIAHeader1) + sizeof(WIAHeader2);
  if (!outfile->Seek(sizeof(WIAHeader1) + sizeof(WIAHeader2), File::SeekOrigin::Begin))
    return ConversionResultCode::WriteFailed;

  u64 partition_entries_offset;
  if (!WriteHeader(outfile, reinterpret_cast<u8*>(partition_entries.data()), partition_entries_size,
                   headers_size_upper_bound, &bytes_written, &partition_entries_offset))
  {
    return ConversionResultCode::WriteFailed;
  }

  u64 raw_data_entries_offset;
  if (!WriteHeader(outfile, compressed_raw_data_entries->data(),
                   compressed_raw_data_entries->size(), headers_size_upper_bound, &bytes_written,
                   &raw_data_entries_offset))
  {
    return ConversionResultCode::WriteFailed;
  }

  u64 group_entries_offset;
  if (!WriteHeader(outfile, compressed_group_entries->data(), compressed_group_entries->size(),
                   headers_size_upper_bound, &bytes_written, &group_entries_offset))
  {
    return ConversionResultCode::WriteFailed;
  }

  u32 disc_type = 0;
  if (infile_volume)
  {
    if (infile_volume->GetVolumeType() == Platform::GameCubeDisc)
      disc_type = 1;
    else if (infile_volume->GetVolumeType() == Platform::WiiDisc)
      disc_type = 2;
  }

  header_2.disc_type = Common::swap32(disc_type);
  header_2.compression_type = Common::swap32(static_cast<u32>(compression_type));
  header_2.compression_level =
      static_cast<s32>(Common::swap32(static_cast<u32>(compression_level)));
  header_2.chunk_size = Common::swap32(static_cast<u32>(chunk_size));

  header_2.number_of_partition_entries = Common::swap32(static_cast<u32>(partition_entries.size()));
  header_2.partition_entry_size = Common::swap32(sizeof(PartitionEntry));
  header_2.partition_entries_offset = Common::swap64(partition_entries_offset);

  header_2.partition_entries_hash = Common::SHA1::CalculateDigest(partition_entries);

  header_2.number_of_raw_data_entries = Common::swap32(static_cast<u32>(raw_data_entries.size()));
  header_2.raw_data_entries_offset = Common::swap64(raw_data_entries_offset);
  header_2.raw_data_entries_size =
      Common::swap32(static_cast<u32>(compressed_raw_data_entries->size()));

  header_2.number_of_group_entries = Common::swap32(static_cast<u32>(group_entries.size()));
  header_2.group_entries_offset = Common::swap64(group_entries_offset);
  header_2.group_entries_size = Common::swap32(static_cast<u32>(compressed_group_entries->size()));

  header_1.magic = RVZ ? RVZ_MAGIC : WIA_MAGIC;
  header_1.version = Common::swap32(RVZ ? RVZ_VERSION : WIA_VERSION);
  header_1.version_compatible =
      Common::swap32(RVZ ? RVZ_VERSION_WRITE_COMPATIBLE : WIA_VERSION_WRITE_COMPATIBLE);
  header_1.header_2_size = Common::swap32(sizeof(WIAHeader2));
  header_1.header_2_hash =
      Common::SHA1::CalculateDigest(reinterpret_cast<const u8*>(&header_2), sizeof(header_2));
  header_1.iso_file_size = Common::swap64(infile->GetDataSize());
  header_1.wia_file_size = Common::swap64(outfile->GetSize());
  header_1.header_1_hash = Common::SHA1::CalculateDigest(reinterpret_cast<const u8*>(&header_1),
                                                         offsetof(WIAHeader1, header_1_hash));

  if (!outfile->Seek(0, File::SeekOrigin::Begin))
    return ConversionResultCode::WriteFailed;

  if (!outfile->Write(Common::AsU8Span(header_1)))
    return ConversionResultCode::WriteFailed;
  if (!outfile->Write(Common::AsU8Span(header_2)))
    return ConversionResultCode::WriteFailed;

  return ConversionResultCode::Success;
}

bool ConvertToWIAOrRVZ(BlobReader* infile, const std::string& infile_path,
                       const std::string& outfile_path, bool rvz,
                       WIARVZCompressionType compression_type, int compression_level,
                       int chunk_size, const CompressCB& callback)
{
  File::DirectIOFile outfile(outfile_path, File::AccessMode::Write);
  if (!outfile.IsOpen())
  {
    PanicAlertFmtT(
        "Failed to open the output file \"{0}\".\n"
        "Check that you have permissions to write the target folder and that the media can "
        "be written.",
        outfile_path);
    return false;
  }

  std::unique_ptr<VolumeDisc> infile_volume = CreateDisc(infile_path);

  const auto convert = rvz ? RVZFileReader::Convert : WIAFileReader::Convert;
  const ConversionResultCode result =
      convert(infile, infile_volume.get(), &outfile, compression_type, compression_level,
              chunk_size, callback);

  if (result == ConversionResultCode::ReadFailed)
    PanicAlertFmtT("Failed to read from the input file \"{0}\".", infile_path);

  if (result == ConversionResultCode::WriteFailed)
  {
    PanicAlertFmtT("Failed to write the output file \"{0}\".\n"
                   "Check that you have enough space available on the target drive.",
                   outfile_path);
  }

  if (result != ConversionResultCode::Success)
  {
    // Remove the incomplete output file
    outfile.Close();
    File::Delete(outfile_path);
  }

  return result == ConversionResultCode::Success;
}

template class WIARVZFileReader<false>;
template class WIARVZFileReader<true>;

}  // namespace DiscIO