wave.cpp 12 KB

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