WavLoader.cpp 13 KB

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