WavLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 "LoaderError.h"
  9. #include <AK/Debug.h>
  10. #include <AK/Endian.h>
  11. #include <AK/FixedArray.h>
  12. #include <AK/NumericLimits.h>
  13. #include <AK/Try.h>
  14. #include <LibCore/MemoryStream.h>
  15. namespace Audio {
  16. static constexpr size_t const 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. }
  21. MaybeLoaderError WavLoaderPlugin::initialize()
  22. {
  23. if (m_backing_memory.has_value())
  24. m_stream = LOADER_TRY(Core::Stream::MemoryStream::construct(m_backing_memory.value()));
  25. else
  26. m_stream = LOADER_TRY(Core::Stream::File::open(m_file->filename(), Core::Stream::OpenMode::Read));
  27. TRY(parse_header());
  28. return {};
  29. }
  30. WavLoaderPlugin::WavLoaderPlugin(Bytes const& buffer)
  31. : m_backing_memory(buffer)
  32. {
  33. }
  34. template<typename SampleReader>
  35. MaybeLoaderError WavLoaderPlugin::read_samples_from_stream(Core::Stream::Stream& stream, SampleReader read_sample, FixedArray<Sample>& samples) const
  36. {
  37. switch (m_num_channels) {
  38. case 1:
  39. for (auto& sample : samples)
  40. sample = Sample(LOADER_TRY(read_sample(stream)));
  41. break;
  42. case 2:
  43. for (auto& sample : samples) {
  44. auto left_channel_sample = LOADER_TRY(read_sample(stream));
  45. auto right_channel_sample = LOADER_TRY(read_sample(stream));
  46. sample = Sample(left_channel_sample, right_channel_sample);
  47. }
  48. break;
  49. default:
  50. VERIFY_NOT_REACHED();
  51. }
  52. return {};
  53. }
  54. // There's no i24 type + we need to do the endianness conversion manually anyways.
  55. static ErrorOr<double> read_sample_int24(Core::Stream::Stream& stream)
  56. {
  57. u8 byte = 0;
  58. TRY(stream.read(Bytes { &byte, 1 }));
  59. i32 sample1 = byte;
  60. TRY(stream.read(Bytes { &byte, 1 }));
  61. i32 sample2 = byte;
  62. TRY(stream.read(Bytes { &byte, 1 }));
  63. i32 sample3 = byte;
  64. i32 value = 0;
  65. value = sample1 << 8;
  66. value |= sample2 << 16;
  67. value |= sample3 << 24;
  68. return static_cast<double>(value) / static_cast<double>((1 << 24) - 1);
  69. }
  70. template<typename T>
  71. static ErrorOr<double> read_sample(Core::Stream::Stream& stream)
  72. {
  73. T sample { 0 };
  74. TRY(stream.read(Bytes { &sample, sizeof(T) }));
  75. // Remap integer samples to normalized floating-point range of -1 to 1.
  76. if constexpr (IsIntegral<T>) {
  77. if constexpr (NumericLimits<T>::is_signed()) {
  78. // Signed integer samples are centered around zero, so this division is enough.
  79. return static_cast<double>(AK::convert_between_host_and_little_endian(sample)) / static_cast<double>(NumericLimits<T>::max());
  80. } else {
  81. // Unsigned integer samples, on the other hand, need to be shifted to center them around zero.
  82. // The first division therefore remaps to the range 0 to 2.
  83. return static_cast<double>(AK::convert_between_host_and_little_endian(sample)) / (static_cast<double>(NumericLimits<T>::max()) / 2.0) - 1.0;
  84. }
  85. } else {
  86. return static_cast<double>(AK::convert_between_host_and_little_endian(sample));
  87. }
  88. }
  89. LoaderSamples WavLoaderPlugin::samples_from_pcm_data(Bytes const& data, size_t samples_to_read) const
  90. {
  91. FixedArray<Sample> samples = LOADER_TRY(FixedArray<Sample>::try_create(samples_to_read));
  92. auto stream = LOADER_TRY(Core::Stream::MemoryStream::construct(move(data)));
  93. switch (m_sample_format) {
  94. case PcmSampleFormat::Uint8:
  95. TRY(read_samples_from_stream(*stream, read_sample<u8>, samples));
  96. break;
  97. case PcmSampleFormat::Int16:
  98. TRY(read_samples_from_stream(*stream, read_sample<i16>, samples));
  99. break;
  100. case PcmSampleFormat::Int24:
  101. TRY(read_samples_from_stream(*stream, read_sample_int24, samples));
  102. break;
  103. case PcmSampleFormat::Float32:
  104. TRY(read_samples_from_stream(*stream, read_sample<float>, samples));
  105. break;
  106. case PcmSampleFormat::Float64:
  107. TRY(read_samples_from_stream(*stream, read_sample<double>, samples));
  108. break;
  109. default:
  110. VERIFY_NOT_REACHED();
  111. }
  112. return samples;
  113. }
  114. LoaderSamples WavLoaderPlugin::get_more_samples(size_t max_samples_to_read_from_input)
  115. {
  116. if (!m_stream)
  117. return LoaderError { LoaderError::Category::Internal, static_cast<size_t>(m_loaded_samples), "No stream; initialization failed" };
  118. auto remaining_samples = m_total_samples - m_loaded_samples;
  119. if (remaining_samples <= 0)
  120. return FixedArray<Sample> {};
  121. // One "sample" contains data from all channels.
  122. // In the Wave spec, this is also called a block.
  123. size_t bytes_per_sample
  124. = m_num_channels * pcm_bits_per_sample(m_sample_format) / 8;
  125. // Might truncate if not evenly divisible by the sample size
  126. auto max_samples_to_read = max_samples_to_read_from_input / bytes_per_sample;
  127. auto samples_to_read = min(max_samples_to_read, remaining_samples);
  128. auto bytes_to_read = samples_to_read * bytes_per_sample;
  129. dbgln_if(AWAVLOADER_DEBUG, "Read {} bytes WAV with num_channels {} sample rate {}, "
  130. "bits per sample {}, sample format {}",
  131. bytes_to_read, m_num_channels, m_sample_rate,
  132. pcm_bits_per_sample(m_sample_format), sample_format_name(m_sample_format));
  133. auto sample_data = LOADER_TRY(ByteBuffer::create_zeroed(bytes_to_read));
  134. LOADER_TRY(m_stream->read(sample_data.bytes()));
  135. // m_loaded_samples should contain the amount of actually loaded samples
  136. m_loaded_samples += samples_to_read;
  137. return samples_from_pcm_data(sample_data.bytes(), samples_to_read);
  138. }
  139. MaybeLoaderError WavLoaderPlugin::seek(int sample_index)
  140. {
  141. dbgln_if(AWAVLOADER_DEBUG, "seek sample_index {}", sample_index);
  142. if (sample_index < 0 || sample_index >= static_cast<int>(m_total_samples))
  143. return LoaderError { LoaderError::Category::Internal, m_loaded_samples, "Seek outside the sample range" };
  144. size_t sample_offset = m_byte_offset_of_data_samples + static_cast<size_t>(sample_index * m_num_channels * (pcm_bits_per_sample(m_sample_format) / 8));
  145. LOADER_TRY(m_stream->seek(sample_offset, Core::Stream::SeekMode::SetPosition));
  146. m_loaded_samples = sample_index;
  147. return {};
  148. }
  149. // Specification reference: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  150. MaybeLoaderError WavLoaderPlugin::parse_header()
  151. {
  152. if (!m_stream)
  153. return LoaderError { LoaderError::Category::Internal, 0, "No stream" };
  154. bool ok = true;
  155. size_t bytes_read = 0;
  156. auto read_u8 = [&]() -> ErrorOr<u8, LoaderError> {
  157. u8 value;
  158. LOADER_TRY(m_stream->read(Bytes { &value, 1 }));
  159. bytes_read += 1;
  160. return value;
  161. };
  162. auto read_u16 = [&]() -> ErrorOr<u16, LoaderError> {
  163. u16 value;
  164. LOADER_TRY(m_stream->read(Bytes { &value, 2 }));
  165. bytes_read += 2;
  166. return value;
  167. };
  168. auto read_u32 = [&]() -> ErrorOr<u32, LoaderError> {
  169. u32 value;
  170. LOADER_TRY(m_stream->read(Bytes { &value, 4 }));
  171. bytes_read += 4;
  172. return value;
  173. };
  174. #define CHECK_OK(category, msg) \
  175. do { \
  176. if (!ok) \
  177. return LoaderError { category, String::formatted("Parsing failed: {}", msg) }; \
  178. } while (0)
  179. u32 riff = TRY(read_u32());
  180. ok = ok && riff == 0x46464952; // "RIFF"
  181. CHECK_OK(LoaderError::Category::Format, "RIFF header");
  182. u32 sz = TRY(read_u32());
  183. ok = ok && sz < maximum_wav_size;
  184. CHECK_OK(LoaderError::Category::Format, "File size");
  185. u32 wave = TRY(read_u32());
  186. ok = ok && wave == 0x45564157; // "WAVE"
  187. CHECK_OK(LoaderError::Category::Format, "WAVE header");
  188. u32 fmt_id = TRY(read_u32());
  189. ok = ok && fmt_id == 0x20746D66; // "fmt "
  190. CHECK_OK(LoaderError::Category::Format, "FMT header");
  191. u32 fmt_size = TRY(read_u32());
  192. ok = ok && (fmt_size == 16 || fmt_size == 18 || fmt_size == 40);
  193. CHECK_OK(LoaderError::Category::Format, "FMT size");
  194. u16 audio_format = TRY(read_u16());
  195. CHECK_OK(LoaderError::Category::Format, "Audio format"); // incomplete read check
  196. ok = ok && (audio_format == WAVE_FORMAT_PCM || audio_format == WAVE_FORMAT_IEEE_FLOAT || audio_format == WAVE_FORMAT_EXTENSIBLE);
  197. CHECK_OK(LoaderError::Category::Unimplemented, "Audio format PCM/Float"); // value check
  198. m_num_channels = TRY(read_u16());
  199. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  200. CHECK_OK(LoaderError::Category::Unimplemented, "Channel count");
  201. m_sample_rate = TRY(read_u32());
  202. CHECK_OK(LoaderError::Category::IO, "Sample rate");
  203. TRY(read_u32());
  204. CHECK_OK(LoaderError::Category::IO, "Data rate");
  205. u16 block_size_bytes = TRY(read_u16());
  206. CHECK_OK(LoaderError::Category::IO, "Block size");
  207. u16 bits_per_sample = TRY(read_u16());
  208. CHECK_OK(LoaderError::Category::IO, "Bits per sample");
  209. if (audio_format == WAVE_FORMAT_EXTENSIBLE) {
  210. ok = ok && (fmt_size == 40);
  211. CHECK_OK(LoaderError::Category::Format, "Extensible fmt size"); // value check
  212. // Discard everything until the GUID.
  213. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  214. TRY(read_u32());
  215. TRY(read_u32());
  216. CHECK_OK(LoaderError::Category::IO, "Discard until GUID");
  217. // Get the underlying audio format from the first two bytes of GUID
  218. u16 guid_subformat = TRY(read_u16());
  219. ok = ok && (guid_subformat == WAVE_FORMAT_PCM || guid_subformat == WAVE_FORMAT_IEEE_FLOAT);
  220. CHECK_OK(LoaderError::Category::Unimplemented, "GUID SubFormat");
  221. audio_format = guid_subformat;
  222. }
  223. if (audio_format == WAVE_FORMAT_PCM) {
  224. ok = ok && (bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24);
  225. CHECK_OK(LoaderError::Category::Unimplemented, "Bits per sample (PCM)"); // value check
  226. // We only support 8-24 bit audio right now because other formats are uncommon
  227. if (bits_per_sample == 8) {
  228. m_sample_format = PcmSampleFormat::Uint8;
  229. } else if (bits_per_sample == 16) {
  230. m_sample_format = PcmSampleFormat::Int16;
  231. } else if (bits_per_sample == 24) {
  232. m_sample_format = PcmSampleFormat::Int24;
  233. }
  234. } else if (audio_format == WAVE_FORMAT_IEEE_FLOAT) {
  235. ok = ok && (bits_per_sample == 32 || bits_per_sample == 64);
  236. CHECK_OK(LoaderError::Category::Unimplemented, "Bits per sample (Float)"); // value check
  237. // Again, only the common 32 and 64 bit
  238. if (bits_per_sample == 32) {
  239. m_sample_format = PcmSampleFormat::Float32;
  240. } else if (bits_per_sample == 64) {
  241. m_sample_format = PcmSampleFormat::Float64;
  242. }
  243. }
  244. ok = ok && (block_size_bytes == (m_num_channels * (bits_per_sample / 8)));
  245. CHECK_OK(LoaderError::Category::Format, "Block size sanity check");
  246. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  247. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  248. // Read chunks until we find DATA
  249. bool found_data = false;
  250. u32 data_size = 0;
  251. u8 search_byte = 0;
  252. while (true) {
  253. search_byte = TRY(read_u8());
  254. CHECK_OK(LoaderError::Category::IO, "Reading byte searching for data");
  255. if (search_byte != 0x64) // D
  256. continue;
  257. search_byte = TRY(read_u8());
  258. CHECK_OK(LoaderError::Category::IO, "Reading next byte searching for data");
  259. if (search_byte != 0x61) // A
  260. continue;
  261. u16 search_remaining = TRY(read_u16());
  262. CHECK_OK(LoaderError::Category::IO, "Reading remaining bytes searching for data");
  263. if (search_remaining != 0x6174) // TA
  264. continue;
  265. data_size = TRY(read_u32());
  266. found_data = true;
  267. break;
  268. }
  269. ok = ok && found_data;
  270. CHECK_OK(LoaderError::Category::Format, "Found no data chunk");
  271. ok = ok && data_size < maximum_wav_size;
  272. CHECK_OK(LoaderError::Category::Format, "Data was too large");
  273. m_total_samples = data_size / block_size_bytes;
  274. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  275. data_size,
  276. block_size_bytes,
  277. m_total_samples);
  278. m_byte_offset_of_data_samples = bytes_read;
  279. return {};
  280. }
  281. }