🛠️🐜 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.

403 lines
12 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. /* 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 = minu(mDevice->mAmbiOrder, 3);
  231. mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
  232. mDevice->mAmbiScale = DevAmbiScaling::FuMa;
  233. isbformat = true;
  234. chanmask = 0;
  235. break;
  236. }
  237. bytes = mDevice->bytesFromFmt();
  238. channels = mDevice->channelsFromFmt();
  239. rewind(mFile);
  240. fputs("RIFF", mFile);
  241. fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close
  242. fputs("WAVE", mFile);
  243. fputs("fmt ", mFile);
  244. fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE
  245. // 16-bit val, format type id (extensible: 0xFFFE)
  246. fwrite16le(0xFFFE, mFile);
  247. // 16-bit val, channel count
  248. fwrite16le(static_cast<ushort>(channels), mFile);
  249. // 32-bit val, frequency
  250. fwrite32le(mDevice->Frequency, mFile);
  251. // 32-bit val, bytes per second
  252. fwrite32le(mDevice->Frequency * channels * bytes, mFile);
  253. // 16-bit val, frame size
  254. fwrite16le(static_cast<ushort>(channels * bytes), mFile);
  255. // 16-bit val, bits per sample
  256. fwrite16le(static_cast<ushort>(bytes * 8), mFile);
  257. // 16-bit val, extra byte count
  258. fwrite16le(22, mFile);
  259. // 16-bit val, valid bits per sample
  260. fwrite16le(static_cast<ushort>(bytes * 8), mFile);
  261. // 32-bit val, channel mask
  262. fwrite32le(chanmask, mFile);
  263. // 16 byte GUID, sub-type format
  264. val = fwrite((mDevice->FmtType == DevFmtFloat) ?
  265. (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) :
  266. (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile);
  267. (void)val;
  268. fputs("data", mFile);
  269. fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close
  270. if(ferror(mFile))
  271. {
  272. ERR("Error writing header: %s\n", strerror(errno));
  273. return false;
  274. }
  275. mDataStart = ftell(mFile);
  276. setDefaultWFXChannelOrder();
  277. const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
  278. mBuffer.resize(bufsize);
  279. return true;
  280. }
  281. void WaveBackend::start()
  282. {
  283. if(mDataStart > 0 && fseek(mFile, 0, SEEK_END) != 0)
  284. WARN("Failed to seek on output file\n");
  285. try {
  286. mKillNow.store(false, std::memory_order_release);
  287. mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
  288. }
  289. catch(std::exception& e) {
  290. throw al::backend_exception{al::backend_error::DeviceError,
  291. "Failed to start mixing thread: %s", e.what()};
  292. }
  293. }
  294. void WaveBackend::stop()
  295. {
  296. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  297. return;
  298. mThread.join();
  299. if(mDataStart > 0)
  300. {
  301. long size{ftell(mFile)};
  302. if(size > 0)
  303. {
  304. long dataLen{size - mDataStart};
  305. if(fseek(mFile, 4, SEEK_SET) == 0)
  306. fwrite32le(static_cast<uint>(size-8), mFile); // 'WAVE' header len
  307. if(fseek(mFile, mDataStart-4, SEEK_SET) == 0)
  308. fwrite32le(static_cast<uint>(dataLen), mFile); // 'data' header len
  309. }
  310. }
  311. }
  312. } // namespace
  313. bool WaveBackendFactory::init()
  314. { return true; }
  315. bool WaveBackendFactory::querySupport(BackendType type)
  316. { return type == BackendType::Playback; }
  317. std::string WaveBackendFactory::probe(BackendType type)
  318. {
  319. std::string outnames;
  320. switch(type)
  321. {
  322. case BackendType::Playback:
  323. /* Includes null char. */
  324. outnames.append(waveDevice, sizeof(waveDevice));
  325. break;
  326. case BackendType::Capture:
  327. break;
  328. }
  329. return outnames;
  330. }
  331. BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
  332. {
  333. if(type == BackendType::Playback)
  334. return BackendPtr{new WaveBackend{device}};
  335. return nullptr;
  336. }
  337. BackendFactory &WaveBackendFactory::getFactory()
  338. {
  339. static WaveBackendFactory factory{};
  340. return factory;
  341. }