WavLoader.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. ByteBuffer sample_data = ByteBuffer::create_zeroed(bytes_to_read);
  60. m_stream->read_or_error(sample_data.bytes());
  61. if (m_stream->handle_any_error()) {
  62. return nullptr;
  63. }
  64. RefPtr<Buffer> buffer = Buffer::from_pcm_data(
  65. sample_data.bytes(),
  66. m_num_channels,
  67. m_sample_format);
  68. // m_loaded_samples should contain the amount of actually loaded samples
  69. m_loaded_samples += samples_to_read;
  70. return buffer;
  71. }
  72. void WavLoaderPlugin::seek(const int sample_index)
  73. {
  74. dbgln_if(AWAVLOADER_DEBUG, "seek sample_index {}", sample_index);
  75. if (sample_index < 0 || sample_index >= m_total_samples)
  76. return;
  77. size_t sample_offset = m_byte_offset_of_data_samples + (sample_index * m_num_channels * (pcm_bits_per_sample(m_sample_format) / 8));
  78. // AK::InputStream does not define seek, hence the special-cases for file and stream.
  79. if (m_file) {
  80. m_file->seek(sample_offset);
  81. } else {
  82. m_memory_stream->seek(sample_offset);
  83. }
  84. m_loaded_samples = sample_index;
  85. }
  86. // Specification reference: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  87. bool WavLoaderPlugin::parse_header()
  88. {
  89. if (!m_stream)
  90. return false;
  91. bool ok = true;
  92. size_t bytes_read = 0;
  93. auto read_u8 = [&]() -> u8 {
  94. u8 value;
  95. *m_stream >> value;
  96. if (m_stream->handle_any_error())
  97. ok = false;
  98. bytes_read += 1;
  99. return value;
  100. };
  101. auto read_u16 = [&]() -> u16 {
  102. u16 value;
  103. *m_stream >> value;
  104. if (m_stream->handle_any_error())
  105. ok = false;
  106. bytes_read += 2;
  107. return value;
  108. };
  109. auto read_u32 = [&]() -> u32 {
  110. u32 value;
  111. *m_stream >> value;
  112. if (m_stream->handle_any_error())
  113. ok = false;
  114. bytes_read += 4;
  115. return value;
  116. };
  117. #define CHECK_OK(msg) \
  118. do { \
  119. if (!ok) { \
  120. m_error_string = String::formatted("Parsing failed: {}", msg); \
  121. dbgln_if(AWAVLOADER_DEBUG, m_error_string); \
  122. return {}; \
  123. } \
  124. } while (0)
  125. u32 riff = read_u32();
  126. ok = ok && riff == 0x46464952; // "RIFF"
  127. CHECK_OK("RIFF header");
  128. u32 sz = read_u32();
  129. ok = ok && sz < maximum_wav_size;
  130. CHECK_OK("File size");
  131. u32 wave = read_u32();
  132. ok = ok && wave == 0x45564157; // "WAVE"
  133. CHECK_OK("WAVE header");
  134. u32 fmt_id = read_u32();
  135. ok = ok && fmt_id == 0x20746D66; // "fmt "
  136. CHECK_OK("FMT header");
  137. u32 fmt_size = read_u32();
  138. ok = ok && (fmt_size == 16 || fmt_size == 18 || fmt_size == 40);
  139. CHECK_OK("FMT size");
  140. u16 audio_format = read_u16();
  141. CHECK_OK("Audio format"); // incomplete read check
  142. ok = ok && (audio_format == WAVE_FORMAT_PCM || audio_format == WAVE_FORMAT_IEEE_FLOAT || audio_format == WAVE_FORMAT_EXTENSIBLE);
  143. CHECK_OK("Audio format PCM/Float"); // value check
  144. m_num_channels = read_u16();
  145. ok = ok && (m_num_channels == 1 || m_num_channels == 2);
  146. CHECK_OK("Channel count");
  147. m_sample_rate = read_u32();
  148. CHECK_OK("Sample rate");
  149. read_u32();
  150. CHECK_OK("Data rate");
  151. u16 block_size_bytes = read_u16();
  152. CHECK_OK("Block size");
  153. u16 bits_per_sample = read_u16();
  154. CHECK_OK("Bits per sample");
  155. if (audio_format == WAVE_FORMAT_EXTENSIBLE) {
  156. ok = ok && (fmt_size == 40);
  157. CHECK_OK("Extensible fmt size"); // value check
  158. // Discard everything until the GUID.
  159. // We've already read 16 bytes from the stream. The GUID starts in another 8 bytes.
  160. read_u32();
  161. read_u32();
  162. CHECK_OK("Discard until GUID");
  163. // Get the underlying audio format from the first two bytes of GUID
  164. u16 guid_subformat = read_u16();
  165. ok = ok && (guid_subformat == WAVE_FORMAT_PCM || guid_subformat == WAVE_FORMAT_IEEE_FLOAT);
  166. CHECK_OK("GUID SubFormat");
  167. audio_format = guid_subformat;
  168. }
  169. if (audio_format == WAVE_FORMAT_PCM) {
  170. ok = ok && (bits_per_sample == 8 || bits_per_sample == 16 || bits_per_sample == 24);
  171. CHECK_OK("Bits per sample (PCM)"); // value check
  172. // We only support 8-24 bit audio right now because other formats are uncommon
  173. if (bits_per_sample == 8) {
  174. m_sample_format = PcmSampleFormat::Uint8;
  175. } else if (bits_per_sample == 16) {
  176. m_sample_format = PcmSampleFormat::Int16;
  177. } else if (bits_per_sample == 24) {
  178. m_sample_format = PcmSampleFormat::Int24;
  179. }
  180. } else if (audio_format == WAVE_FORMAT_IEEE_FLOAT) {
  181. ok = ok && (bits_per_sample == 32 || bits_per_sample == 64);
  182. CHECK_OK("Bits per sample (Float)"); // value check
  183. // Again, only the common 32 and 64 bit
  184. if (bits_per_sample == 32) {
  185. m_sample_format = PcmSampleFormat::Float32;
  186. } else if (bits_per_sample == 64) {
  187. m_sample_format = PcmSampleFormat::Float64;
  188. }
  189. }
  190. ok = ok && (block_size_bytes == (m_num_channels * (bits_per_sample / 8)));
  191. CHECK_OK("Block size sanity check");
  192. dbgln_if(AWAVLOADER_DEBUG, "WAV format {} at {} bit, {} channels, rate {}Hz ",
  193. sample_format_name(m_sample_format), pcm_bits_per_sample(m_sample_format), m_num_channels, m_sample_rate);
  194. // Read chunks until we find DATA
  195. bool found_data = false;
  196. u32 data_sz = 0;
  197. u8 search_byte = 0;
  198. while (true) {
  199. search_byte = read_u8();
  200. CHECK_OK("Reading byte searching for data");
  201. if (search_byte != 0x64) //D
  202. continue;
  203. search_byte = read_u8();
  204. CHECK_OK("Reading next byte searching for data");
  205. if (search_byte != 0x61) //A
  206. continue;
  207. u16 search_remaining = read_u16();
  208. CHECK_OK("Reading remaining bytes searching for data");
  209. if (search_remaining != 0x6174) //TA
  210. continue;
  211. data_sz = read_u32();
  212. found_data = true;
  213. break;
  214. }
  215. ok = ok && found_data;
  216. CHECK_OK("Found no data chunk");
  217. ok = ok && data_sz < maximum_wav_size;
  218. CHECK_OK("Data was too large");
  219. m_total_samples = data_sz / block_size_bytes;
  220. dbgln_if(AWAVLOADER_DEBUG, "WAV data size {}, bytes per sample {}, total samples {}",
  221. data_sz,
  222. block_size_bytes,
  223. m_total_samples);
  224. m_byte_offset_of_data_samples = bytes_read;
  225. return true;
  226. }
  227. }