WavLoader.cpp 13 KB

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