WavLoader.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, kleines Filmröllchen <malu.bertsch@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "WavLoader.h"
  8. #include "Buffer.h"
  9. #include <AK/Debug.h>
  10. #include <AK/NumericLimits.h>
  11. #include <AK/OwnPtr.h>
  12. #include <LibCore/File.h>
  13. #include <LibCore/FileStream.h>
  14. namespace Audio {
  15. static constexpr size_t maximum_wav_size = 1 * GiB; // FIXME: is there a more appropriate size limit?
  16. WavLoaderPlugin::WavLoaderPlugin(const StringView& path)
  17. : m_file(Core::File::construct(path))
  18. {
  19. if (!m_file->open(Core::OpenMode::ReadOnly)) {
  20. m_error_string = String::formatted("Can't open file: {}", m_file->error_string());
  21. return;
  22. }
  23. m_stream = make<Core::InputFileStream>(*m_file);
  24. valid = parse_header();
  25. if (!valid)
  26. return;
  27. }
  28. WavLoaderPlugin::WavLoaderPlugin(const ByteBuffer& buffer)
  29. {
  30. m_stream = make<InputMemoryStream>(buffer);
  31. if (!m_stream) {
  32. m_error_string = String::formatted("Can't open memory stream");
  33. return;
  34. }
  35. m_memory_stream = static_cast<InputMemoryStream*>(m_stream.ptr());
  36. valid = parse_header();
  37. if (!valid)
  38. return;
  39. }
  40. RefPtr<Buffer> WavLoaderPlugin::get_more_samples(size_t max_bytes_to_read_from_input)
  41. {
  42. if (!m_stream)
  43. return nullptr;
  44. int remaining_samples = m_total_samples - m_loaded_samples;
  45. if (remaining_samples <= 0) {
  46. return nullptr;
  47. }
  48. // One "sample" contains data from all channels.
  49. // In the Wave spec, this is also called a block.
  50. size_t bytes_per_sample = m_num_channels * pcm_bits_per_sample(m_sample_format) / 8;
  51. // Might truncate if not evenly divisible by the sample size
  52. int max_samples_to_read = static_cast<int>(max_bytes_to_read_from_input) / bytes_per_sample;
  53. int samples_to_read = min(max_samples_to_read, remaining_samples);
  54. size_t bytes_to_read = samples_to_read * bytes_per_sample;
  55. dbgln_if(AWAVLOADER_DEBUG, "Read {} bytes WAV with num_channels {} sample rate {}, "
  56. "bits per sample {}, sample format {}",
  57. bytes_to_read, m_num_channels, m_sample_rate,
  58. pcm_bits_per_sample(m_sample_format), sample_format_name(m_sample_format));
  59. auto sample_data_result = ByteBuffer::create_zeroed(bytes_to_read);
  60. if (!sample_data_result.has_value())
  61. return nullptr;
  62. auto sample_data = sample_data_result.release_value();
  63. m_stream->read_or_error(sample_data.bytes());
  64. if (m_stream->handle_any_error()) {
  65. return nullptr;
  66. }
  67. RefPtr<Buffer> buffer = Buffer::from_pcm_data(
  68. sample_data.bytes(),
  69. m_num_channels,
  70. m_sample_format);
  71. // m_loaded_samples should contain the amount of actually loaded samples
  72. m_loaded_samples += samples_to_read;
  73. return buffer;
  74. }
  75. void WavLoaderPlugin::seek(const int sample_index)
  76. {
  77. dbgln_if(AWAVLOADER_DEBUG, "seek sample_index {}", sample_index);
  78. if (sample_index < 0 || sample_index >= m_total_samples)
  79. return;
  80. size_t sample_offset = m_byte_offset_of_data_samples + (sample_index * m_num_channels * (pcm_bits_per_sample(m_sample_format) / 8));
  81. // AK::InputStream does not define seek, hence the special-cases for file and stream.
  82. if (m_file) {
  83. m_file->seek(sample_offset);
  84. } else {
  85. m_memory_stream->seek(sample_offset);
  86. }
  87. m_loaded_samples = sample_index;
  88. }
  89. // Specification reference: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  90. bool WavLoaderPlugin::parse_header()
  91. {
  92. if (!m_stream)
  93. return false;
  94. bool ok = true;
  95. size_t bytes_read = 0;
  96. auto read_u8 = [&]() -> u8 {
  97. u8 value;
  98. *m_stream >> value;
  99. if (m_stream->handle_any_error())
  100. ok = false;
  101. bytes_read += 1;
  102. return value;
  103. };
  104. auto read_u16 = [&]() -> u16 {
  105. u16 value;
  106. *m_stream >> value;
  107. if (m_stream->handle_any_error())
  108. ok = false;
  109. bytes_read += 2;
  110. return value;
  111. };
  112. auto read_u32 = [&]() -> u32 {
  113. u32 value;
  114. *m_stream >> value;
  115. if (m_stream->handle_any_error())
  116. ok = false;
  117. bytes_read += 4;
  118. return value;
  119. };
  120. #define CHECK_OK(msg) \
  121. do { \
  122. if (!ok) { \
  123. m_error_string = String::formatted("Parsing failed: {}", msg); \
  124. dbgln_if(AWAVLOADER_DEBUG, m_error_string); \
  125. return {}; \
  126. } \
  127. } while (0)
  128. u32 riff = read_u32();
  129. ok = ok && riff == 0x46464952; // "RIFF"
  130. CHECK_OK("RIFF header");
  131. u32 sz = read_u32();
  132. ok = ok && sz < maximum_wav_size;
  133. CHECK_OK("File size");
  134. u32 wave = read_u32();
  135. ok = ok && wave == 0x45564157; // "WAVE"
  136. CHECK_OK("WAVE header");
  137. u32 fmt_id = read_u32();
  138. ok = ok && fmt_id == 0x20746D66; // "fmt "
  139. CHECK_OK("FMT header");
  140. u32 fmt_size = read_u32();
  141. ok = ok && (fmt_size == 16 || fmt_size == 18 || fmt_size == 40);
  142. CHECK_OK("FMT size");
  143. u16 audio_format = read_u16();
  144. CHECK_OK("Audio format"); // incomplete read check
  145. ok = ok && (audio_format == WAVE_FORMAT_PCM || audio_format == WAVE_FORMAT_IEEE_FLOAT || audio_format == WAVE_FORMAT_EXTENSIBLE);
  146. CHECK_OK("Audio format PCM/Float"); // value check
  147. m_num_channels = read_u16();
  148. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  149. CHECK_OK("Channel count");
  150. m_sample_rate = read_u32();
  151. CHECK_OK("Sample rate");
  152. read_u32();
  153. CHECK_OK("Data rate");
  154. u16 block_size_bytes = read_u16();
  155. CHECK_OK("Block size");
  156. u16 bits_per_sample = read_u16();
  157. CHECK_OK("Bits per sample");
  158. if (audio_format == WAVE_FORMAT_EXTENSIBLE) {
  159. ok = ok && (fmt_size == 40);
  160. CHECK_OK("Extensible fmt size"); // value check
  161. // Discard everything until the GUID.
  162. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  163. read_u32();
  164. read_u32();
  165. CHECK_OK("Discard until GUID");
  166. // Get the underlying audio format from the first two bytes of GUID
  167. u16 guid_subformat = read_u16();
  168. ok = ok && (guid_subformat == WAVE_FORMAT_PCM || guid_subformat == WAVE_FORMAT_IEEE_FLOAT);
  169. CHECK_OK("GUID SubFormat");
  170. audio_format = guid_subformat;
  171. }
  172. if (audio_format == WAVE_FORMAT_PCM) {
  173. ok = ok && (bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24);
  174. CHECK_OK("Bits per sample (PCM)"); // value check
  175. // We only support 8-24 bit audio right now because other formats are uncommon
  176. if (bits_per_sample == 8) {
  177. m_sample_format = PcmSampleFormat::Uint8;
  178. } else if (bits_per_sample == 16) {
  179. m_sample_format = PcmSampleFormat::Int16;
  180. } else if (bits_per_sample == 24) {
  181. m_sample_format = PcmSampleFormat::Int24;
  182. }
  183. } else if (audio_format == WAVE_FORMAT_IEEE_FLOAT) {
  184. ok = ok && (bits_per_sample == 32 || bits_per_sample == 64);
  185. CHECK_OK("Bits per sample (Float)"); // value check
  186. // Again, only the common 32 and 64 bit
  187. if (bits_per_sample == 32) {
  188. m_sample_format = PcmSampleFormat::Float32;
  189. } else if (bits_per_sample == 64) {
  190. m_sample_format = PcmSampleFormat::Float64;
  191. }
  192. }
  193. ok = ok && (block_size_bytes == (m_num_channels * (bits_per_sample / 8)));
  194. CHECK_OK("Block size sanity check");
  195. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  196. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  197. // Read chunks until we find DATA
  198. bool found_data = false;
  199. u32 data_sz = 0;
  200. u8 search_byte = 0;
  201. while (true) {
  202. search_byte = read_u8();
  203. CHECK_OK("Reading byte searching for data");
  204. if (search_byte != 0x64) // D
  205. continue;
  206. search_byte = read_u8();
  207. CHECK_OK("Reading next byte searching for data");
  208. if (search_byte != 0x61) // A
  209. continue;
  210. u16 search_remaining = read_u16();
  211. CHECK_OK("Reading remaining bytes searching for data");
  212. if (search_remaining != 0x6174) // TA
  213. continue;
  214. data_sz = read_u32();
  215. found_data = true;
  216. break;
  217. }
  218. ok = ok && found_data;
  219. CHECK_OK("Found no data chunk");
  220. ok = ok && data_sz < maximum_wav_size;
  221. CHECK_OK("Data was too large");
  222. m_total_samples = data_sz / block_size_bytes;
  223. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  224. data_sz,
  225. block_size_bytes,
  226. m_total_samples);
  227. m_byte_offset_of_data_samples = bytes_read;
  228. return true;
  229. }
  230. }