/* Copyright (c) 2019 Alex Diener This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Alex Diener alex@ludobloom.com */ #include "nativeaudio/AudioOut.h" #include #include #include #include #define DSOUND_BUFFER_SIZE 8192 #define TRANSPORT_BUFFER_SIZE 4096 #define FRAMES_PER_OUTPUT_CYCLE 1024 #define AUDIO_THREAD_SLEEP_MILLISECONDS 2 #define TARGET_WRITE_BYTES (FRAMES_PER_OUTPUT_CYCLE * 4) static bool initialized, outputActive; static LPDIRECTSOUND directSoundInterface; static LPDIRECTSOUNDBUFFER primaryBuffer, outputBuffer; static CRITICAL_SECTION criticalSection; static AudioOut_sampleFormat transportFormat, hostFormat; static void * transportBuffer; static AudioOutCallback outputCallback; static void * outputContext; static AudioOut_resampleState resampleState; static DWORD WINAPI outputThreadFunc(LPVOID lpParameter) { HRESULT result; void * outData1 = NULL, * outData2 = NULL; DWORD dataSize1, dataSize2; DWORD writeCursor, lastWriteCursor = 0, bytesToWrite, lastWriteEndPosition = 0; bool waitingForPlay = true; bool underflowDetected = false; while (outputActive) { result = IDirectSoundBuffer_GetCurrentPosition(outputBuffer, NULL, &writeCursor); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "IDirectSoundBuffer_GetCurrentPosition failed: 0x%X\n", (int) result); #endif return 0; } if (writeCursor < lastWriteCursor) { lastWriteEndPosition -= DSOUND_BUFFER_SIZE; } if (writeCursor + TARGET_WRITE_BYTES <= lastWriteEndPosition) { Sleep(AUDIO_THREAD_SLEEP_MILLISECONDS); continue; } if (writeCursor > lastWriteEndPosition && !underflowDetected) { #ifdef DEBUG fprintf(stderr, "Warning: Audio underflow detected (%d, %d)\n", (int) writeCursor, (int) lastWriteEndPosition); #endif lastWriteEndPosition = writeCursor; underflowDetected = true; } bytesToWrite = TARGET_WRITE_BYTES - (lastWriteEndPosition - writeCursor); result = IDirectSoundBuffer_Lock(outputBuffer, lastWriteEndPosition % DSOUND_BUFFER_SIZE, bytesToWrite, &outData1, &dataSize1, &outData2, &dataSize2, 0); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "IDirectSoundBuffer_Lock failed: 0x%X\n", (int) result); #endif return 0; } if (transportFormat.channelCount == hostFormat.channelCount && transportFormat.sampleRate == hostFormat.sampleRate && transportFormat.bytesPerSample == hostFormat.bytesPerSample) { if (dataSize1 > 0) { outputCallback(outData1, dataSize1 / hostFormat.bytesPerSample / hostFormat.channelCount, outputContext); } if (dataSize2 > 0) { outputCallback(outData2, dataSize2 / hostFormat.bytesPerSample / hostFormat.channelCount, outputContext); } } else { unsigned int remainingOutFrameCount1, remainingOutFrameCount2, inFrameCount, inFrameCountMax, frameOffset1 = 0, frameOffset2 = 0, framesConsumed, framesWritten, framesConsumed1 = 0; inFrameCountMax = TRANSPORT_BUFFER_SIZE / transportFormat.bytesPerSample / transportFormat.channelCount; remainingOutFrameCount1 = dataSize1 / hostFormat.bytesPerSample / hostFormat.channelCount; remainingOutFrameCount2 = dataSize2 / hostFormat.bytesPerSample / hostFormat.channelCount; while (remainingOutFrameCount1 > 0 || remainingOutFrameCount2 > 0) { inFrameCount = (remainingOutFrameCount1 + remainingOutFrameCount2) * transportFormat.sampleRate / hostFormat.sampleRate; if (inFrameCount > inFrameCountMax) { inFrameCount = inFrameCountMax; } // TODO: Use AudioOut_transferToOutput() outputCallback(transportBuffer, inFrameCount, outputContext); if (remainingOutFrameCount1 > 0) { AudioOut_convertSamples(transportBuffer, inFrameCount, transportFormat, outData1 + frameOffset1 * hostFormat.bytesPerSample * hostFormat.channelCount, remainingOutFrameCount1, hostFormat, &framesConsumed, &framesWritten, &resampleState); remainingOutFrameCount1 -= framesWritten; frameOffset1 += framesWritten; framesConsumed1 += framesConsumed; } if (remainingOutFrameCount1 == 0 && remainingOutFrameCount2 > 0) { AudioOut_convertSamples(transportBuffer + frameOffset1 * transportFormat.bytesPerSample * transportFormat.channelCount, inFrameCount + framesConsumed1, transportFormat, outData2 + frameOffset2 * hostFormat.bytesPerSample * hostFormat.channelCount, remainingOutFrameCount2, hostFormat, &framesConsumed, &framesWritten, &resampleState); remainingOutFrameCount2 -= framesWritten; frameOffset2 += framesWritten; } } } result = IDirectSoundBuffer_Unlock(outputBuffer, outData1, dataSize1, outData2, dataSize2); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "IDirectSoundBuffer_Unlock returned 0x%X\n", (int) result); #endif return 0; } lastWriteEndPosition += dataSize1 + dataSize2; lastWriteCursor = writeCursor; if (waitingForPlay) { result = IDirectSoundBuffer_Play(outputBuffer, 0, 0, DSBPLAY_LOOPING); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "IDirectSoundBuffer_Play returned 0x%X\n", (int) result); #endif return 0; } waitingForPlay = false; } Sleep(AUDIO_THREAD_SLEEP_MILLISECONDS); } IDirectSoundBuffer_Stop(outputBuffer); IDirectSoundBuffer_SetCurrentPosition(outputBuffer, 0); return 0; } void AudioOut_init(const char * processName) { if (initialized) { return; } HRESULT result; HWND windowHandle; DSBUFFERDESC primaryBufferDesc, outputBufferDesc; WAVEFORMATEX waveFormat; result = DirectSoundCreate(NULL, &directSoundInterface, NULL); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "DirectSoundCreate returned 0x%X\n", (int) result); #endif return; } windowHandle = GetForegroundWindow(); if (windowHandle == NULL) { windowHandle = GetDesktopWindow(); } result = IDirectSound_SetCooperativeLevel(directSoundInterface, windowHandle, DSSCL_PRIORITY); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "SetCooperativeLevel returned 0x%X\n", (int) result); #endif return; } memset(&primaryBufferDesc, 0, sizeof(primaryBufferDesc)); primaryBufferDesc.dwSize = sizeof(primaryBufferDesc); primaryBufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER; primaryBufferDesc.dwBufferBytes = 0; primaryBufferDesc.lpwfxFormat = NULL; result = IDirectSound_CreateSoundBuffer(directSoundInterface, &primaryBufferDesc, &primaryBuffer, NULL); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "CreateSoundBuffer (primary) returned 0x%X\n", (int) result); #endif return; } hostFormat.channelCount = 2; hostFormat.sampleRate = 44100; hostFormat.bytesPerSample = sizeof(int16_t); memset(&waveFormat, 0, sizeof(waveFormat)); waveFormat.wFormatTag = WAVE_FORMAT_PCM; waveFormat.nChannels = hostFormat.channelCount; waveFormat.nSamplesPerSec = hostFormat.sampleRate; waveFormat.nAvgBytesPerSec = hostFormat.sampleRate * hostFormat.channelCount * hostFormat.bytesPerSample; waveFormat.nBlockAlign = hostFormat.channelCount * hostFormat.bytesPerSample; waveFormat.wBitsPerSample = hostFormat.bytesPerSample * 8; waveFormat.cbSize = 0; result = IDirectSoundBuffer_SetFormat(primaryBuffer, &waveFormat); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "SetFormat returned 0x%X\n", (int) result); #endif return; } memset(&outputBufferDesc, 0, sizeof(outputBufferDesc)); outputBufferDesc.dwSize = sizeof(outputBufferDesc); outputBufferDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2; outputBufferDesc.dwBufferBytes = DSOUND_BUFFER_SIZE; outputBufferDesc.lpwfxFormat = &waveFormat; result = IDirectSound_CreateSoundBuffer(directSoundInterface, &outputBufferDesc, &outputBuffer, NULL); if (result != DS_OK) { #ifdef DEBUG fprintf(stderr, "CreateSoundBuffer (output) returned 0x%X\n", (int) result); #endif return; } transportFormat = hostFormat; transportBuffer = malloc(TRANSPORT_BUFFER_SIZE); initialized = true; } void AudioOut_shutdown(void) { } AudioOut_sampleFormat AudioOut_getHostFormat(void) { return hostFormat; } AudioOut_sampleFormat AudioOut_getTransportFormat(void) { return transportFormat; } void AudioOut_startOutput(AudioOutCallback callback, void * context) { if (!outputActive) { outputCallback = callback; InitializeCriticalSectionAndSpinCount(&criticalSection, 0x400); CreateThread(NULL, 0, outputThreadFunc, outputContext, 0, NULL); outputActive = true; } } void AudioOut_stopOutput(void) { outputActive = false; }