WavLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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(OwnPtr<Core::Stream::SeekableStream> stream)
  18. : LoaderPlugin(move(stream))
  19. {
  20. }
  21. Result<NonnullOwnPtr<WavLoaderPlugin>, LoaderError> WavLoaderPlugin::try_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::try_create(Bytes buffer)
  29. {
  30. auto stream = LOADER_TRY(Core::Stream::MemoryStream::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>::try_create(samples_to_read));
  101. auto stream = LOADER_TRY(Core::Stream::MemoryStream::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. if (!m_stream)
  126. return LoaderError { LoaderError::Category::Internal, static_cast<size_t>(m_loaded_samples), "No stream; initialization failed" };
  127. auto remaining_samples = m_total_samples - m_loaded_samples;
  128. if (remaining_samples <= 0)
  129. return FixedArray<Sample> {};
  130. // One "sample" contains data from all channels.
  131. // In the Wave spec, this is also called a block.
  132. size_t bytes_per_sample
  133. = m_num_channels * pcm_bits_per_sample(m_sample_format) / 8;
  134. // Might truncate if not evenly divisible by the sample size
  135. auto max_samples_to_read = max_samples_to_read_from_input / bytes_per_sample;
  136. auto samples_to_read = min(max_samples_to_read, remaining_samples);
  137. auto bytes_to_read = samples_to_read * bytes_per_sample;
  138. dbgln_if(AWAVLOADER_DEBUG, "Read {} bytes WAV with num_channels {} sample rate {}, "
  139. "bits per sample {}, sample format {}",
  140. bytes_to_read, m_num_channels, m_sample_rate,
  141. pcm_bits_per_sample(m_sample_format), sample_format_name(m_sample_format));
  142. auto sample_data = LOADER_TRY(ByteBuffer::create_zeroed(bytes_to_read));
  143. LOADER_TRY(m_stream->read(sample_data.bytes()));
  144. // m_loaded_samples should contain the amount of actually loaded samples
  145. m_loaded_samples += samples_to_read;
  146. return samples_from_pcm_data(sample_data.bytes(), samples_to_read);
  147. }
  148. MaybeLoaderError WavLoaderPlugin::seek(int sample_index)
  149. {
  150. dbgln_if(AWAVLOADER_DEBUG, "seek sample_index {}", sample_index);
  151. if (sample_index < 0 || sample_index >= static_cast<int>(m_total_samples))
  152. return LoaderError { LoaderError::Category::Internal, m_loaded_samples, "Seek outside the sample range" };
  153. 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));
  154. LOADER_TRY(m_stream->seek(sample_offset, Core::Stream::SeekMode::SetPosition));
  155. m_loaded_samples = sample_index;
  156. return {};
  157. }
  158. // Specification reference: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  159. MaybeLoaderError WavLoaderPlugin::parse_header()
  160. {
  161. if (!m_stream)
  162. return LoaderError { LoaderError::Category::Internal, 0, "No stream" };
  163. bool ok = true;
  164. size_t bytes_read = 0;
  165. auto read_u8 = [&]() -> ErrorOr<u8, LoaderError> {
  166. u8 value;
  167. LOADER_TRY(m_stream->read(Bytes { &value, 1 }));
  168. bytes_read += 1;
  169. return value;
  170. };
  171. auto read_u16 = [&]() -> ErrorOr<u16, LoaderError> {
  172. u16 value;
  173. LOADER_TRY(m_stream->read(Bytes { &value, 2 }));
  174. bytes_read += 2;
  175. return value;
  176. };
  177. auto read_u32 = [&]() -> ErrorOr<u32, LoaderError> {
  178. u32 value;
  179. LOADER_TRY(m_stream->read(Bytes { &value, 4 }));
  180. bytes_read += 4;
  181. return value;
  182. };
  183. #define CHECK_OK(category, msg) \
  184. do { \
  185. if (!ok) \
  186. return LoaderError { category, String::formatted("Parsing failed: {}", msg) }; \
  187. } while (0)
  188. u32 riff = TRY(read_u32());
  189. ok = ok && riff == 0x46464952; // "RIFF"
  190. CHECK_OK(LoaderError::Category::Format, "RIFF header");
  191. u32 sz = TRY(read_u32());
  192. ok = ok && sz < maximum_wav_size;
  193. CHECK_OK(LoaderError::Category::Format, "File size");
  194. u32 wave = TRY(read_u32());
  195. ok = ok && wave == 0x45564157; // "WAVE"
  196. CHECK_OK(LoaderError::Category::Format, "WAVE header");
  197. u32 fmt_id = TRY(read_u32());
  198. ok = ok && fmt_id == 0x20746D66; // "fmt "
  199. CHECK_OK(LoaderError::Category::Format, "FMT header");
  200. u32 fmt_size = TRY(read_u32());
  201. ok = ok && (fmt_size == 16 || fmt_size == 18 || fmt_size == 40);
  202. CHECK_OK(LoaderError::Category::Format, "FMT size");
  203. u16 audio_format = TRY(read_u16());
  204. CHECK_OK(LoaderError::Category::Format, "Audio format"); // incomplete read check
  205. ok = ok && (audio_format == WAVE_FORMAT_PCM || audio_format == WAVE_FORMAT_IEEE_FLOAT || audio_format == WAVE_FORMAT_EXTENSIBLE);
  206. CHECK_OK(LoaderError::Category::Unimplemented, "Audio format PCM/Float"); // value check
  207. m_num_channels = TRY(read_u16());
  208. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  209. CHECK_OK(LoaderError::Category::Unimplemented, "Channel count");
  210. m_sample_rate = TRY(read_u32());
  211. CHECK_OK(LoaderError::Category::IO, "Sample rate");
  212. TRY(read_u32());
  213. CHECK_OK(LoaderError::Category::IO, "Data rate");
  214. u16 block_size_bytes = TRY(read_u16());
  215. CHECK_OK(LoaderError::Category::IO, "Block size");
  216. u16 bits_per_sample = TRY(read_u16());
  217. CHECK_OK(LoaderError::Category::IO, "Bits per sample");
  218. if (audio_format == WAVE_FORMAT_EXTENSIBLE) {
  219. ok = ok && (fmt_size == 40);
  220. CHECK_OK(LoaderError::Category::Format, "Extensible fmt size"); // value check
  221. // Discard everything until the GUID.
  222. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  223. TRY(read_u32());
  224. TRY(read_u32());
  225. CHECK_OK(LoaderError::Category::IO, "Discard until GUID");
  226. // Get the underlying audio format from the first two bytes of GUID
  227. u16 guid_subformat = TRY(read_u16());
  228. ok = ok && (guid_subformat == WAVE_FORMAT_PCM || guid_subformat == WAVE_FORMAT_IEEE_FLOAT);
  229. CHECK_OK(LoaderError::Category::Unimplemented, "GUID SubFormat");
  230. audio_format = guid_subformat;
  231. }
  232. if (audio_format == WAVE_FORMAT_PCM) {
  233. ok = ok && (bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24);
  234. CHECK_OK(LoaderError::Category::Unimplemented, "Bits per sample (PCM)"); // value check
  235. // We only support 8-24 bit audio right now because other formats are uncommon
  236. if (bits_per_sample == 8) {
  237. m_sample_format = PcmSampleFormat::Uint8;
  238. } else if (bits_per_sample == 16) {
  239. m_sample_format = PcmSampleFormat::Int16;
  240. } else if (bits_per_sample == 24) {
  241. m_sample_format = PcmSampleFormat::Int24;
  242. }
  243. } else if (audio_format == WAVE_FORMAT_IEEE_FLOAT) {
  244. ok = ok && (bits_per_sample == 32 || bits_per_sample == 64);
  245. CHECK_OK(LoaderError::Category::Unimplemented, "Bits per sample (Float)"); // value check
  246. // Again, only the common 32 and 64 bit
  247. if (bits_per_sample == 32) {
  248. m_sample_format = PcmSampleFormat::Float32;
  249. } else if (bits_per_sample == 64) {
  250. m_sample_format = PcmSampleFormat::Float64;
  251. }
  252. }
  253. ok = ok && (block_size_bytes == (m_num_channels * (bits_per_sample / 8)));
  254. CHECK_OK(LoaderError::Category::Format, "Block size sanity check");
  255. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  256. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  257. // Read chunks until we find DATA
  258. bool found_data = false;
  259. u32 data_size = 0;
  260. u8 search_byte = 0;
  261. while (true) {
  262. search_byte = TRY(read_u8());
  263. CHECK_OK(LoaderError::Category::IO, "Reading byte searching for data");
  264. if (search_byte != 0x64) // D
  265. continue;
  266. search_byte = TRY(read_u8());
  267. CHECK_OK(LoaderError::Category::IO, "Reading next byte searching for data");
  268. if (search_byte != 0x61) // A
  269. continue;
  270. u16 search_remaining = TRY(read_u16());
  271. CHECK_OK(LoaderError::Category::IO, "Reading remaining bytes searching for data");
  272. if (search_remaining != 0x6174) // TA
  273. continue;
  274. data_size = TRY(read_u32());
  275. found_data = true;
  276. break;
  277. }
  278. ok = ok && found_data;
  279. CHECK_OK(LoaderError::Category::Format, "Found no data chunk");
  280. ok = ok && data_size < maximum_wav_size;
  281. CHECK_OK(LoaderError::Category::Format, "Data was too large");
  282. m_total_samples = data_size / block_size_bytes;
  283. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  284. data_size,
  285. block_size_bytes,
  286. m_total_samples);
  287. m_byte_offset_of_data_samples = bytes_read;
  288. return {};
  289. }
  290. }