🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

401 lines
11 KiB

  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 <thread>
  32. #include "albit.h"
  33. #include "albyte.h"
  34. #include "alc/alconfig.h"
  35. #include "almalloc.h"
  36. #include "alnumeric.h"
  37. #include "core/device.h"
  38. #include "core/helpers.h"
  39. #include "core/logging.h"
  40. #include "opthelpers.h"
  41. #include "strutils.h"
  42. #include "threads.h"
  43. #include "vector.h"
  44. namespace {
  45. using std::chrono::seconds;
  46. using std::chrono::milliseconds;
  47. using std::chrono::nanoseconds;
  48. using ubyte = unsigned char;
  49. using ushort = unsigned short;
  50. constexpr char waveDevice[] = "Wave File Writer";
  51. constexpr ubyte SUBTYPE_PCM[]{
  52. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
  53. 0x00, 0x38, 0x9b, 0x71
  54. };
  55. constexpr ubyte SUBTYPE_FLOAT[]{
  56. 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
  57. 0x00, 0x38, 0x9b, 0x71
  58. };
  59. constexpr ubyte SUBTYPE_BFORMAT_PCM[]{
  60. 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
  61. 0xca, 0x00, 0x00, 0x00
  62. };
  63. constexpr ubyte SUBTYPE_BFORMAT_FLOAT[]{
  64. 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
  65. 0xca, 0x00, 0x00, 0x00
  66. };
  67. void fwrite16le(ushort val, FILE *f)
  68. {
  69. ubyte data[2]{ static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff) };
  70. fwrite(data, 1, 2, f);
  71. }
  72. void fwrite32le(uint val, FILE *f)
  73. {
  74. ubyte data[4]{ static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff),
  75. static_cast<ubyte>((val>>16)&0xff), static_cast<ubyte>((val>>24)&0xff) };
  76. fwrite(data, 1, 4, f);
  77. }
  78. struct WaveBackend final : public BackendBase {
  79. WaveBackend(DeviceBase *device) noexcept : BackendBase{device} { }
  80. ~WaveBackend() override;
  81. int mixerProc();
  82. void open(const char *name) override;
  83. bool reset() override;
  84. void start() override;
  85. void stop() override;
  86. FILE *mFile{nullptr};
  87. long mDataStart{-1};
  88. al::vector<al::byte> mBuffer;
  89. std::atomic<bool> mKillNow{true};
  90. std::thread mThread;
  91. DEF_NEWDEL(WaveBackend)
  92. };
  93. WaveBackend::~WaveBackend()
  94. {
  95. if(mFile)
  96. fclose(mFile);
  97. mFile = nullptr;
  98. }
  99. int WaveBackend::mixerProc()
  100. {
  101. const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2};
  102. althrd_setname(MIXER_THREAD_NAME);
  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() & ~size_t{1}};
  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() & ~size_t{3}};
  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)};
  143. if(fs < mDevice->UpdateSize || ferror(mFile))
  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(const char *name)
  165. {
  166. auto fname = ConfigValueStr(nullptr, "wave", "file");
  167. if(!fname) throw al::backend_exception{al::backend_error::NoDevice,
  168. "No wave output filename"};
  169. if(!name)
  170. name = waveDevice;
  171. else if(strcmp(name, waveDevice) != 0)
  172. throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
  173. name};
  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->c_str())};
  179. mFile = _wfopen(wname.c_str(), L"wb");
  180. }
  181. #else
  182. mFile = 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(), strerror(errno)};
  187. mDevice->DeviceName = name;
  188. }
  189. bool WaveBackend::reset()
  190. {
  191. uint channels{0}, bytes{0}, chanmask{0};
  192. bool isbformat{false};
  193. size_t val;
  194. fseek(mFile, 0, SEEK_SET);
  195. clearerr(mFile);
  196. if(GetConfigValueBool(nullptr, "wave", "bformat", 0))
  197. {
  198. mDevice->FmtChans = DevFmtAmbi3D;
  199. mDevice->mAmbiOrder = 1;
  200. }
  201. switch(mDevice->FmtType)
  202. {
  203. case DevFmtByte:
  204. mDevice->FmtType = DevFmtUByte;
  205. break;
  206. case DevFmtUShort:
  207. mDevice->FmtType = DevFmtShort;
  208. break;
  209. case DevFmtUInt:
  210. mDevice->FmtType = DevFmtInt;
  211. break;
  212. case DevFmtUByte:
  213. case DevFmtShort:
  214. case DevFmtInt:
  215. case DevFmtFloat:
  216. break;
  217. }
  218. switch(mDevice->FmtChans)
  219. {
  220. case DevFmtMono: chanmask = 0x04; break;
  221. case DevFmtStereo: chanmask = 0x01 | 0x02; break;
  222. case DevFmtQuad: chanmask = 0x01 | 0x02 | 0x10 | 0x20; break;
  223. case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break;
  224. case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break;
  225. case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
  226. case DevFmtAmbi3D:
  227. /* .amb output requires FuMa */
  228. mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3);
  229. mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
  230. mDevice->mAmbiScale = DevAmbiScaling::FuMa;
  231. isbformat = true;
  232. chanmask = 0;
  233. break;
  234. }
  235. bytes = mDevice->bytesFromFmt();
  236. channels = mDevice->channelsFromFmt();
  237. rewind(mFile);
  238. fputs("RIFF", mFile);
  239. fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close
  240. fputs("WAVE", mFile);
  241. fputs("fmt ", mFile);
  242. fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE
  243. // 16-bit val, format type id (extensible: 0xFFFE)
  244. fwrite16le(0xFFFE, mFile);
  245. // 16-bit val, channel count
  246. fwrite16le(static_cast<ushort>(channels), mFile);
  247. // 32-bit val, frequency
  248. fwrite32le(mDevice->Frequency, mFile);
  249. // 32-bit val, bytes per second
  250. fwrite32le(mDevice->Frequency * channels * bytes, mFile);
  251. // 16-bit val, frame size
  252. fwrite16le(static_cast<ushort>(channels * bytes), mFile);
  253. // 16-bit val, bits per sample
  254. fwrite16le(static_cast<ushort>(bytes * 8), mFile);
  255. // 16-bit val, extra byte count
  256. fwrite16le(22, mFile);
  257. // 16-bit val, valid bits per sample
  258. fwrite16le(static_cast<ushort>(bytes * 8), mFile);
  259. // 32-bit val, channel mask
  260. fwrite32le(chanmask, mFile);
  261. // 16 byte GUID, sub-type format
  262. val = fwrite((mDevice->FmtType == DevFmtFloat) ?
  263. (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) :
  264. (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile);
  265. (void)val;
  266. fputs("data", mFile);
  267. fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close
  268. if(ferror(mFile))
  269. {
  270. ERR("Error writing header: %s\n", strerror(errno));
  271. return false;
  272. }
  273. mDataStart = ftell(mFile);
  274. setDefaultWFXChannelOrder();
  275. const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
  276. mBuffer.resize(bufsize);
  277. return true;
  278. }
  279. void WaveBackend::start()
  280. {
  281. if(mDataStart > 0 && fseek(mFile, 0, SEEK_END) != 0)
  282. WARN("Failed to seek on output file\n");
  283. try {
  284. mKillNow.store(false, std::memory_order_release);
  285. mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
  286. }
  287. catch(std::exception& e) {
  288. throw al::backend_exception{al::backend_error::DeviceError,
  289. "Failed to start mixing thread: %s", e.what()};
  290. }
  291. }
  292. void WaveBackend::stop()
  293. {
  294. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  295. return;
  296. mThread.join();
  297. if(mDataStart > 0)
  298. {
  299. long size{ftell(mFile)};
  300. if(size > 0)
  301. {
  302. long dataLen{size - mDataStart};
  303. if(fseek(mFile, 4, SEEK_SET) == 0)
  304. fwrite32le(static_cast<uint>(size-8), mFile); // 'WAVE' header len
  305. if(fseek(mFile, mDataStart-4, SEEK_SET) == 0)
  306. fwrite32le(static_cast<uint>(dataLen), mFile); // 'data' header len
  307. }
  308. }
  309. }
  310. } // namespace
  311. bool WaveBackendFactory::init()
  312. { return true; }
  313. bool WaveBackendFactory::querySupport(BackendType type)
  314. { return type == BackendType::Playback; }
  315. std::string WaveBackendFactory::probe(BackendType type)
  316. {
  317. std::string outnames;
  318. switch(type)
  319. {
  320. case BackendType::Playback:
  321. /* Includes null char. */
  322. outnames.append(waveDevice, sizeof(waveDevice));
  323. break;
  324. case BackendType::Capture:
  325. break;
  326. }
  327. return outnames;
  328. }
  329. BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
  330. {
  331. if(type == BackendType::Playback)
  332. return BackendPtr{new WaveBackend{device}};
  333. return nullptr;
  334. }
  335. BackendFactory &WaveBackendFactory::getFactory()
  336. {
  337. static WaveBackendFactory factory{};
  338. return factory;
  339. }