CISOBlob.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2010 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "DiscIO/CISOBlob.h"
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <memory>
  7. #include <utility>
  8. #include "Common/CommonTypes.h"
  9. #include "Common/IOFile.h"
  10. namespace DiscIO
  11. {
  12. CISOFileReader::CISOFileReader(File::IOFile file) : m_file(std::move(file))
  13. {
  14. m_size = m_file.GetSize();
  15. CISOHeader header;
  16. m_file.Seek(0, File::SeekOrigin::Begin);
  17. m_file.ReadArray(&header, 1);
  18. m_block_size = header.block_size;
  19. MapType count = 0;
  20. for (u32 idx = 0; idx < CISO_MAP_SIZE; ++idx)
  21. m_ciso_map[idx] = (1 == header.map[idx]) ? count++ : UNUSED_BLOCK_ID;
  22. }
  23. std::unique_ptr<CISOFileReader> CISOFileReader::Create(File::IOFile file)
  24. {
  25. CISOHeader header;
  26. if (file.Seek(0, File::SeekOrigin::Begin) && file.ReadArray(&header, 1) &&
  27. header.magic == CISO_MAGIC)
  28. {
  29. return std::unique_ptr<CISOFileReader>(new CISOFileReader(std::move(file)));
  30. }
  31. return nullptr;
  32. }
  33. std::unique_ptr<BlobReader> CISOFileReader::CopyReader() const
  34. {
  35. return Create(m_file.Duplicate("rb"));
  36. }
  37. u64 CISOFileReader::GetDataSize() const
  38. {
  39. return static_cast<u64>(CISO_MAP_SIZE) * m_block_size;
  40. }
  41. u64 CISOFileReader::GetRawSize() const
  42. {
  43. return m_size;
  44. }
  45. bool CISOFileReader::Read(u64 offset, u64 nbytes, u8* out_ptr)
  46. {
  47. if (offset + nbytes > GetDataSize())
  48. return false;
  49. while (nbytes != 0)
  50. {
  51. u64 const block = offset / m_block_size;
  52. u64 const data_offset = offset % m_block_size;
  53. u64 const bytes_to_read = std::min(m_block_size - data_offset, nbytes);
  54. if (block < CISO_MAP_SIZE && UNUSED_BLOCK_ID != m_ciso_map[block])
  55. {
  56. // calculate the base address
  57. u64 const file_off = CISO_HEADER_SIZE + m_ciso_map[block] * (u64)m_block_size + data_offset;
  58. if (!(m_file.Seek(file_off, File::SeekOrigin::Begin) &&
  59. m_file.ReadArray(out_ptr, bytes_to_read)))
  60. {
  61. m_file.ClearError();
  62. return false;
  63. }
  64. }
  65. else
  66. {
  67. std::fill_n(out_ptr, bytes_to_read, 0);
  68. }
  69. out_ptr += bytes_to_read;
  70. offset += bytes_to_read;
  71. nbytes -= bytes_to_read;
  72. }
  73. return true;
  74. }
  75. } // namespace DiscIO