CompressedBlob.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Copyright 2008 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #ifdef _WIN32
  5. #include <io.h>
  6. #include <windows.h>
  7. #endif
  8. #include <algorithm>
  9. #include <cinttypes>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. #include <zlib.h>
  16. #include "Common/CommonTypes.h"
  17. #include "Common/FileUtil.h"
  18. #include "Common/Hash.h"
  19. #include "Common/StringUtil.h"
  20. #include "DiscIO/Blob.h"
  21. #include "DiscIO/CompressedBlob.h"
  22. #include "DiscIO/DiscScrubber.h"
  23. namespace DiscIO
  24. {
  25. CompressedBlobReader::CompressedBlobReader(const std::string& filename) : m_file_name(filename)
  26. {
  27. m_file.Open(filename, "rb");
  28. m_file_size = File::GetSize(filename);
  29. m_file.ReadArray(&m_header, 1);
  30. SetSectorSize(m_header.block_size);
  31. // cache block pointers and hashes
  32. m_block_pointers = new u64[m_header.num_blocks];
  33. m_file.ReadArray(m_block_pointers, m_header.num_blocks);
  34. m_hashes = new u32[m_header.num_blocks];
  35. m_file.ReadArray(m_hashes, m_header.num_blocks);
  36. m_data_offset = (sizeof(CompressedBlobHeader))
  37. + (sizeof(u64)) * m_header.num_blocks // skip block pointers
  38. + (sizeof(u32)) * m_header.num_blocks; // skip hashes
  39. // A compressed block is never ever longer than a decompressed block, so just header.block_size should be fine.
  40. // I still add some safety margin.
  41. m_zlib_buffer_size = m_header.block_size + 64;
  42. m_zlib_buffer = new u8[m_zlib_buffer_size];
  43. memset(m_zlib_buffer, 0, m_zlib_buffer_size);
  44. }
  45. CompressedBlobReader* CompressedBlobReader::Create(const std::string& filename)
  46. {
  47. if (IsCompressedBlob(filename))
  48. return new CompressedBlobReader(filename);
  49. else
  50. return nullptr;
  51. }
  52. CompressedBlobReader::~CompressedBlobReader()
  53. {
  54. delete [] m_zlib_buffer;
  55. delete [] m_block_pointers;
  56. delete [] m_hashes;
  57. }
  58. // IMPORTANT: Calling this function invalidates all earlier pointers gotten from this function.
  59. u64 CompressedBlobReader::GetBlockCompressedSize(u64 block_num) const
  60. {
  61. u64 start = m_block_pointers[block_num];
  62. if (block_num < m_header.num_blocks - 1)
  63. return m_block_pointers[block_num + 1] - start;
  64. else if (block_num == m_header.num_blocks - 1)
  65. return m_header.compressed_data_size - start;
  66. else
  67. PanicAlert("GetBlockCompressedSize - illegal block number %i", (int)block_num);
  68. return 0;
  69. }
  70. void CompressedBlobReader::GetBlock(u64 block_num, u8 *out_ptr)
  71. {
  72. bool uncompressed = false;
  73. u32 comp_block_size = (u32)GetBlockCompressedSize(block_num);
  74. u64 offset = m_block_pointers[block_num] + m_data_offset;
  75. if (offset & (1ULL << 63))
  76. {
  77. if (comp_block_size != m_header.block_size)
  78. PanicAlert("Uncompressed block with wrong size");
  79. uncompressed = true;
  80. offset &= ~(1ULL << 63);
  81. }
  82. // clear unused part of zlib buffer. maybe this can be deleted when it works fully.
  83. memset(m_zlib_buffer + comp_block_size, 0, m_zlib_buffer_size - comp_block_size);
  84. m_file.Seek(offset, SEEK_SET);
  85. m_file.ReadBytes(m_zlib_buffer, comp_block_size);
  86. u8* source = m_zlib_buffer;
  87. u8* dest = out_ptr;
  88. // First, check hash.
  89. u32 block_hash = HashAdler32(source, comp_block_size);
  90. if (block_hash != m_hashes[block_num])
  91. PanicAlertT("The disc image \"%s\" is corrupt.\n"
  92. "Hash of block %" PRIu64 " is %08x instead of %08x.",
  93. m_file_name.c_str(),
  94. block_num, block_hash, m_hashes[block_num]);
  95. if (uncompressed)
  96. {
  97. memcpy(dest, source, comp_block_size);
  98. }
  99. else
  100. {
  101. z_stream z;
  102. memset(&z, 0, sizeof(z));
  103. z.next_in = source;
  104. z.avail_in = comp_block_size;
  105. if (z.avail_in > m_header.block_size)
  106. {
  107. PanicAlert("We have a problem");
  108. }
  109. z.next_out = dest;
  110. z.avail_out = m_header.block_size;
  111. inflateInit(&z);
  112. int status = inflate(&z, Z_FULL_FLUSH);
  113. u32 uncomp_size = m_header.block_size - z.avail_out;
  114. if (status != Z_STREAM_END)
  115. {
  116. // this seem to fire wrongly from time to time
  117. // to be sure, don't use compressed isos :P
  118. PanicAlert("Failure reading block %" PRIu64 " - out of data and not at end.", block_num);
  119. }
  120. inflateEnd(&z);
  121. if (uncomp_size != m_header.block_size)
  122. PanicAlert("Wrong block size");
  123. }
  124. }
  125. bool CompressFileToBlob(const std::string& infile, const std::string& outfile, u32 sub_type,
  126. int block_size, CompressCB callback, void* arg)
  127. {
  128. bool scrubbing = false;
  129. if (IsCompressedBlob(infile))
  130. {
  131. PanicAlertT("\"%s\" is already compressed! Cannot compress it further.", infile.c_str());
  132. return false;
  133. }
  134. File::IOFile inf(infile, "rb");
  135. if (!inf)
  136. {
  137. PanicAlertT("Failed to open the input file \"%s\".", infile.c_str());
  138. return false;
  139. }
  140. File::IOFile f(outfile, "wb");
  141. if (!f)
  142. {
  143. PanicAlertT("Failed to open the output file \"%s\".\n"
  144. "Check that you have permissions to write the target folder and that the media can be written.",
  145. outfile.c_str());
  146. return false;
  147. }
  148. if (sub_type == 1)
  149. {
  150. if (!DiscScrubber::SetupScrub(infile, block_size))
  151. {
  152. PanicAlertT("\"%s\" failed to be scrubbed. Probably the image is corrupt.", infile.c_str());
  153. return false;
  154. }
  155. scrubbing = true;
  156. }
  157. z_stream z = {};
  158. if (deflateInit(&z, 9) != Z_OK)
  159. {
  160. DiscScrubber::Cleanup();
  161. return false;
  162. }
  163. callback("Files opened, ready to compress.", 0, arg);
  164. CompressedBlobHeader header;
  165. header.magic_cookie = kBlobCookie;
  166. header.sub_type = sub_type;
  167. header.block_size = block_size;
  168. header.data_size = File::GetSize(infile);
  169. // round upwards!
  170. header.num_blocks = (u32)((header.data_size + (block_size - 1)) / block_size);
  171. u64* offsets = new u64[header.num_blocks];
  172. u32* hashes = new u32[header.num_blocks];
  173. u8* out_buf = new u8[block_size];
  174. u8* in_buf = new u8[block_size];
  175. // seek past the header (we will write it at the end)
  176. f.Seek(sizeof(CompressedBlobHeader), SEEK_CUR);
  177. // seek past the offset and hash tables (we will write them at the end)
  178. f.Seek((sizeof(u64) + sizeof(u32)) * header.num_blocks, SEEK_CUR);
  179. // Now we are ready to write compressed data!
  180. u64 position = 0;
  181. int num_compressed = 0;
  182. int num_stored = 0;
  183. int progress_monitor = std::max<int>(1, header.num_blocks / 1000);
  184. bool success = true;
  185. for (u32 i = 0; i < header.num_blocks; i++)
  186. {
  187. if (i % progress_monitor == 0)
  188. {
  189. const u64 inpos = inf.Tell();
  190. int ratio = 0;
  191. if (inpos != 0)
  192. ratio = (int)(100 * position / inpos);
  193. std::string temp = StringFromFormat("%i of %i blocks. Compression ratio %i%%", i, header.num_blocks, ratio);
  194. bool was_cancelled = !callback(temp, (float)i / (float)header.num_blocks, arg);
  195. if (was_cancelled)
  196. {
  197. success = false;
  198. break;
  199. }
  200. }
  201. offsets[i] = position;
  202. size_t read_bytes;
  203. if (scrubbing)
  204. read_bytes = DiscScrubber::GetNextBlock(inf, in_buf);
  205. else
  206. inf.ReadArray(in_buf, header.block_size, &read_bytes);
  207. if (read_bytes < header.block_size)
  208. std::fill(in_buf + read_bytes, in_buf + header.block_size, 0);
  209. int retval = deflateReset(&z);
  210. z.next_in = in_buf;
  211. z.avail_in = header.block_size;
  212. z.next_out = out_buf;
  213. z.avail_out = block_size;
  214. if (retval != Z_OK)
  215. {
  216. ERROR_LOG(DISCIO, "Deflate failed");
  217. success = false;
  218. break;
  219. }
  220. int status = deflate(&z, Z_FINISH);
  221. int comp_size = block_size - z.avail_out;
  222. u8* write_buf;
  223. int write_size;
  224. if ((status != Z_STREAM_END) || (z.avail_out < 10))
  225. {
  226. //PanicAlert("%i %i Store %i", i*block_size, position, comp_size);
  227. // let's store uncompressed
  228. write_buf = in_buf;
  229. offsets[i] |= 0x8000000000000000ULL;
  230. write_size = block_size;
  231. num_stored++;
  232. }
  233. else
  234. {
  235. // let's store compressed
  236. //PanicAlert("Comp %i to %i", block_size, comp_size);
  237. write_buf = out_buf;
  238. write_size = comp_size;
  239. num_compressed++;
  240. }
  241. if (!f.WriteBytes(write_buf, write_size))
  242. {
  243. PanicAlertT(
  244. "Failed to write the output file \"%s\".\n"
  245. "Check that you have enough space available on the target drive.",
  246. outfile.c_str());
  247. success = false;
  248. break;
  249. }
  250. position += write_size;
  251. hashes[i] = HashAdler32(write_buf, write_size);
  252. }
  253. header.compressed_data_size = position;
  254. if (!success)
  255. {
  256. // Remove the incomplete output file.
  257. f.Close();
  258. File::Delete(outfile);
  259. }
  260. else
  261. {
  262. // Okay, go back and fill in headers
  263. f.Seek(0, SEEK_SET);
  264. f.WriteArray(&header, 1);
  265. f.WriteArray(offsets, header.num_blocks);
  266. f.WriteArray(hashes, header.num_blocks);
  267. }
  268. // Cleanup
  269. delete[] in_buf;
  270. delete[] out_buf;
  271. delete[] offsets;
  272. delete[] hashes;
  273. deflateEnd(&z);
  274. DiscScrubber::Cleanup();
  275. if (success)
  276. {
  277. callback("Done compressing disc image.", 1.0f, arg);
  278. }
  279. return success;
  280. }
  281. bool DecompressBlobToFile(const std::string& infile, const std::string& outfile, CompressCB callback, void* arg)
  282. {
  283. if (!IsCompressedBlob(infile))
  284. {
  285. PanicAlertT("File not compressed");
  286. return false;
  287. }
  288. std::unique_ptr<CompressedBlobReader> reader(CompressedBlobReader::Create(infile));
  289. if (!reader)
  290. {
  291. PanicAlertT("Failed to open the input file \"%s\".", infile.c_str());
  292. return false;
  293. }
  294. File::IOFile f(outfile, "wb");
  295. if (!f)
  296. {
  297. PanicAlertT(
  298. "Failed to open the output file \"%s\".\n"
  299. "Check that you have permissions to write the target folder and that the media can be written.",
  300. outfile.c_str());
  301. return false;
  302. }
  303. const CompressedBlobHeader &header = reader->GetHeader();
  304. static const size_t BUFFER_BLOCKS = 32;
  305. size_t buffer_size = header.block_size * BUFFER_BLOCKS;
  306. size_t last_buffer_size = header.block_size * (header.num_blocks % BUFFER_BLOCKS);
  307. std::vector<u8> buffer(buffer_size);
  308. u32 num_buffers = (header.num_blocks + BUFFER_BLOCKS - 1) / BUFFER_BLOCKS;
  309. int progress_monitor = std::max<int>(1, num_buffers / 100);
  310. bool success = true;
  311. for (u64 i = 0; i < num_buffers; i++)
  312. {
  313. if (i % progress_monitor == 0)
  314. {
  315. bool was_cancelled = !callback("Unpacking", (float)i / (float)num_buffers, arg);
  316. if (was_cancelled)
  317. {
  318. success = false;
  319. break;
  320. }
  321. }
  322. const size_t sz = i == num_buffers - 1 ? last_buffer_size : buffer_size;
  323. reader->Read(i * buffer_size, sz, buffer.data());
  324. if (!f.WriteBytes(buffer.data(), sz))
  325. {
  326. PanicAlertT(
  327. "Failed to write the output file \"%s\".\n"
  328. "Check that you have enough space available on the target drive.",
  329. outfile.c_str());
  330. success = false;
  331. break;
  332. }
  333. }
  334. if (!success)
  335. {
  336. // Remove the incomplete output file.
  337. f.Close();
  338. File::Delete(outfile);
  339. }
  340. else
  341. {
  342. f.Resize(header.data_size);
  343. }
  344. return true;
  345. }
  346. bool IsCompressedBlob(const std::string& filename)
  347. {
  348. File::IOFile f(filename, "rb");
  349. CompressedBlobHeader header;
  350. return f.ReadArray(&header, 1) && (header.magic_cookie == kBlobCookie);
  351. }
  352. } // namespace