WavLoader.cpp 8.4 KB

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