Don't call log10 with values too close to 0
[openal-soft.git] / alc / backends / winmm.cpp
blobea4fee1e8f5f7c5fff401acb317fdb694fb4edff
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.
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.
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
21 #include "config.h"
23 #include "winmm.h"
25 #include <cstdlib>
26 #include <cstdio>
27 #include <memory.h>
29 #include <windows.h>
30 #include <mmsystem.h>
31 #include <mmreg.h>
33 #include <array>
34 #include <atomic>
35 #include <thread>
36 #include <vector>
37 #include <string>
38 #include <algorithm>
39 #include <functional>
41 #include "alsem.h"
42 #include "alstring.h"
43 #include "althrd_setname.h"
44 #include "core/device.h"
45 #include "core/helpers.h"
46 #include "core/logging.h"
47 #include "ringbuffer.h"
48 #include "strutils.h"
49 #include "vector.h"
51 #ifndef WAVE_FORMAT_IEEE_FLOAT
52 #define WAVE_FORMAT_IEEE_FLOAT 0x0003
53 #endif
55 namespace {
57 #define DEVNAME_HEAD "OpenAL Soft on "
60 std::vector<std::string> PlaybackDevices;
61 std::vector<std::string> CaptureDevices;
63 bool checkName(const std::vector<std::string> &list, const std::string &name)
64 { return std::find(list.cbegin(), list.cend(), name) != list.cend(); }
66 void ProbePlaybackDevices()
68 PlaybackDevices.clear();
70 UINT numdevs{waveOutGetNumDevs()};
71 PlaybackDevices.reserve(numdevs);
72 for(UINT i{0};i < numdevs;++i)
74 std::string dname;
76 WAVEOUTCAPSW WaveCaps{};
77 if(waveOutGetDevCapsW(i, &WaveCaps, sizeof(WaveCaps)) == MMSYSERR_NOERROR)
79 const std::string basename{DEVNAME_HEAD + wstr_to_utf8(std::data(WaveCaps.szPname))};
81 int count{1};
82 std::string newname{basename};
83 while(checkName(PlaybackDevices, newname))
85 newname = basename;
86 newname += " #";
87 newname += std::to_string(++count);
89 dname = std::move(newname);
91 TRACE("Got device \"%s\", ID %u\n", dname.c_str(), i);
93 PlaybackDevices.emplace_back(std::move(dname));
97 void ProbeCaptureDevices()
99 CaptureDevices.clear();
101 UINT numdevs{waveInGetNumDevs()};
102 CaptureDevices.reserve(numdevs);
103 for(UINT i{0};i < numdevs;++i)
105 std::string dname;
107 WAVEINCAPSW WaveCaps{};
108 if(waveInGetDevCapsW(i, &WaveCaps, sizeof(WaveCaps)) == MMSYSERR_NOERROR)
110 const std::string basename{DEVNAME_HEAD + wstr_to_utf8(std::data(WaveCaps.szPname))};
112 int count{1};
113 std::string newname{basename};
114 while(checkName(CaptureDevices, newname))
116 newname = basename;
117 newname += " #";
118 newname += std::to_string(++count);
120 dname = std::move(newname);
122 TRACE("Got device \"%s\", ID %u\n", dname.c_str(), i);
124 CaptureDevices.emplace_back(std::move(dname));
129 struct WinMMPlayback final : public BackendBase {
130 WinMMPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
131 ~WinMMPlayback() override;
133 void CALLBACK waveOutProc(HWAVEOUT device, UINT msg, DWORD_PTR param1, DWORD_PTR param2) noexcept;
134 static void CALLBACK waveOutProcC(HWAVEOUT device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) noexcept
135 { reinterpret_cast<WinMMPlayback*>(instance)->waveOutProc(device, msg, param1, param2); }
137 int mixerProc();
139 void open(std::string_view name) override;
140 bool reset() override;
141 void start() override;
142 void stop() override;
144 std::atomic<uint> mWritable{0u};
145 al::semaphore mSem;
146 uint mIdx{0u};
147 std::array<WAVEHDR,4> mWaveBuffer{};
148 al::vector<char,16> mBuffer;
150 HWAVEOUT mOutHdl{nullptr};
152 WAVEFORMATEX mFormat{};
154 std::atomic<bool> mKillNow{true};
155 std::thread mThread;
158 WinMMPlayback::~WinMMPlayback()
160 if(mOutHdl)
161 waveOutClose(mOutHdl);
162 mOutHdl = nullptr;
165 /* WinMMPlayback::waveOutProc
167 * Posts a message to 'WinMMPlayback::mixerProc' every time a WaveOut Buffer is
168 * completed and returns to the application (for more data)
170 void CALLBACK WinMMPlayback::waveOutProc(HWAVEOUT, UINT msg, DWORD_PTR, DWORD_PTR) noexcept
172 if(msg != WOM_DONE) return;
173 mWritable.fetch_add(1, std::memory_order_acq_rel);
174 mSem.post();
177 FORCE_ALIGN int WinMMPlayback::mixerProc()
179 SetRTPriority();
180 althrd_setname(GetMixerThreadName());
182 while(!mKillNow.load(std::memory_order_acquire)
183 && mDevice->Connected.load(std::memory_order_acquire))
185 uint todo{mWritable.load(std::memory_order_acquire)};
186 if(todo < 1)
188 mSem.wait();
189 continue;
192 size_t widx{mIdx};
193 do {
194 WAVEHDR &waveHdr = mWaveBuffer[widx];
195 if(++widx == mWaveBuffer.size()) widx = 0;
197 mDevice->renderSamples(waveHdr.lpData, mDevice->UpdateSize, mFormat.nChannels);
198 mWritable.fetch_sub(1, std::memory_order_acq_rel);
199 waveOutWrite(mOutHdl, &waveHdr, sizeof(WAVEHDR));
200 } while(--todo);
201 mIdx = static_cast<uint>(widx);
204 return 0;
208 void WinMMPlayback::open(std::string_view name)
210 if(PlaybackDevices.empty())
211 ProbePlaybackDevices();
213 // Find the Device ID matching the deviceName if valid
214 auto iter = !name.empty() ?
215 std::find(PlaybackDevices.cbegin(), PlaybackDevices.cend(), name) :
216 PlaybackDevices.cbegin();
217 if(iter == PlaybackDevices.cend())
218 throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%.*s\" not found",
219 al::sizei(name), name.data()};
220 auto DeviceID = static_cast<UINT>(std::distance(PlaybackDevices.cbegin(), iter));
222 DevFmtType fmttype{mDevice->FmtType};
223 WAVEFORMATEX format{};
224 do {
225 format = WAVEFORMATEX{};
226 if(fmttype == DevFmtFloat)
228 format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
229 format.wBitsPerSample = 32;
231 else
233 format.wFormatTag = WAVE_FORMAT_PCM;
234 if(fmttype == DevFmtUByte || fmttype == DevFmtByte)
235 format.wBitsPerSample = 8;
236 else
237 format.wBitsPerSample = 16;
239 format.nChannels = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2);
240 format.nBlockAlign = static_cast<WORD>(format.wBitsPerSample * format.nChannels / 8);
241 format.nSamplesPerSec = mDevice->Frequency;
242 format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
243 format.cbSize = 0;
245 MMRESULT res{waveOutOpen(&mOutHdl, DeviceID, &format,
246 reinterpret_cast<DWORD_PTR>(&WinMMPlayback::waveOutProcC),
247 reinterpret_cast<DWORD_PTR>(this), CALLBACK_FUNCTION)};
248 if(res == MMSYSERR_NOERROR) break;
250 if(fmttype != DevFmtFloat)
251 throw al::backend_exception{al::backend_error::DeviceError, "waveOutOpen failed: %u",
252 res};
254 fmttype = DevFmtShort;
255 } while(true);
257 mFormat = format;
259 mDevice->DeviceName = PlaybackDevices[DeviceID];
262 bool WinMMPlayback::reset()
264 mDevice->BufferSize = static_cast<uint>(uint64_t{mDevice->BufferSize} *
265 mFormat.nSamplesPerSec / mDevice->Frequency);
266 mDevice->BufferSize = (mDevice->BufferSize+3) & ~0x3u;
267 mDevice->UpdateSize = mDevice->BufferSize / 4;
268 mDevice->Frequency = mFormat.nSamplesPerSec;
270 if(mFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
272 if(mFormat.wBitsPerSample == 32)
273 mDevice->FmtType = DevFmtFloat;
274 else
276 ERR("Unhandled IEEE float sample depth: %d\n", mFormat.wBitsPerSample);
277 return false;
280 else if(mFormat.wFormatTag == WAVE_FORMAT_PCM)
282 if(mFormat.wBitsPerSample == 16)
283 mDevice->FmtType = DevFmtShort;
284 else if(mFormat.wBitsPerSample == 8)
285 mDevice->FmtType = DevFmtUByte;
286 else
288 ERR("Unhandled PCM sample depth: %d\n", mFormat.wBitsPerSample);
289 return false;
292 else
294 ERR("Unhandled format tag: 0x%04x\n", mFormat.wFormatTag);
295 return false;
298 if(mFormat.nChannels >= 2)
299 mDevice->FmtChans = DevFmtStereo;
300 else if(mFormat.nChannels == 1)
301 mDevice->FmtChans = DevFmtMono;
302 else
304 ERR("Unhandled channel count: %d\n", mFormat.nChannels);
305 return false;
307 setDefaultWFXChannelOrder();
309 const uint BufferSize{mDevice->UpdateSize * mFormat.nChannels * mDevice->bytesFromFmt()};
311 decltype(mBuffer)(BufferSize*mWaveBuffer.size()).swap(mBuffer);
312 mWaveBuffer[0] = WAVEHDR{};
313 mWaveBuffer[0].lpData = mBuffer.data();
314 mWaveBuffer[0].dwBufferLength = BufferSize;
315 for(size_t i{1};i < mWaveBuffer.size();i++)
317 mWaveBuffer[i] = WAVEHDR{};
318 mWaveBuffer[i].lpData = mWaveBuffer[i-1].lpData + mWaveBuffer[i-1].dwBufferLength;
319 mWaveBuffer[i].dwBufferLength = BufferSize;
321 mIdx = 0;
323 return true;
326 void WinMMPlayback::start()
328 try {
329 for(auto &waveHdr : mWaveBuffer)
330 waveOutPrepareHeader(mOutHdl, &waveHdr, sizeof(WAVEHDR));
331 mWritable.store(static_cast<uint>(mWaveBuffer.size()), std::memory_order_release);
333 mKillNow.store(false, std::memory_order_release);
334 mThread = std::thread{std::mem_fn(&WinMMPlayback::mixerProc), this};
336 catch(std::exception& e) {
337 throw al::backend_exception{al::backend_error::DeviceError,
338 "Failed to start mixing thread: %s", e.what()};
342 void WinMMPlayback::stop()
344 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
345 return;
346 mThread.join();
348 while(mWritable.load(std::memory_order_acquire) < mWaveBuffer.size())
349 mSem.wait();
350 for(auto &waveHdr : mWaveBuffer)
351 waveOutUnprepareHeader(mOutHdl, &waveHdr, sizeof(WAVEHDR));
352 mWritable.store(0, std::memory_order_release);
356 struct WinMMCapture final : public BackendBase {
357 WinMMCapture(DeviceBase *device) noexcept : BackendBase{device} { }
358 ~WinMMCapture() override;
360 void CALLBACK waveInProc(HWAVEIN device, UINT msg, DWORD_PTR param1, DWORD_PTR param2) noexcept;
361 static void CALLBACK waveInProcC(HWAVEIN device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) noexcept
362 { reinterpret_cast<WinMMCapture*>(instance)->waveInProc(device, msg, param1, param2); }
364 int captureProc();
366 void open(std::string_view name) override;
367 void start() override;
368 void stop() override;
369 void captureSamples(std::byte *buffer, uint samples) override;
370 uint availableSamples() override;
372 std::atomic<uint> mReadable{0u};
373 al::semaphore mSem;
374 uint mIdx{0};
375 std::array<WAVEHDR,4> mWaveBuffer{};
376 al::vector<char,16> mBuffer;
378 HWAVEIN mInHdl{nullptr};
380 RingBufferPtr mRing{nullptr};
382 WAVEFORMATEX mFormat{};
384 std::atomic<bool> mKillNow{true};
385 std::thread mThread;
388 WinMMCapture::~WinMMCapture()
390 // Close the Wave device
391 if(mInHdl)
392 waveInClose(mInHdl);
393 mInHdl = nullptr;
396 /* WinMMCapture::waveInProc
398 * Posts a message to 'WinMMCapture::captureProc' every time a WaveIn Buffer is
399 * completed and returns to the application (with more data).
401 void CALLBACK WinMMCapture::waveInProc(HWAVEIN, UINT msg, DWORD_PTR, DWORD_PTR) noexcept
403 if(msg != WIM_DATA) return;
404 mReadable.fetch_add(1, std::memory_order_acq_rel);
405 mSem.post();
408 int WinMMCapture::captureProc()
410 althrd_setname(GetRecordThreadName());
412 while(!mKillNow.load(std::memory_order_acquire) &&
413 mDevice->Connected.load(std::memory_order_acquire))
415 uint todo{mReadable.load(std::memory_order_acquire)};
416 if(todo < 1)
418 mSem.wait();
419 continue;
422 size_t widx{mIdx};
423 do {
424 WAVEHDR &waveHdr = mWaveBuffer[widx];
425 widx = (widx+1) % mWaveBuffer.size();
427 std::ignore = mRing->write(waveHdr.lpData,
428 waveHdr.dwBytesRecorded / mFormat.nBlockAlign);
429 mReadable.fetch_sub(1, std::memory_order_acq_rel);
430 waveInAddBuffer(mInHdl, &waveHdr, sizeof(WAVEHDR));
431 } while(--todo);
432 mIdx = static_cast<uint>(widx);
435 return 0;
439 void WinMMCapture::open(std::string_view name)
441 if(CaptureDevices.empty())
442 ProbeCaptureDevices();
444 // Find the Device ID matching the deviceName if valid
445 auto iter = !name.empty() ?
446 std::find(CaptureDevices.cbegin(), CaptureDevices.cend(), name) :
447 CaptureDevices.cbegin();
448 if(iter == CaptureDevices.cend())
449 throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%.*s\" not found",
450 al::sizei(name), name.data()};
451 auto DeviceID = static_cast<UINT>(std::distance(CaptureDevices.cbegin(), iter));
453 switch(mDevice->FmtChans)
455 case DevFmtMono:
456 case DevFmtStereo:
457 break;
459 case DevFmtQuad:
460 case DevFmtX51:
461 case DevFmtX61:
462 case DevFmtX71:
463 case DevFmtX714:
464 case DevFmtX7144:
465 case DevFmtX3D71:
466 case DevFmtAmbi3D:
467 throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
468 DevFmtChannelsString(mDevice->FmtChans)};
471 switch(mDevice->FmtType)
473 case DevFmtUByte:
474 case DevFmtShort:
475 case DevFmtInt:
476 case DevFmtFloat:
477 break;
479 case DevFmtByte:
480 case DevFmtUShort:
481 case DevFmtUInt:
482 throw al::backend_exception{al::backend_error::DeviceError, "%s samples not supported",
483 DevFmtTypeString(mDevice->FmtType)};
486 mFormat = WAVEFORMATEX{};
487 mFormat.wFormatTag = (mDevice->FmtType == DevFmtFloat) ?
488 WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM;
489 mFormat.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
490 mFormat.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
491 mFormat.nBlockAlign = static_cast<WORD>(mFormat.wBitsPerSample * mFormat.nChannels / 8);
492 mFormat.nSamplesPerSec = mDevice->Frequency;
493 mFormat.nAvgBytesPerSec = mFormat.nSamplesPerSec * mFormat.nBlockAlign;
494 mFormat.cbSize = 0;
496 MMRESULT res{waveInOpen(&mInHdl, DeviceID, &mFormat,
497 reinterpret_cast<DWORD_PTR>(&WinMMCapture::waveInProcC),
498 reinterpret_cast<DWORD_PTR>(this), CALLBACK_FUNCTION)};
499 if(res != MMSYSERR_NOERROR)
500 throw al::backend_exception{al::backend_error::DeviceError, "waveInOpen failed: %u", res};
502 // Ensure each buffer is 50ms each
503 DWORD BufferSize{mFormat.nAvgBytesPerSec / 20u};
504 BufferSize -= (BufferSize % mFormat.nBlockAlign);
506 // Allocate circular memory buffer for the captured audio
507 // Make sure circular buffer is at least 100ms in size
508 const auto CapturedDataSize = std::max<size_t>(mDevice->BufferSize,
509 BufferSize*mWaveBuffer.size());
511 mRing = RingBuffer::Create(CapturedDataSize, mFormat.nBlockAlign, false);
513 decltype(mBuffer)(BufferSize*mWaveBuffer.size()).swap(mBuffer);
514 mWaveBuffer[0] = WAVEHDR{};
515 mWaveBuffer[0].lpData = mBuffer.data();
516 mWaveBuffer[0].dwBufferLength = BufferSize;
517 for(size_t i{1};i < mWaveBuffer.size();++i)
519 mWaveBuffer[i] = WAVEHDR{};
520 mWaveBuffer[i].lpData = mWaveBuffer[i-1].lpData + mWaveBuffer[i-1].dwBufferLength;
521 mWaveBuffer[i].dwBufferLength = mWaveBuffer[i-1].dwBufferLength;
524 mDevice->DeviceName = CaptureDevices[DeviceID];
527 void WinMMCapture::start()
529 try {
530 for(size_t i{0};i < mWaveBuffer.size();++i)
532 waveInPrepareHeader(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR));
533 waveInAddBuffer(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR));
536 mKillNow.store(false, std::memory_order_release);
537 mThread = std::thread{std::mem_fn(&WinMMCapture::captureProc), this};
539 waveInStart(mInHdl);
541 catch(std::exception& e) {
542 throw al::backend_exception{al::backend_error::DeviceError,
543 "Failed to start recording thread: %s", e.what()};
547 void WinMMCapture::stop()
549 waveInStop(mInHdl);
551 mKillNow.store(true, std::memory_order_release);
552 if(mThread.joinable())
554 mSem.post();
555 mThread.join();
558 waveInReset(mInHdl);
559 for(size_t i{0};i < mWaveBuffer.size();++i)
560 waveInUnprepareHeader(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR));
562 mReadable.store(0, std::memory_order_release);
563 mIdx = 0;
566 void WinMMCapture::captureSamples(std::byte *buffer, uint samples)
567 { std::ignore = mRing->read(buffer, samples); }
569 uint WinMMCapture::availableSamples()
570 { return static_cast<uint>(mRing->readSpace()); }
572 } // namespace
575 bool WinMMBackendFactory::init()
576 { return true; }
578 bool WinMMBackendFactory::querySupport(BackendType type)
579 { return type == BackendType::Playback || type == BackendType::Capture; }
581 auto WinMMBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
583 std::vector<std::string> outnames;
584 auto add_device = [&outnames](const std::string &dname) -> void
585 { if(!dname.empty()) outnames.emplace_back(dname); };
587 switch(type)
589 case BackendType::Playback:
590 ProbePlaybackDevices();
591 outnames.reserve(PlaybackDevices.size());
592 std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
593 break;
595 case BackendType::Capture:
596 ProbeCaptureDevices();
597 outnames.reserve(CaptureDevices.size());
598 std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
599 break;
601 return outnames;
604 BackendPtr WinMMBackendFactory::createBackend(DeviceBase *device, BackendType type)
606 if(type == BackendType::Playback)
607 return BackendPtr{new WinMMPlayback{device}};
608 if(type == BackendType::Capture)
609 return BackendPtr{new WinMMCapture{device}};
610 return nullptr;
613 BackendFactory &WinMMBackendFactory::getFactory()
615 static WinMMBackendFactory factory{};
616 return factory;