AWavLoader.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/BufferStream.h>
  27. #include <LibAudio/AWavLoader.h>
  28. #include <LibCore/CFile.h>
  29. #include <LibCore/CIODeviceStreamReader.h>
  30. #include <limits>
  31. AWavLoader::AWavLoader(const StringView& path)
  32. : m_file(Core::File::construct(path))
  33. {
  34. if (!m_file->open(Core::IODevice::ReadOnly)) {
  35. m_error_string = String::format("Can't open file: %s", m_file->error_string());
  36. return;
  37. }
  38. parse_header();
  39. m_resampler = make<AResampleHelper>(m_sample_rate, 44100);
  40. }
  41. RefPtr<ABuffer> AWavLoader::get_more_samples(size_t max_bytes_to_read_from_input)
  42. {
  43. #ifdef AWAVLOADER_DEBUG
  44. dbgprintf("Read WAV of format PCM with num_channels %u sample rate %u, bits per sample %u\n", m_num_channels, m_sample_rate, m_bits_per_sample);
  45. #endif
  46. auto raw_samples = m_file->read(max_bytes_to_read_from_input);
  47. if (raw_samples.is_empty())
  48. return nullptr;
  49. auto buffer = ABuffer::from_pcm_data(raw_samples, *m_resampler, m_num_channels, m_bits_per_sample);
  50. //Buffer contains normalized samples, but m_loaded_samples should containt the ammount of actually loaded samples
  51. m_loaded_samples += static_cast<int>(max_bytes_to_read_from_input) / (m_num_channels * (m_bits_per_sample / 8));
  52. m_loaded_samples = min(m_total_samples, m_loaded_samples);
  53. return buffer;
  54. }
  55. void AWavLoader::seek(const int position)
  56. {
  57. if (position < 0 || position > m_total_samples)
  58. return;
  59. m_loaded_samples = position;
  60. m_file->seek(position * m_num_channels * (m_bits_per_sample / 8));
  61. }
  62. void AWavLoader::reset()
  63. {
  64. seek(0);
  65. }
  66. bool AWavLoader::parse_header()
  67. {
  68. Core::IODeviceStreamReader stream(*m_file);
  69. #define CHECK_OK(msg) \
  70. do { \
  71. ASSERT(ok); \
  72. if (stream.handle_read_failure()) { \
  73. m_error_string = String::format("Premature stream EOF at %s", msg); \
  74. return {}; \
  75. } \
  76. if (!ok) { \
  77. m_error_string = String::format("Parsing failed: %s", msg); \
  78. return {}; \
  79. } else { \
  80. dbgprintf("%s is OK!\n", msg); \
  81. } \
  82. } while (0);
  83. bool ok = true;
  84. u32 riff;
  85. stream >> riff;
  86. ok = ok && riff == 0x46464952; // "RIFF"
  87. CHECK_OK("RIFF header");
  88. u32 sz;
  89. stream >> sz;
  90. ok = ok && sz < 1024 * 1024 * 1024; // arbitrary
  91. CHECK_OK("File size");
  92. ASSERT(sz < 1024 * 1024 * 1024);
  93. u32 wave;
  94. stream >> wave;
  95. ok = ok && wave == 0x45564157; // "WAVE"
  96. CHECK_OK("WAVE header");
  97. u32 fmt_id;
  98. stream >> fmt_id;
  99. ok = ok && fmt_id == 0x20746D66; // "FMT"
  100. CHECK_OK("FMT header");
  101. u32 fmt_size;
  102. stream >> fmt_size;
  103. ok = ok && fmt_size == 16;
  104. CHECK_OK("FMT size");
  105. ASSERT(fmt_size == 16);
  106. u16 audio_format;
  107. stream >> audio_format;
  108. CHECK_OK("Audio format"); // incomplete read check
  109. ok = ok && audio_format == 1; // WAVE_FORMAT_PCM
  110. ASSERT(audio_format == 1);
  111. CHECK_OK("Audio format"); // value check
  112. stream >> m_num_channels;
  113. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  114. CHECK_OK("Channel count");
  115. stream >> m_sample_rate;
  116. CHECK_OK("Sample rate");
  117. u32 byte_rate;
  118. stream >> byte_rate;
  119. CHECK_OK("Byte rate");
  120. u16 block_align;
  121. stream >> block_align;
  122. CHECK_OK("Block align");
  123. stream >> m_bits_per_sample;
  124. CHECK_OK("Bits per sample"); // incomplete read check
  125. ok = ok && (m_bits_per_sample == 8 || m_bits_per_sample == 16 || m_bits_per_sample == 24);
  126. ASSERT(m_bits_per_sample == 8 || m_bits_per_sample == 16 || m_bits_per_sample == 24);
  127. CHECK_OK("Bits per sample"); // value check
  128. // Read chunks until we find DATA
  129. bool found_data = false;
  130. u32 data_sz = 0;
  131. while (true) {
  132. u32 chunk_id;
  133. stream >> chunk_id;
  134. CHECK_OK("Reading chunk ID searching for data");
  135. stream >> data_sz;
  136. CHECK_OK("Reading chunk size searching for data");
  137. if (chunk_id == 0x61746164) { // DATA
  138. found_data = true;
  139. break;
  140. }
  141. }
  142. ok = ok && found_data;
  143. CHECK_OK("Found no data chunk");
  144. ASSERT(found_data);
  145. ok = ok && data_sz < INT32_MAX;
  146. CHECK_OK("Data was too large");
  147. int bytes_per_sample = (m_bits_per_sample / 8) * m_num_channels;
  148. m_total_samples = data_sz / bytes_per_sample;
  149. // Just make sure we're good before we read the data...
  150. ASSERT(!stream.handle_read_failure());
  151. return true;
  152. }
  153. AResampleHelper::AResampleHelper(float source, float target)
  154. : m_ratio(source / target)
  155. {
  156. }
  157. void AResampleHelper::process_sample(float sample_l, float sample_r)
  158. {
  159. m_last_sample_l = sample_l;
  160. m_last_sample_r = sample_r;
  161. m_current_ratio += 1;
  162. }
  163. bool AResampleHelper::read_sample(float& next_l, float& next_r)
  164. {
  165. if (m_current_ratio > 0) {
  166. m_current_ratio -= m_ratio;
  167. next_l = m_last_sample_l;
  168. next_r = m_last_sample_r;
  169. return true;
  170. }
  171. return false;
  172. }
  173. template<typename SampleReader>
  174. static void read_samples_from_stream(BufferStream& stream, SampleReader read_sample, Vector<ASample>& samples, AResampleHelper& resampler, int num_channels)
  175. {
  176. float norm_l = 0;
  177. float norm_r = 0;
  178. switch (num_channels) {
  179. case 1:
  180. for (;;) {
  181. while (resampler.read_sample(norm_l, norm_r)) {
  182. samples.append(ASample(norm_l));
  183. }
  184. norm_l = read_sample(stream);
  185. if (stream.handle_read_failure()) {
  186. break;
  187. }
  188. resampler.process_sample(norm_l, norm_r);
  189. }
  190. break;
  191. case 2:
  192. for (;;) {
  193. while (resampler.read_sample(norm_l, norm_r)) {
  194. samples.append(ASample(norm_l, norm_r));
  195. }
  196. norm_l = read_sample(stream);
  197. norm_r = read_sample(stream);
  198. if (stream.handle_read_failure()) {
  199. break;
  200. }
  201. resampler.process_sample(norm_l, norm_r);
  202. }
  203. break;
  204. default:
  205. ASSERT_NOT_REACHED();
  206. }
  207. }
  208. static float read_norm_sample_24(BufferStream& stream)
  209. {
  210. u8 byte = 0;
  211. stream >> byte;
  212. u32 sample1 = byte;
  213. stream >> byte;
  214. u32 sample2 = byte;
  215. stream >> byte;
  216. u32 sample3 = byte;
  217. i32 value = 0;
  218. value = sample1 << 8;
  219. value |= (sample2 << 16);
  220. value |= (sample3 << 24);
  221. return float(value) / std::numeric_limits<i32>::max();
  222. }
  223. static float read_norm_sample_16(BufferStream& stream)
  224. {
  225. i16 sample = 0;
  226. stream >> sample;
  227. return float(sample) / std::numeric_limits<i16>::max();
  228. }
  229. static float read_norm_sample_8(BufferStream& stream)
  230. {
  231. u8 sample = 0;
  232. stream >> sample;
  233. return float(sample) / std::numeric_limits<u8>::max();
  234. }
  235. // ### can't const this because BufferStream is non-const
  236. // perhaps we need a reading class separate from the writing one, that can be
  237. // entirely consted.
  238. RefPtr<ABuffer> ABuffer::from_pcm_data(ByteBuffer& data, AResampleHelper& resampler, int num_channels, int bits_per_sample)
  239. {
  240. BufferStream stream(data);
  241. Vector<ASample> fdata;
  242. fdata.ensure_capacity(data.size() / (bits_per_sample / 8));
  243. #ifdef AWAVLOADER_DEBUG
  244. dbg() << "Reading " << bits_per_sample << " bits and " << num_channels << " channels, total bytes: " << data.size();
  245. #endif
  246. switch (bits_per_sample) {
  247. case 8:
  248. read_samples_from_stream(stream, read_norm_sample_8, fdata, resampler, num_channels);
  249. break;
  250. case 16:
  251. read_samples_from_stream(stream, read_norm_sample_16, fdata, resampler, num_channels);
  252. break;
  253. case 24:
  254. read_samples_from_stream(stream, read_norm_sample_24, fdata, resampler, num_channels);
  255. break;
  256. default:
  257. ASSERT_NOT_REACHED();
  258. }
  259. // We should handle this in a better way above, but for now --
  260. // just make sure we're good. Worst case we just write some 0s where they
  261. // don't belong.
  262. ASSERT(!stream.handle_read_failure());
  263. return ABuffer::create_with_samples(move(fdata));
  264. }