WavLoader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, 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 "RIFFTypes.h"
  10. #include <AK/Debug.h>
  11. #include <AK/Endian.h>
  12. #include <AK/FixedArray.h>
  13. #include <AK/MemoryStream.h>
  14. #include <AK/NumericLimits.h>
  15. #include <AK/Try.h>
  16. #include <LibCore/File.h>
  17. namespace Audio {
  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::InputBufferedFile::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. #define CHECK(check, category, msg) \
  157. do { \
  158. if (!(check)) { \
  159. return LoaderError { category, static_cast<size_t>(LOADER_TRY(m_stream->tell())), DeprecatedString::formatted("WAV header: {}", msg) }; \
  160. } \
  161. } while (0)
  162. auto riff = TRY(m_stream->read_value<RIFF::ChunkID>());
  163. CHECK(riff == RIFF::riff_magic, LoaderError::Category::Format, "RIFF header magic invalid");
  164. TRY(m_stream->read_value<LittleEndian<u32>>()); // File size header
  165. auto wave = TRY(m_stream->read_value<RIFF::ChunkID>());
  166. CHECK(wave == RIFF::wave_subformat_id, LoaderError::Category::Format, "WAVE subformat id invalid");
  167. auto format_chunk = TRY(m_stream->read_value<RIFF::Chunk>());
  168. CHECK(format_chunk.id.as_ascii_string() == RIFF::format_chunk_id, LoaderError::Category::Format, "FMT chunk id invalid");
  169. auto format_stream = format_chunk.data_stream();
  170. u16 audio_format = TRY(format_stream.read_value<LittleEndian<u16>>());
  171. CHECK(audio_format == to_underlying(RIFF::WaveFormat::Pcm) || audio_format == to_underlying(RIFF::WaveFormat::IEEEFloat) || audio_format == to_underlying(RIFF::WaveFormat::Extensible),
  172. LoaderError::Category::Unimplemented, "Audio format not supported");
  173. m_num_channels = TRY(format_stream.read_value<LittleEndian<u16>>());
  174. CHECK(m_num_channels == 1 || m_num_channels == 2, LoaderError::Category::Unimplemented, "Channel count");
  175. m_sample_rate = TRY(format_stream.read_value<LittleEndian<u32>>());
  176. // Data rate; can be ignored.
  177. TRY(format_stream.read_value<LittleEndian<u32>>());
  178. u16 block_size_bytes = TRY(format_stream.read_value<LittleEndian<u16>>());
  179. u16 bits_per_sample = TRY(format_stream.read_value<LittleEndian<u16>>());
  180. if (audio_format == to_underlying(RIFF::WaveFormat::Extensible)) {
  181. CHECK(format_chunk.size == 40, LoaderError::Category::Format, "Extensible fmt size is not 40 bytes");
  182. // Discard everything until the GUID.
  183. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  184. TRY(format_stream.read_value<LittleEndian<u64>>());
  185. // Get the underlying audio format from the first two bytes of GUID
  186. u16 guid_subformat = TRY(format_stream.read_value<LittleEndian<u16>>());
  187. CHECK(guid_subformat == to_underlying(RIFF::WaveFormat::Pcm) || guid_subformat == to_underlying(RIFF::WaveFormat::IEEEFloat), LoaderError::Category::Unimplemented, "GUID SubFormat not supported");
  188. audio_format = guid_subformat;
  189. }
  190. if (audio_format == to_underlying(RIFF::WaveFormat::Pcm)) {
  191. CHECK(bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24, LoaderError::Category::Unimplemented, "PCM bits per sample not supported");
  192. // We only support 8-24 bit audio right now because other formats are uncommon
  193. if (bits_per_sample == 8) {
  194. m_sample_format = PcmSampleFormat::Uint8;
  195. } else if (bits_per_sample == 16) {
  196. m_sample_format = PcmSampleFormat::Int16;
  197. } else if (bits_per_sample == 24) {
  198. m_sample_format = PcmSampleFormat::Int24;
  199. }
  200. } else if (audio_format == to_underlying(RIFF::WaveFormat::IEEEFloat)) {
  201. CHECK(bits_per_sample == 32 || bits_per_sample == 64, LoaderError::Category::Unimplemented, "Float bits per sample not supported");
  202. // Again, only the common 32 and 64 bit
  203. if (bits_per_sample == 32) {
  204. m_sample_format = PcmSampleFormat::Float32;
  205. } else if (bits_per_sample == 64) {
  206. m_sample_format = PcmSampleFormat::Float64;
  207. }
  208. }
  209. CHECK(block_size_bytes == (m_num_channels * (bits_per_sample / 8)), LoaderError::Category::Format, "Block size invalid");
  210. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  211. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  212. // Read all chunks before DATA.
  213. bool found_data = false;
  214. while (!found_data) {
  215. auto chunk_header = TRY(m_stream->read_value<RIFF::ChunkID>());
  216. if (chunk_header == RIFF::data_chunk_id) {
  217. found_data = true;
  218. } else {
  219. TRY(m_stream->seek(-RIFF::chunk_id_size, SeekMode::FromCurrentPosition));
  220. auto chunk = TRY(m_stream->read_value<RIFF::Chunk>());
  221. if (chunk.id == RIFF::list_chunk_id) {
  222. auto maybe_list = chunk.data_stream().read_value<RIFF::List>();
  223. if (maybe_list.is_error()) {
  224. dbgln("WAV Warning: LIST chunk invalid, error: {}", maybe_list.release_error());
  225. continue;
  226. }
  227. auto list = maybe_list.release_value();
  228. if (list.type == RIFF::info_chunk_id) {
  229. auto maybe_error = load_wav_info_block(move(list.chunks));
  230. if (maybe_error.is_error())
  231. dbgln("WAV Warning: INFO chunk invalid, error: {}", maybe_error.release_error());
  232. } else {
  233. dbgln("Unhandled WAV list of type {} with {} subchunks", list.type.as_ascii_string(), list.chunks.size());
  234. }
  235. } else {
  236. dbgln_if(AWAVLOADER_DEBUG, "Unhandled WAV chunk of type {}, size {} bytes", chunk.id.as_ascii_string(), chunk.size);
  237. }
  238. }
  239. }
  240. u32 data_size = TRY(m_stream->read_value<LittleEndian<u32>>());
  241. CHECK(found_data, LoaderError::Category::Format, "Found no data chunk");
  242. m_total_samples = data_size / block_size_bytes;
  243. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  244. data_size,
  245. block_size_bytes,
  246. m_total_samples);
  247. m_byte_offset_of_data_samples = TRY(m_stream->tell());
  248. return {};
  249. }
  250. // http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/riffmci.pdf page 23 (LIST type)
  251. // We only recognize the relevant official metadata types; types added in later errata of RIFF are not relevant for audio.
  252. MaybeLoaderError WavLoaderPlugin::load_wav_info_block(Vector<RIFF::Chunk> info_chunks)
  253. {
  254. for (auto const& chunk : info_chunks) {
  255. auto metadata_name = chunk.id.as_ascii_string();
  256. // Chunk contents are zero-terminated strings "ZSTR", so we just drop the null terminator.
  257. StringView metadata_text { chunk.data.span().trim(chunk.data.size() - 1) };
  258. // Note that we assume chunks to be unique, since that seems to almost always be the case.
  259. // Worst case we just drop some metadata.
  260. if (metadata_name == "IART"sv) {
  261. // Artists are combined together with semicolons, at least when you edit them in Windows File Explorer.
  262. auto artists = metadata_text.split_view(";"sv);
  263. for (auto artist : artists)
  264. TRY(m_metadata.add_person(Person::Role::Artist, TRY(String::from_utf8(artist))));
  265. } else if (metadata_name == "ICMT"sv) {
  266. m_metadata.comment = TRY(String::from_utf8(metadata_text));
  267. } else if (metadata_name == "ICOP"sv) {
  268. m_metadata.copyright = TRY(String::from_utf8(metadata_text));
  269. } else if (metadata_name == "ICRD"sv) {
  270. m_metadata.unparsed_time = TRY(String::from_utf8(metadata_text));
  271. } else if (metadata_name == "IENG"sv) {
  272. TRY(m_metadata.add_person(Person::Role::Engineer, TRY(String::from_utf8(metadata_text))));
  273. } else if (metadata_name == "IGNR"sv) {
  274. m_metadata.genre = TRY(String::from_utf8(metadata_text));
  275. } else if (metadata_name == "INAM"sv) {
  276. m_metadata.title = TRY(String::from_utf8(metadata_text));
  277. } else if (metadata_name == "ISFT"sv) {
  278. m_metadata.encoder = TRY(String::from_utf8(metadata_text));
  279. } else if (metadata_name == "ISRC"sv) {
  280. TRY(m_metadata.add_person(Person::Role::Publisher, TRY(String::from_utf8(metadata_text))));
  281. } else {
  282. TRY(m_metadata.add_miscellaneous(TRY(String::from_utf8(metadata_name)), TRY(String::from_utf8(metadata_text))));
  283. }
  284. }
  285. return {};
  286. }
  287. }