wave.cpp 12 KB

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