WavLoader.cpp 13 KB

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