WavLoader.cpp 10 KB

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