WavLoader.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 <AK/Debug.h>
  8. #include <AK/NumericLimits.h>
  9. #include <AK/OwnPtr.h>
  10. #include <LibAudio/Buffer.h>
  11. #include <LibAudio/WavLoader.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. m_resampler = make<ResampleHelper>(m_sample_rate, 44100);
  28. }
  29. WavLoaderPlugin::WavLoaderPlugin(const ByteBuffer& buffer)
  30. {
  31. m_stream = make<InputMemoryStream>(buffer);
  32. if (!m_stream) {
  33. m_error_string = String::formatted("Can't open memory stream");
  34. return;
  35. }
  36. m_memory_stream = static_cast<InputMemoryStream*>(m_stream.ptr());
  37. valid = parse_header();
  38. if (!valid)
  39. return;
  40. m_resampler = make<ResampleHelper>(m_sample_rate, 44100);
  41. }
  42. RefPtr<Buffer> WavLoaderPlugin::get_more_samples(size_t max_bytes_to_read_from_input)
  43. {
  44. if (!m_stream)
  45. return nullptr;
  46. size_t bytes_per_sample = (m_num_channels * (pcm_bits_per_sample(m_sample_format) / 8));
  47. // Might truncate if not evenly divisible
  48. size_t samples_to_read = static_cast<int>(max_bytes_to_read_from_input) / bytes_per_sample;
  49. size_t bytes_to_read = samples_to_read * bytes_per_sample;
  50. dbgln_if(AWAVLOADER_DEBUG, "Read {} bytes ({} samples) WAV with num_channels {} sample rate {}, "
  51. "bits per sample {}, sample format {}",
  52. bytes_to_read, samples_to_read, m_num_channels, m_sample_rate,
  53. pcm_bits_per_sample(m_sample_format), sample_format_name(m_sample_format));
  54. ByteBuffer sample_data = ByteBuffer::create_zeroed(bytes_to_read);
  55. m_stream->read_or_error(sample_data.bytes());
  56. if (m_stream->handle_any_error()) {
  57. return nullptr;
  58. }
  59. RefPtr<Buffer> buffer = Buffer::from_pcm_data(
  60. sample_data.bytes(),
  61. *m_resampler,
  62. m_num_channels,
  63. m_sample_format);
  64. // m_loaded_samples should contain the amount of actually loaded samples
  65. m_loaded_samples += samples_to_read;
  66. m_loaded_samples = min(m_total_samples, m_loaded_samples);
  67. return buffer;
  68. }
  69. void WavLoaderPlugin::seek(const int sample_index)
  70. {
  71. dbgln_if(AWAVLOADER_DEBUG, "seek sample_index {}", sample_index);
  72. if (sample_index < 0 || sample_index >= m_total_samples)
  73. return;
  74. m_loaded_samples = sample_index;
  75. size_t byte_position = m_byte_offset_of_data_samples + sample_index * m_num_channels * (pcm_bits_per_sample(m_sample_format) / 8);
  76. // AK::InputStream does not define seek.
  77. if (m_file) {
  78. m_file->seek(byte_position);
  79. } else {
  80. m_memory_stream->seek(byte_position);
  81. }
  82. }
  83. // Specification reference: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  84. bool WavLoaderPlugin::parse_header()
  85. {
  86. if (!m_stream)
  87. return false;
  88. bool ok = true;
  89. size_t bytes_read = 0;
  90. auto read_u8 = [&]() -> u8 {
  91. u8 value;
  92. *m_stream >> value;
  93. if (m_stream->handle_any_error())
  94. ok = false;
  95. bytes_read += 1;
  96. return value;
  97. };
  98. auto read_u16 = [&]() -> u16 {
  99. u16 value;
  100. *m_stream >> value;
  101. if (m_stream->handle_any_error())
  102. ok = false;
  103. bytes_read += 2;
  104. return value;
  105. };
  106. auto read_u32 = [&]() -> u32 {
  107. u32 value;
  108. *m_stream >> value;
  109. if (m_stream->handle_any_error())
  110. ok = false;
  111. bytes_read += 4;
  112. return value;
  113. };
  114. #define CHECK_OK(msg) \
  115. do { \
  116. if (!ok) { \
  117. m_error_string = String::formatted("Parsing failed: {}", msg); \
  118. dbgln_if(AWAVLOADER_DEBUG, m_error_string); \
  119. return {}; \
  120. } \
  121. } while (0)
  122. u32 riff = read_u32();
  123. ok = ok && riff == 0x46464952; // "RIFF"
  124. CHECK_OK("RIFF header");
  125. u32 sz = read_u32();
  126. ok = ok && sz < maximum_wav_size;
  127. CHECK_OK("File size");
  128. u32 wave = read_u32();
  129. ok = ok && wave == 0x45564157; // "WAVE"
  130. CHECK_OK("WAVE header");
  131. u32 fmt_id = read_u32();
  132. ok = ok && fmt_id == 0x20746D66; // "fmt "
  133. CHECK_OK("FMT header");
  134. u32 fmt_size = read_u32();
  135. ok = ok && (fmt_size == 16 || fmt_size == 18 || fmt_size == 40);
  136. CHECK_OK("FMT size");
  137. u16 audio_format = read_u16();
  138. CHECK_OK("Audio format"); // incomplete read check
  139. ok = ok && (audio_format == WAVE_FORMAT_PCM || audio_format == WAVE_FORMAT_IEEE_FLOAT || audio_format == WAVE_FORMAT_EXTENSIBLE);
  140. CHECK_OK("Audio format PCM/Float"); // value check
  141. m_num_channels = read_u16();
  142. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  143. CHECK_OK("Channel count");
  144. m_sample_rate = read_u32();
  145. CHECK_OK("Sample rate");
  146. read_u32();
  147. CHECK_OK("Data rate");
  148. read_u16();
  149. CHECK_OK("Block size");
  150. u16 bits_per_sample = read_u16();
  151. CHECK_OK("Bits per sample"); // incomplete read check
  152. if (audio_format == WAVE_FORMAT_EXTENSIBLE) {
  153. ok = ok && (fmt_size == 40);
  154. CHECK_OK("Extensible fmt size"); // value check
  155. // Discard everything until the GUID.
  156. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  157. read_u32();
  158. read_u32();
  159. CHECK_OK("Discard until GUID");
  160. // Get the underlying audio format from the first two bytes of GUID
  161. u16 guid_subformat = read_u16();
  162. ok = ok && (guid_subformat == WAVE_FORMAT_PCM || guid_subformat == WAVE_FORMAT_IEEE_FLOAT);
  163. CHECK_OK("GUID SubFormat");
  164. audio_format = guid_subformat;
  165. }
  166. if (audio_format == WAVE_FORMAT_PCM) {
  167. ok = ok && (bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24);
  168. CHECK_OK("Bits per sample (PCM)"); // value check
  169. // We only support 8-24 bit audio right now because other formats are uncommon
  170. if (bits_per_sample == 8) {
  171. m_sample_format = PcmSampleFormat::Uint8;
  172. } else if (bits_per_sample == 16) {
  173. m_sample_format = PcmSampleFormat::Int16;
  174. } else if (bits_per_sample == 24) {
  175. m_sample_format = PcmSampleFormat::Int24;
  176. }
  177. } else if (audio_format == WAVE_FORMAT_IEEE_FLOAT) {
  178. ok = ok && (bits_per_sample == 32 || bits_per_sample == 64);
  179. CHECK_OK("Bits per sample (Float)"); // value check
  180. // Again, only the common 32 and 64 bit
  181. if (bits_per_sample == 32) {
  182. m_sample_format = PcmSampleFormat::Float32;
  183. } else if (bits_per_sample == 64) {
  184. m_sample_format = PcmSampleFormat::Float64;
  185. }
  186. }
  187. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  188. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  189. // Read chunks until we find DATA
  190. bool found_data = false;
  191. u32 data_sz = 0;
  192. u8 search_byte = 0;
  193. while (true) {
  194. search_byte = read_u8();
  195. CHECK_OK("Reading byte searching for data");
  196. if (search_byte != 0x64) //D
  197. continue;
  198. search_byte = read_u8();
  199. CHECK_OK("Reading next byte searching for data");
  200. if (search_byte != 0x61) //A
  201. continue;
  202. u16 search_remaining = read_u16();
  203. CHECK_OK("Reading remaining bytes searching for data");
  204. if (search_remaining != 0x6174) //TA
  205. continue;
  206. data_sz = read_u32();
  207. found_data = true;
  208. break;
  209. }
  210. ok = ok && found_data;
  211. CHECK_OK("Found no data chunk");
  212. ok = ok && data_sz < maximum_wav_size;
  213. CHECK_OK("Data was too large");
  214. int bytes_per_sample = (bits_per_sample / 8) * m_num_channels;
  215. m_total_samples = data_sz / bytes_per_sample;
  216. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  217. data_sz,
  218. bytes_per_sample,
  219. m_total_samples);
  220. m_byte_offset_of_data_samples = bytes_read;
  221. return true;
  222. }
  223. ResampleHelper::ResampleHelper(double source, double target)
  224. : m_ratio(source / target)
  225. {
  226. }
  227. void ResampleHelper::process_sample(double sample_l, double sample_r)
  228. {
  229. m_last_sample_l = sample_l;
  230. m_last_sample_r = sample_r;
  231. m_current_ratio += 1;
  232. }
  233. bool ResampleHelper::read_sample(double& next_l, double& next_r)
  234. {
  235. if (m_current_ratio > 0) {
  236. m_current_ratio -= m_ratio;
  237. next_l = m_last_sample_l;
  238. next_r = m_last_sample_r;
  239. return true;
  240. }
  241. return false;
  242. }
  243. }