1 #pragma once
2 
3 // This should only be included from WindowsAudio.cpp and DSoundStream.cpp.
4 
5 #include "WindowsAudio.h"
6 #include <mmreg.h>
7 
8 struct IDirectSound8;
9 struct IDirectSoundBuffer;
10 
11 class DSoundAudioBackend : public WindowsAudioBackend {
12 public:
13 	DSoundAudioBackend();
14 	~DSoundAudioBackend() override;
15 
16 	bool Init(HWND window, StreamCallback callback, int sampleRate) override;  // If fails, can safely delete the object
17 	void Update() override;
GetSampleRate()18 	int GetSampleRate() override { return sampleRate_; }
19 
20 private:
ModBufferSize(int x)21 	inline int ModBufferSize(int x) { return (x + bufferSize_) % bufferSize_; }
22 	int RunThread();
23 	static unsigned int WINAPI soundThread(void *param);
24 	bool CreateBuffer();
25 	bool WriteDataToBuffer(DWORD offset, // Our own write cursor.
26 		char* soundData, // Start of our data.
27 		DWORD soundBytes); // Size of block to copy.
28 
29 	CRITICAL_SECTION soundCriticalSection;
30 	HWND window_;
31 	HANDLE soundSyncEvent_ = nullptr;
32 	HANDLE hThread_ = nullptr;
33 
34 	StreamCallback callback_;
35 
36 	IDirectSound8 *ds_ = nullptr;
37 	IDirectSoundBuffer *dsBuffer_ = nullptr;
38 
39 	int bufferSize_; // bytes
40 	int totalRenderedBytes_;
41 	int sampleRate_;
42 
43 	volatile int threadData_ = 0;
44 
45 	enum {
46 		BUFSIZE = 0x4000,
47 		MAXWAIT = 20,   //ms
48 	};
49 
50 	int currentPos_;
51 	int lastPos_;
52 	short realtimeBuffer_[BUFSIZE * 2];
53 };
54