wave.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 1999-2007 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include "wave.h"
  22. #include <algorithm>
  23. #include <atomic>
  24. #include <cerrno>
  25. #include <chrono>
  26. #include <cstdint>
  27. #include <cstdio>
  28. #include <cstring>
  29. #include <exception>
  30. #include <system_error>
  31. #include <thread>
  32. #include <vector>
  33. #include "albit.h"
  34. #include "alc/alconfig.h"
  35. #include "almalloc.h"
  36. #include "alnumeric.h"
  37. #include "althrd_setname.h"
  38. #include "core/device.h"
  39. #include "core/logging.h"
  40. #include "strutils.h"
  41. namespace {
  42. using namespace std::string_view_literals;
  43. using std::chrono::seconds;
  44. using std::chrono::milliseconds;
  45. using std::chrono::nanoseconds;
  46. using ubyte = unsigned char;
  47. using ushort = unsigned short;
  48. struct FileDeleter {
  49. void operator()(gsl::owner<FILE*> f) { fclose(f); }
  50. };
  51. using FilePtr = std::unique_ptr<FILE,FileDeleter>;
  52. [[nodiscard]] constexpr auto GetDeviceName() noexcept { return "Wave File Writer"sv; }
  53. constexpr std::array<ubyte,16> SUBTYPE_PCM{{
  54. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
  55. 0x00, 0x38, 0x9b, 0x71
  56. }};
  57. constexpr std::array<ubyte,16> SUBTYPE_FLOAT{{
  58. 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
  59. 0x00, 0x38, 0x9b, 0x71
  60. }};
  61. constexpr std::array<ubyte,16> SUBTYPE_BFORMAT_PCM{{
  62. 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
  63. 0xca, 0x00, 0x00, 0x00
  64. }};
  65. constexpr std::array<ubyte,16> SUBTYPE_BFORMAT_FLOAT{{
  66. 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
  67. 0xca, 0x00, 0x00, 0x00
  68. }};
  69. void fwrite16le(ushort val, FILE *f)
  70. {
  71. std::array data{static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff)};
  72. fwrite(data.data(), 1, data.size(), f);
  73. }
  74. void fwrite32le(uint val, FILE *f)
  75. {
  76. std::array data{static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff),
  77. static_cast<ubyte>((val>>16)&0xff), static_cast<ubyte>((val>>24)&0xff)};
  78. fwrite(data.data(), 1, data.size(), f);
  79. }
  80. struct WaveBackend final : public BackendBase {
  81. explicit WaveBackend(DeviceBase *device) noexcept : BackendBase{device} { }
  82. ~WaveBackend() override;
  83. int mixerProc();
  84. void open(std::string_view name) override;
  85. bool reset() override;
  86. void start() override;
  87. void stop() override;
  88. FilePtr mFile{nullptr};
  89. long mDataStart{-1};
  90. std::vector<std::byte> mBuffer;
  91. std::atomic<bool> mKillNow{true};
  92. std::thread mThread;
  93. };
  94. WaveBackend::~WaveBackend() = default;
  95. int WaveBackend::mixerProc()
  96. {
  97. const milliseconds restTime{mDevice->mUpdateSize*1000/mDevice->mSampleRate / 2};
  98. althrd_setname(GetMixerThreadName());
  99. const size_t frameStep{mDevice->channelsFromFmt()};
  100. const size_t frameSize{mDevice->frameSizeFromFmt()};
  101. int64_t done{0};
  102. auto start = std::chrono::steady_clock::now();
  103. while(!mKillNow.load(std::memory_order_acquire)
  104. && mDevice->Connected.load(std::memory_order_acquire))
  105. {
  106. auto now = std::chrono::steady_clock::now();
  107. /* This converts from nanoseconds to nanosamples, then to samples. */
  108. const auto avail = int64_t{std::chrono::duration_cast<seconds>((now-start) *
  109. mDevice->mSampleRate).count()};
  110. if(avail-done < mDevice->mUpdateSize)
  111. {
  112. std::this_thread::sleep_for(restTime);
  113. continue;
  114. }
  115. while(avail-done >= mDevice->mUpdateSize)
  116. {
  117. mDevice->renderSamples(mBuffer.data(), mDevice->mUpdateSize, frameStep);
  118. done += mDevice->mUpdateSize;
  119. if(al::endian::native != al::endian::little)
  120. {
  121. const uint bytesize{mDevice->bytesFromFmt()};
  122. if(bytesize == 2)
  123. {
  124. const size_t len{mBuffer.size() & ~1_uz};
  125. for(size_t i{0};i < len;i+=2)
  126. std::swap(mBuffer[i], mBuffer[i+1]);
  127. }
  128. else if(bytesize == 4)
  129. {
  130. const size_t len{mBuffer.size() & ~3_uz};
  131. for(size_t i{0};i < len;i+=4)
  132. {
  133. std::swap(mBuffer[i ], mBuffer[i+3]);
  134. std::swap(mBuffer[i+1], mBuffer[i+2]);
  135. }
  136. }
  137. }
  138. const size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->mUpdateSize, mFile.get())};
  139. if(fs < mDevice->mUpdateSize || ferror(mFile.get()))
  140. {
  141. ERR("Error writing to file");
  142. mDevice->handleDisconnect("Failed to write playback samples");
  143. break;
  144. }
  145. }
  146. /* For every completed second, increment the start time and reduce the
  147. * samples done. This prevents the difference between the start time
  148. * and current time from growing too large, while maintaining the
  149. * correct number of samples to render.
  150. */
  151. if(done >= mDevice->mSampleRate)
  152. {
  153. seconds s{done/mDevice->mSampleRate};
  154. done %= mDevice->mSampleRate;
  155. start += s;
  156. }
  157. }
  158. return 0;
  159. }
  160. void WaveBackend::open(std::string_view name)
  161. {
  162. auto fname = ConfigValueStr({}, "wave", "file");
  163. if(!fname) throw al::backend_exception{al::backend_error::NoDevice,
  164. "No wave output filename"};
  165. if(name.empty())
  166. name = GetDeviceName();
  167. else if(name != GetDeviceName())
  168. throw al::backend_exception{al::backend_error::NoDevice, "Device name \"{}\" not found",
  169. name};
  170. /* There's only one "device", so if it's already open, we're done. */
  171. if(mFile) return;
  172. #ifdef _WIN32
  173. {
  174. std::wstring wname{utf8_to_wstr(fname.value())};
  175. mFile = FilePtr{_wfopen(wname.c_str(), L"wb")};
  176. }
  177. #else
  178. mFile = FilePtr{fopen(fname->c_str(), "wb")};
  179. #endif
  180. if(!mFile)
  181. throw al::backend_exception{al::backend_error::DeviceError, "Could not open file '{}': {}",
  182. *fname, std::generic_category().message(errno)};
  183. mDeviceName = name;
  184. }
  185. bool WaveBackend::reset()
  186. {
  187. if(GetConfigValueBool({}, "wave", "bformat", false))
  188. {
  189. mDevice->FmtChans = DevFmtAmbi3D;
  190. mDevice->mAmbiOrder = 1;
  191. }
  192. switch(mDevice->FmtType)
  193. {
  194. case DevFmtByte:
  195. mDevice->FmtType = DevFmtUByte;
  196. break;
  197. case DevFmtUShort:
  198. mDevice->FmtType = DevFmtShort;
  199. break;
  200. case DevFmtUInt:
  201. mDevice->FmtType = DevFmtInt;
  202. break;
  203. case DevFmtUByte:
  204. case DevFmtShort:
  205. case DevFmtInt:
  206. case DevFmtFloat:
  207. break;
  208. }
  209. auto chanmask = 0u;
  210. auto isbformat = false;
  211. switch(mDevice->FmtChans)
  212. {
  213. case DevFmtMono: chanmask = 0x04; break;
  214. case DevFmtStereo: chanmask = 0x01 | 0x02; break;
  215. case DevFmtQuad: chanmask = 0x01 | 0x02 | 0x10 | 0x20; break;
  216. case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break;
  217. case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break;
  218. case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
  219. case DevFmtX7144:
  220. mDevice->FmtChans = DevFmtX714;
  221. [[fallthrough]];
  222. case DevFmtX714:
  223. chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400 | 0x1000 | 0x4000
  224. | 0x8000 | 0x20000;
  225. break;
  226. /* NOTE: Same as 7.1. */
  227. case DevFmtX3D71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
  228. case DevFmtAmbi3D:
  229. /* .amb output requires FuMa */
  230. mDevice->mAmbiOrder = std::min(mDevice->mAmbiOrder, 3u);
  231. mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
  232. mDevice->mAmbiScale = DevAmbiScaling::FuMa;
  233. isbformat = true;
  234. chanmask = 0;
  235. break;
  236. }
  237. const auto bytes = mDevice->bytesFromFmt();
  238. const auto channels = mDevice->channelsFromFmt();
  239. if(fseek(mFile.get(), 0, SEEK_CUR) != 0)
  240. {
  241. /* ESPIPE means the underlying file isn't seekable, which is fine for
  242. * piped output.
  243. */
  244. if(auto errcode = errno; errcode != ESPIPE)
  245. {
  246. ERR("Failed to reset file offset: {} ({})", std::generic_category().message(errcode),
  247. errcode);
  248. }
  249. }
  250. clearerr(mFile.get());
  251. fputs("RIFF", mFile.get());
  252. fwrite32le(0xFFFFFFFF, mFile.get()); // 'RIFF' header len; filled in at stop
  253. fputs("WAVE", mFile.get());
  254. fputs("fmt ", mFile.get());
  255. fwrite32le(40, mFile.get()); // 'fmt ' header len; 40 bytes for EXTENSIBLE
  256. // 16-bit val, format type id (extensible: 0xFFFE)
  257. fwrite16le(0xFFFE, mFile.get());
  258. // 16-bit val, channel count
  259. fwrite16le(static_cast<ushort>(channels), mFile.get());
  260. // 32-bit val, frequency
  261. fwrite32le(mDevice->mSampleRate, mFile.get());
  262. // 32-bit val, bytes per second
  263. fwrite32le(mDevice->mSampleRate * channels * bytes, mFile.get());
  264. // 16-bit val, frame size
  265. fwrite16le(static_cast<ushort>(channels * bytes), mFile.get());
  266. // 16-bit val, bits per sample
  267. fwrite16le(static_cast<ushort>(bytes * 8), mFile.get());
  268. // 16-bit val, extra byte count
  269. fwrite16le(22, mFile.get());
  270. // 16-bit val, valid bits per sample
  271. fwrite16le(static_cast<ushort>(bytes * 8), mFile.get());
  272. // 32-bit val, channel mask
  273. fwrite32le(chanmask, mFile.get());
  274. // 16 byte GUID, sub-type format
  275. std::ignore = fwrite((mDevice->FmtType == DevFmtFloat) ?
  276. (isbformat ? SUBTYPE_BFORMAT_FLOAT.data() : SUBTYPE_FLOAT.data()) :
  277. (isbformat ? SUBTYPE_BFORMAT_PCM.data() : SUBTYPE_PCM.data()), 1, 16, mFile.get());
  278. fputs("data", mFile.get());
  279. fwrite32le(0xFFFFFFFF, mFile.get()); // 'data' header len; filled in at stop
  280. if(ferror(mFile.get()))
  281. {
  282. ERR("Error writing header: {}", std::generic_category().message(errno));
  283. return false;
  284. }
  285. mDataStart = ftell(mFile.get());
  286. setDefaultWFXChannelOrder();
  287. const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->mUpdateSize};
  288. mBuffer.resize(bufsize);
  289. return true;
  290. }
  291. void WaveBackend::start()
  292. {
  293. if(mDataStart > 0 && fseek(mFile.get(), 0, SEEK_END) != 0)
  294. WARN("Failed to seek on output file");
  295. try {
  296. mKillNow.store(false, std::memory_order_release);
  297. mThread = std::thread{&WaveBackend::mixerProc, this};
  298. }
  299. catch(std::exception& e) {
  300. throw al::backend_exception{al::backend_error::DeviceError,
  301. "Failed to start mixing thread: {}", e.what()};
  302. }
  303. }
  304. void WaveBackend::stop()
  305. {
  306. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  307. return;
  308. mThread.join();
  309. if(mDataStart > 0)
  310. {
  311. long size{ftell(mFile.get())};
  312. if(size > 0)
  313. {
  314. long dataLen{size - mDataStart};
  315. if(fseek(mFile.get(), 4, SEEK_SET) == 0)
  316. fwrite32le(static_cast<uint>(size-8), mFile.get()); // 'WAVE' header len
  317. if(fseek(mFile.get(), mDataStart-4, SEEK_SET) == 0)
  318. fwrite32le(static_cast<uint>(dataLen), mFile.get()); // 'data' header len
  319. }
  320. }
  321. }
  322. } // namespace
  323. bool WaveBackendFactory::init()
  324. { return true; }
  325. bool WaveBackendFactory::querySupport(BackendType type)
  326. { return type == BackendType::Playback; }
  327. auto WaveBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
  328. {
  329. switch(type)
  330. {
  331. case BackendType::Playback:
  332. return std::vector{std::string{GetDeviceName()}};
  333. case BackendType::Capture:
  334. break;
  335. }
  336. return {};
  337. }
  338. BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
  339. {
  340. if(type == BackendType::Playback)
  341. return BackendPtr{new WaveBackend{device}};
  342. return nullptr;
  343. }
  344. BackendFactory &WaveBackendFactory::getFactory()
  345. {
  346. static WaveBackendFactory factory{};
  347. return factory;
  348. }