WavLoader.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "WavLoader.h"
  8. #include "Buffer.h"
  9. #include <AK/Debug.h>
  10. #include <AK/FixedArray.h>
  11. #include <AK/NumericLimits.h>
  12. #include <AK/OwnPtr.h>
  13. #include <AK/Try.h>
  14. #include <LibCore/File.h>
  15. #include <LibCore/FileStream.h>
  16. namespace Audio {
  17. static constexpr size_t maximum_wav_size = 1 * GiB; // FIXME: is there a more appropriate size limit?
  18. WavLoaderPlugin::WavLoaderPlugin(StringView path)
  19. : m_file(Core::File::construct(path))
  20. {
  21. if (!m_file->open(Core::OpenMode::ReadOnly)) {
  22. m_error = LoaderError { String::formatted("Can't open file: {}", m_file->error_string()) };
  23. return;
  24. }
  25. m_stream = make<Core::InputFileStream>(*m_file);
  26. }
  27. MaybeLoaderError WavLoaderPlugin::initialize()
  28. {
  29. if (m_error.has_value())
  30. return m_error.release_value();
  31. TRY(parse_header());
  32. return {};
  33. }
  34. WavLoaderPlugin::WavLoaderPlugin(Bytes const& buffer)
  35. {
  36. m_stream = make<InputMemoryStream>(buffer);
  37. if (!m_stream) {
  38. m_error = LoaderError { String::formatted("Can't open memory stream") };
  39. return;
  40. }
  41. m_memory_stream = static_cast<InputMemoryStream*>(m_stream.ptr());
  42. }
  43. LoaderSamples WavLoaderPlugin::get_more_samples(size_t max_bytes_to_read_from_input)
  44. {
  45. if (!m_stream)
  46. return LoaderError { LoaderError::Category::Internal, static_cast<size_t>(m_loaded_samples), "No stream" };
  47. int remaining_samples = m_total_samples - m_loaded_samples;
  48. if (remaining_samples <= 0)
  49. return FixedArray<Sample> {};
  50. // One "sample" contains data from all channels.
  51. // In the Wave spec, this is also called a block.
  52. size_t bytes_per_sample
  53. = m_num_channels * pcm_bits_per_sample(m_sample_format) / 8;
  54. // Might truncate if not evenly divisible by the sample size
  55. int max_samples_to_read = static_cast<int>(max_bytes_to_read_from_input) / bytes_per_sample;
  56. int samples_to_read = min(max_samples_to_read, remaining_samples);
  57. size_t bytes_to_read = samples_to_read * bytes_per_sample;
  58. dbgln_if(AWAVLOADER_DEBUG, "Read {} bytes WAV with num_channels {} sample rate {}, "
  59. "bits per sample {}, sample format {}",
  60. bytes_to_read, m_num_channels, m_sample_rate,
  61. pcm_bits_per_sample(m_sample_format), sample_format_name(m_sample_format));
  62. auto sample_data_result = ByteBuffer::create_zeroed(bytes_to_read);
  63. if (sample_data_result.is_error())
  64. return LoaderError { LoaderError::Category::IO, static_cast<size_t>(m_loaded_samples), "Couldn't allocate sample buffer" };
  65. auto sample_data = sample_data_result.release_value();
  66. m_stream->read_or_error(sample_data.bytes());
  67. if (m_stream->handle_any_error())
  68. return LoaderError { LoaderError::Category::IO, static_cast<size_t>(m_loaded_samples), "Stream read error" };
  69. auto buffer = LegacyBuffer::from_pcm_data(
  70. sample_data.bytes(),
  71. m_num_channels,
  72. m_sample_format);
  73. if (buffer.is_error())
  74. return LoaderError { LoaderError::Category::Internal, static_cast<size_t>(m_loaded_samples), "Couldn't allocate sample buffer" };
  75. // m_loaded_samples should contain the amount of actually loaded samples
  76. m_loaded_samples += samples_to_read;
  77. return LOADER_TRY(buffer.value()->to_sample_array());
  78. }
  79. MaybeLoaderError WavLoaderPlugin::seek(int const sample_index)
  80. {
  81. dbgln_if(AWAVLOADER_DEBUG, "seek sample_index {}", sample_index);
  82. if (sample_index < 0 || sample_index >= m_total_samples)
  83. return LoaderError { LoaderError::Category::Internal, static_cast<size_t>(m_loaded_samples), "Seek outside the sample range" };
  84. size_t sample_offset = m_byte_offset_of_data_samples + (sample_index * m_num_channels * (pcm_bits_per_sample(m_sample_format) / 8));
  85. // AK::InputStream does not define seek, hence the special-cases for file and stream.
  86. if (m_file) {
  87. m_file->seek(sample_offset);
  88. } else {
  89. m_memory_stream->seek(sample_offset);
  90. }
  91. m_loaded_samples = sample_index;
  92. return {};
  93. }
  94. // Specification reference: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  95. MaybeLoaderError WavLoaderPlugin::parse_header()
  96. {
  97. if (!m_stream)
  98. return LoaderError { LoaderError::Category::Internal, 0, "No stream" };
  99. bool ok = true;
  100. size_t bytes_read = 0;
  101. auto read_u8 = [&]() -> u8 {
  102. u8 value;
  103. *m_stream >> value;
  104. if (m_stream->handle_any_error())
  105. ok = false;
  106. bytes_read += 1;
  107. return value;
  108. };
  109. auto read_u16 = [&]() -> u16 {
  110. u16 value;
  111. *m_stream >> value;
  112. if (m_stream->handle_any_error())
  113. ok = false;
  114. bytes_read += 2;
  115. return value;
  116. };
  117. auto read_u32 = [&]() -> u32 {
  118. u32 value;
  119. *m_stream >> value;
  120. if (m_stream->handle_any_error())
  121. ok = false;
  122. bytes_read += 4;
  123. return value;
  124. };
  125. #define CHECK_OK(category, msg) \
  126. do { \
  127. if (!ok) \
  128. return LoaderError { category, String::formatted("Parsing failed: {}", msg) }; \
  129. } while (0)
  130. u32 riff = read_u32();
  131. ok = ok && riff == 0x46464952; // "RIFF"
  132. CHECK_OK(LoaderError::Category::Format, "RIFF header");
  133. u32 sz = read_u32();
  134. ok = ok && sz < maximum_wav_size;
  135. CHECK_OK(LoaderError::Category::Format, "File size");
  136. u32 wave = read_u32();
  137. ok = ok && wave == 0x45564157; // "WAVE"
  138. CHECK_OK(LoaderError::Category::Format, "WAVE header");
  139. u32 fmt_id = read_u32();
  140. ok = ok && fmt_id == 0x20746D66; // "fmt "
  141. CHECK_OK(LoaderError::Category::Format, "FMT header");
  142. u32 fmt_size = read_u32();
  143. ok = ok && (fmt_size == 16 || fmt_size == 18 || fmt_size == 40);
  144. CHECK_OK(LoaderError::Category::Format, "FMT size");
  145. u16 audio_format = read_u16();
  146. CHECK_OK(LoaderError::Category::Format, "Audio format"); // incomplete read check
  147. ok = ok && (audio_format == WAVE_FORMAT_PCM || audio_format == WAVE_FORMAT_IEEE_FLOAT || audio_format == WAVE_FORMAT_EXTENSIBLE);
  148. CHECK_OK(LoaderError::Category::Unimplemented, "Audio format PCM/Float"); // value check
  149. m_num_channels = read_u16();
  150. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  151. CHECK_OK(LoaderError::Category::Unimplemented, "Channel count");
  152. m_sample_rate = read_u32();
  153. CHECK_OK(LoaderError::Category::IO, "Sample rate");
  154. read_u32();
  155. CHECK_OK(LoaderError::Category::IO, "Data rate");
  156. u16 block_size_bytes = read_u16();
  157. CHECK_OK(LoaderError::Category::IO, "Block size");
  158. u16 bits_per_sample = read_u16();
  159. CHECK_OK(LoaderError::Category::IO, "Bits per sample");
  160. if (audio_format == WAVE_FORMAT_EXTENSIBLE) {
  161. ok = ok && (fmt_size == 40);
  162. CHECK_OK(LoaderError::Category::Format, "Extensible fmt size"); // value check
  163. // Discard everything until the GUID.
  164. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  165. read_u32();
  166. read_u32();
  167. CHECK_OK(LoaderError::Category::IO, "Discard until GUID");
  168. // Get the underlying audio format from the first two bytes of GUID
  169. u16 guid_subformat = read_u16();
  170. ok = ok && (guid_subformat == WAVE_FORMAT_PCM || guid_subformat == WAVE_FORMAT_IEEE_FLOAT);
  171. CHECK_OK(LoaderError::Category::Unimplemented, "GUID SubFormat");
  172. audio_format = guid_subformat;
  173. }
  174. if (audio_format == WAVE_FORMAT_PCM) {
  175. ok = ok && (bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24);
  176. CHECK_OK(LoaderError::Category::Unimplemented, "Bits per sample (PCM)"); // value check
  177. // We only support 8-24 bit audio right now because other formats are uncommon
  178. if (bits_per_sample == 8) {
  179. m_sample_format = PcmSampleFormat::Uint8;
  180. } else if (bits_per_sample == 16) {
  181. m_sample_format = PcmSampleFormat::Int16;
  182. } else if (bits_per_sample == 24) {
  183. m_sample_format = PcmSampleFormat::Int24;
  184. }
  185. } else if (audio_format == WAVE_FORMAT_IEEE_FLOAT) {
  186. ok = ok && (bits_per_sample == 32 || bits_per_sample == 64);
  187. CHECK_OK(LoaderError::Category::Unimplemented, "Bits per sample (Float)"); // value check
  188. // Again, only the common 32 and 64 bit
  189. if (bits_per_sample == 32) {
  190. m_sample_format = PcmSampleFormat::Float32;
  191. } else if (bits_per_sample == 64) {
  192. m_sample_format = PcmSampleFormat::Float64;
  193. }
  194. }
  195. ok = ok && (block_size_bytes == (m_num_channels * (bits_per_sample / 8)));
  196. CHECK_OK(LoaderError::Category::Format, "Block size sanity check");
  197. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  198. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  199. // Read chunks until we find DATA
  200. bool found_data = false;
  201. u32 data_sz = 0;
  202. u8 search_byte = 0;
  203. while (true) {
  204. search_byte = read_u8();
  205. CHECK_OK(LoaderError::Category::IO, "Reading byte searching for data");
  206. if (search_byte != 0x64) // D
  207. continue;
  208. search_byte = read_u8();
  209. CHECK_OK(LoaderError::Category::IO, "Reading next byte searching for data");
  210. if (search_byte != 0x61) // A
  211. continue;
  212. u16 search_remaining = read_u16();
  213. CHECK_OK(LoaderError::Category::IO, "Reading remaining bytes searching for data");
  214. if (search_remaining != 0x6174) // TA
  215. continue;
  216. data_sz = read_u32();
  217. found_data = true;
  218. break;
  219. }
  220. ok = ok && found_data;
  221. CHECK_OK(LoaderError::Category::Format, "Found no data chunk");
  222. ok = ok && data_sz < maximum_wav_size;
  223. CHECK_OK(LoaderError::Category::Format, "Data was too large");
  224. m_total_samples = data_sz / block_size_bytes;
  225. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  226. data_sz,
  227. block_size_bytes,
  228. m_total_samples);
  229. m_byte_offset_of_data_samples = bytes_read;
  230. return {};
  231. }
  232. }