wave.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 "AL/al.h"
  33. #include "albyte.h"
  34. #include "alcmain.h"
  35. #include "alconfig.h"
  36. #include "alexcpt.h"
  37. #include "almalloc.h"
  38. #include "alnumeric.h"
  39. #include "alu.h"
  40. #include "compat.h"
  41. #include "endiantest.h"
  42. #include "logging.h"
  43. #include "strutils.h"
  44. #include "threads.h"
  45. #include "vector.h"
  46. namespace {
  47. using std::chrono::seconds;
  48. using std::chrono::milliseconds;
  49. using std::chrono::nanoseconds;
  50. constexpr ALCchar waveDevice[] = "Wave File Writer";
  51. constexpr ALubyte SUBTYPE_PCM[]{
  52. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
  53. 0x00, 0x38, 0x9b, 0x71
  54. };
  55. constexpr ALubyte SUBTYPE_FLOAT[]{
  56. 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
  57. 0x00, 0x38, 0x9b, 0x71
  58. };
  59. constexpr ALubyte SUBTYPE_BFORMAT_PCM[]{
  60. 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
  61. 0xca, 0x00, 0x00, 0x00
  62. };
  63. constexpr ALubyte 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(ALushort val, FILE *f)
  68. {
  69. ALubyte data[2]{ static_cast<ALubyte>(val&0xff), static_cast<ALubyte>((val>>8)&0xff) };
  70. fwrite(data, 1, 2, f);
  71. }
  72. void fwrite32le(ALuint val, FILE *f)
  73. {
  74. ALubyte data[4]{ static_cast<ALubyte>(val&0xff), static_cast<ALubyte>((val>>8)&0xff),
  75. static_cast<ALubyte>((val>>16)&0xff), static_cast<ALubyte>((val>>24)&0xff) };
  76. fwrite(data, 1, 4, f);
  77. }
  78. struct WaveBackend final : public BackendBase {
  79. WaveBackend(ALCdevice *device) noexcept : BackendBase{device} { }
  80. ~WaveBackend() override;
  81. int mixerProc();
  82. void open(const ALCchar *name) override;
  83. bool reset() override;
  84. bool 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 ALuint frameSize{mDevice->frameSizeFromFmt()};
  104. int64_t done{0};
  105. auto start = std::chrono::steady_clock::now();
  106. while(!mKillNow.load(std::memory_order_acquire) &&
  107. mDevice->Connected.load(std::memory_order_acquire))
  108. {
  109. auto now = std::chrono::steady_clock::now();
  110. /* This converts from nanoseconds to nanosamples, then to samples. */
  111. int64_t avail{std::chrono::duration_cast<seconds>((now-start) *
  112. mDevice->Frequency).count()};
  113. if(avail-done < mDevice->UpdateSize)
  114. {
  115. std::this_thread::sleep_for(restTime);
  116. continue;
  117. }
  118. while(avail-done >= mDevice->UpdateSize)
  119. {
  120. {
  121. std::lock_guard<WaveBackend> _{*this};
  122. aluMixData(mDevice, mBuffer.data(), mDevice->UpdateSize);
  123. }
  124. done += mDevice->UpdateSize;
  125. if(!IS_LITTLE_ENDIAN)
  126. {
  127. const ALuint bytesize{mDevice->bytesFromFmt()};
  128. if(bytesize == 2)
  129. {
  130. ALushort *samples = reinterpret_cast<ALushort*>(mBuffer.data());
  131. const size_t len{mBuffer.size() / 2};
  132. for(size_t i{0};i < len;i++)
  133. {
  134. const ALushort samp{samples[i]};
  135. samples[i] = static_cast<ALushort>((samp>>8) | (samp<<8));
  136. }
  137. }
  138. else if(bytesize == 4)
  139. {
  140. ALuint *samples = reinterpret_cast<ALuint*>(mBuffer.data());
  141. const size_t len{mBuffer.size() / 4};
  142. for(size_t i{0};i < len;i++)
  143. {
  144. const ALuint samp{samples[i]};
  145. samples[i] = (samp>>24) | ((samp>>8)&0x0000ff00) |
  146. ((samp<<8)&0x00ff0000) | (samp<<24);
  147. }
  148. }
  149. }
  150. size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->UpdateSize, mFile)};
  151. (void)fs;
  152. if(ferror(mFile))
  153. {
  154. ERR("Error writing to file\n");
  155. aluHandleDisconnect(mDevice, "Failed to write playback samples");
  156. break;
  157. }
  158. }
  159. /* For every completed second, increment the start time and reduce the
  160. * samples done. This prevents the difference between the start time
  161. * and current time from growing too large, while maintaining the
  162. * correct number of samples to render.
  163. */
  164. if(done >= mDevice->Frequency)
  165. {
  166. seconds s{done/mDevice->Frequency};
  167. start += s;
  168. done -= mDevice->Frequency*s.count();
  169. }
  170. }
  171. return 0;
  172. }
  173. void WaveBackend::open(const ALCchar *name)
  174. {
  175. const char *fname{GetConfigValue(nullptr, "wave", "file", "")};
  176. if(!fname[0]) throw al::backend_exception{ALC_INVALID_VALUE, "No wave output filename"};
  177. if(!name)
  178. name = waveDevice;
  179. else if(strcmp(name, waveDevice) != 0)
  180. throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", 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{ALC_INVALID_VALUE, "Could not open file '%s': %s", fname,
  191. strerror(errno)};
  192. mDevice->DeviceName = name;
  193. }
  194. bool WaveBackend::reset()
  195. {
  196. ALuint channels=0, bytes=0, chanmask=0;
  197. int isbformat = 0;
  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 = AmbiLayout::FuMa;
  236. mDevice->mAmbiScale = AmbiNorm::FuMa;
  237. isbformat = 1;
  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<ALushort>(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<ALushort>(channels * bytes), mFile);
  259. // 16-bit val, bits per sample
  260. fwrite16le(static_cast<ALushort>(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<ALushort>(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(mDevice);
  281. const ALuint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
  282. mBuffer.resize(bufsize);
  283. return true;
  284. }
  285. bool WaveBackend::start()
  286. {
  287. try {
  288. mKillNow.store(false, std::memory_order_release);
  289. mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
  290. return true;
  291. }
  292. catch(std::exception& e) {
  293. ERR("Failed to start mixing thread: %s\n", e.what());
  294. }
  295. catch(...) {
  296. }
  297. return false;
  298. }
  299. void WaveBackend::stop()
  300. {
  301. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  302. return;
  303. mThread.join();
  304. long size{ftell(mFile)};
  305. if(size > 0)
  306. {
  307. long dataLen{size - mDataStart};
  308. if(fseek(mFile, mDataStart-4, SEEK_SET) == 0)
  309. fwrite32le(static_cast<ALuint>(dataLen), mFile); // 'data' header len
  310. if(fseek(mFile, 4, SEEK_SET) == 0)
  311. fwrite32le(static_cast<ALuint>(size-8), mFile); // 'WAVE' header len
  312. }
  313. }
  314. } // namespace
  315. bool WaveBackendFactory::init()
  316. { return true; }
  317. bool WaveBackendFactory::querySupport(BackendType type)
  318. { return type == BackendType::Playback; }
  319. void WaveBackendFactory::probe(DevProbe type, std::string *outnames)
  320. {
  321. switch(type)
  322. {
  323. case DevProbe::Playback:
  324. /* Includes null char. */
  325. outnames->append(waveDevice, sizeof(waveDevice));
  326. break;
  327. case DevProbe::Capture:
  328. break;
  329. }
  330. }
  331. BackendPtr WaveBackendFactory::createBackend(ALCdevice *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. }