WavLoader.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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/NumericLimits.h>
  27. #include <AK/OwnPtr.h>
  28. #include <LibAudio/Buffer.h>
  29. #include <LibAudio/WavLoader.h>
  30. #include <LibCore/File.h>
  31. #include <LibCore/IODeviceStreamReader.h>
  32. namespace Audio {
  33. WavLoaderPlugin::WavLoaderPlugin(const StringView& path)
  34. : m_file(Core::File::construct(path))
  35. {
  36. if (!m_file->open(Core::IODevice::ReadOnly)) {
  37. m_error_string = String::formatted("Can't open file: {}", m_file->error_string());
  38. return;
  39. }
  40. valid = parse_header();
  41. if (!valid)
  42. return;
  43. m_resampler = make<ResampleHelper>(m_sample_rate, 44100);
  44. }
  45. WavLoaderPlugin::WavLoaderPlugin(const ByteBuffer& buffer)
  46. {
  47. m_stream = make<InputMemoryStream>(buffer);
  48. if (!m_stream) {
  49. m_error_string = String::formatted("Can't open memory stream");
  50. return;
  51. }
  52. valid = parse_header();
  53. if (!valid)
  54. return;
  55. m_resampler = make<ResampleHelper>(m_sample_rate, 44100);
  56. }
  57. bool WavLoaderPlugin::sniff()
  58. {
  59. return valid;
  60. }
  61. RefPtr<Buffer> WavLoaderPlugin::get_more_samples(size_t max_bytes_to_read_from_input)
  62. {
  63. #ifdef AWAVLOADER_DEBUG
  64. dbgln("Read WAV of format PCM with num_channels {} sample rate {}, bits per sample {}", m_num_channels, m_sample_rate, m_bits_per_sample);
  65. #endif
  66. size_t samples_to_read = static_cast<int>(max_bytes_to_read_from_input) / (m_num_channels * (m_bits_per_sample / 8));
  67. RefPtr<Buffer> buffer;
  68. if (m_file) {
  69. auto raw_samples = m_file->read(max_bytes_to_read_from_input);
  70. if (raw_samples.is_empty())
  71. return nullptr;
  72. buffer = Buffer::from_pcm_data(raw_samples, *m_resampler, m_num_channels, m_bits_per_sample);
  73. } else {
  74. buffer = Buffer::from_pcm_stream(*m_stream, *m_resampler, m_num_channels, m_bits_per_sample, samples_to_read);
  75. }
  76. //Buffer contains normalized samples, but m_loaded_samples should contain the amount of actually loaded samples
  77. m_loaded_samples += samples_to_read;
  78. m_loaded_samples = min(m_total_samples, m_loaded_samples);
  79. return buffer;
  80. }
  81. void WavLoaderPlugin::seek(const int position)
  82. {
  83. if (position < 0 || position > m_total_samples)
  84. return;
  85. m_loaded_samples = position;
  86. size_t byte_position = position * m_num_channels * (m_bits_per_sample / 8);
  87. if (m_file)
  88. m_file->seek(byte_position);
  89. else
  90. m_stream->seek(byte_position);
  91. }
  92. void WavLoaderPlugin::reset()
  93. {
  94. seek(0);
  95. }
  96. bool WavLoaderPlugin::parse_header()
  97. {
  98. OwnPtr<Core::IODeviceStreamReader> file_stream;
  99. bool ok = true;
  100. if (m_file)
  101. file_stream = make<Core::IODeviceStreamReader>(*m_file);
  102. auto read_u8 = [&]() -> u8 {
  103. u8 value;
  104. if (m_file) {
  105. *file_stream >> value;
  106. if (file_stream->handle_read_failure())
  107. ok = false;
  108. } else {
  109. *m_stream >> value;
  110. if (m_stream->has_any_error())
  111. ok = false;
  112. }
  113. return value;
  114. };
  115. auto read_u16 = [&]() -> u16 {
  116. u16 value;
  117. if (m_file) {
  118. *file_stream >> value;
  119. if (file_stream->handle_read_failure())
  120. ok = false;
  121. } else {
  122. *m_stream >> value;
  123. if (m_stream->has_any_error())
  124. ok = false;
  125. }
  126. return value;
  127. };
  128. auto read_u32 = [&]() -> u32 {
  129. u32 value;
  130. if (m_file) {
  131. *file_stream >> value;
  132. if (file_stream->handle_read_failure())
  133. ok = false;
  134. } else {
  135. *m_stream >> value;
  136. if (m_stream->has_any_error())
  137. ok = false;
  138. }
  139. return value;
  140. };
  141. #define CHECK_OK(msg) \
  142. do { \
  143. if (!ok) { \
  144. m_error_string = String::formatted("Parsing failed: {}", msg); \
  145. return {}; \
  146. } \
  147. } while (0);
  148. u32 riff = read_u32();
  149. ok = ok && riff == 0x46464952; // "RIFF"
  150. CHECK_OK("RIFF header");
  151. u32 sz = read_u32();
  152. ok = ok && sz < 1024 * 1024 * 1024; // arbitrary
  153. CHECK_OK("File size");
  154. ASSERT(sz < 1024 * 1024 * 1024);
  155. u32 wave = read_u32();
  156. ok = ok && wave == 0x45564157; // "WAVE"
  157. CHECK_OK("WAVE header");
  158. u32 fmt_id = read_u32();
  159. ok = ok && fmt_id == 0x20746D66; // "FMT"
  160. CHECK_OK("FMT header");
  161. u32 fmt_size = read_u32();
  162. ok = ok && fmt_size == 16;
  163. CHECK_OK("FMT size");
  164. ASSERT(fmt_size == 16);
  165. u16 audio_format = read_u16();
  166. CHECK_OK("Audio format"); // incomplete read check
  167. ok = ok && audio_format == 1; // WAVE_FORMAT_PCM
  168. ASSERT(audio_format == 1);
  169. CHECK_OK("Audio format"); // value check
  170. m_num_channels = read_u16();
  171. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  172. CHECK_OK("Channel count");
  173. m_sample_rate = read_u32();
  174. CHECK_OK("Sample rate");
  175. read_u32();
  176. CHECK_OK("Byte rate");
  177. read_u16();
  178. CHECK_OK("Block align");
  179. m_bits_per_sample = read_u16();
  180. CHECK_OK("Bits per sample"); // incomplete read check
  181. ok = ok && (m_bits_per_sample == 8 || m_bits_per_sample == 16 || m_bits_per_sample == 24);
  182. ASSERT(m_bits_per_sample == 8 || m_bits_per_sample == 16 || m_bits_per_sample == 24);
  183. CHECK_OK("Bits per sample"); // value check
  184. // Read chunks until we find DATA
  185. bool found_data = false;
  186. u32 data_sz = 0;
  187. u8 search_byte = 0;
  188. while (true) {
  189. search_byte = read_u8();
  190. CHECK_OK("Reading byte searching for data");
  191. if (search_byte != 0x64) //D
  192. continue;
  193. search_byte = read_u8();
  194. CHECK_OK("Reading next byte searching for data");
  195. if (search_byte != 0x61) //A
  196. continue;
  197. u16 search_remaining = read_u16();
  198. CHECK_OK("Reading remaining bytes searching for data");
  199. if (search_remaining != 0x6174) //TA
  200. continue;
  201. data_sz = read_u32();
  202. found_data = true;
  203. break;
  204. }
  205. ok = ok && found_data;
  206. CHECK_OK("Found no data chunk");
  207. ASSERT(found_data);
  208. ok = ok && data_sz < INT32_MAX;
  209. CHECK_OK("Data was too large");
  210. int bytes_per_sample = (m_bits_per_sample / 8) * m_num_channels;
  211. m_total_samples = data_sz / bytes_per_sample;
  212. return true;
  213. }
  214. ResampleHelper::ResampleHelper(double source, double target)
  215. : m_ratio(source / target)
  216. {
  217. }
  218. void ResampleHelper::process_sample(double sample_l, double sample_r)
  219. {
  220. m_last_sample_l = sample_l;
  221. m_last_sample_r = sample_r;
  222. m_current_ratio += 1;
  223. }
  224. bool ResampleHelper::read_sample(double& next_l, double& next_r)
  225. {
  226. if (m_current_ratio > 0) {
  227. m_current_ratio -= m_ratio;
  228. next_l = m_last_sample_l;
  229. next_r = m_last_sample_r;
  230. return true;
  231. }
  232. return false;
  233. }
  234. }