1 /*************************************************************************/
2 /*  audio_driver_winrt.cpp                                               */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
9 /*                                                                       */
10 /* Permission is hereby granted, free of charge, to any person obtaining */
11 /* a copy of this software and associated documentation files (the       */
12 /* "Software"), to deal in the Software without restriction, including   */
13 /* without limitation the rights to use, copy, modify, merge, publish,   */
14 /* distribute, sublicense, and/or sell copies of the Software, and to    */
15 /* permit persons to whom the Software is furnished to do so, subject to */
16 /* the following conditions:                                             */
17 /*                                                                       */
18 /* The above copyright notice and this permission notice shall be        */
19 /* included in all copies or substantial portions of the Software.       */
20 /*                                                                       */
21 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
22 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
23 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
24 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
25 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
26 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
27 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
28 /*************************************************************************/
29 #include "audio_driver_winrt.h"
30 
31 #include "globals.h"
32 #include "os/os.h"
33 
34 using namespace Windows::Media;
35 using namespace Windows::Media::Core;
36 using namespace Windows::Media::MediaProperties;
37 using namespace Windows::Media::Editing;
38 using namespace Windows::Foundation;
39 
get_name() const40 const char *AudioDriverWinRT::get_name() const {
41 	return "WinRT";
42 }
43 
init()44 Error AudioDriverWinRT::init() {
45 
46 	active = false;
47 	thread_exited = false;
48 	exit_thread = false;
49 	pcm_open = false;
50 	samples_in = NULL;
51 
52 	mix_rate = 48000;
53 	output_format = OUTPUT_STEREO;
54 	channels = 2;
55 
56 	int latency = GLOBAL_DEF("audio/output_latency", 25);
57 	buffer_size = closest_power_of_2(latency * mix_rate / 1000);
58 
59 	samples_in = memnew_arr(int32_t, buffer_size * channels);
60 	for (int i = 0; i < AUDIO_BUFFERS; i++) {
61 		samples_out[i] = memnew_arr(int16_t, buffer_size * channels);
62 		xaudio_buffer[i].AudioBytes = buffer_size * channels * sizeof(int16_t);
63 		xaudio_buffer[i].pAudioData = (const BYTE *)(samples_out[i]);
64 		xaudio_buffer[i].Flags = 0;
65 	}
66 
67 	HRESULT hr;
68 	hr = XAudio2Create(&xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR);
69 	if (hr != S_OK) {
70 		ERR_EXPLAIN("Error creating XAudio2 engine.");
71 		ERR_FAIL_V(ERR_UNAVAILABLE);
72 	}
73 	hr = xaudio->CreateMasteringVoice(&mastering_voice);
74 	if (hr != S_OK) {
75 		ERR_EXPLAIN("Error creating XAudio2 mastering voice.");
76 		ERR_FAIL_V(ERR_UNAVAILABLE);
77 	}
78 
79 	wave_format.nChannels = channels;
80 	wave_format.cbSize = 0;
81 	wave_format.nSamplesPerSec = mix_rate;
82 	wave_format.wFormatTag = WAVE_FORMAT_PCM;
83 	wave_format.wBitsPerSample = 16;
84 	wave_format.nBlockAlign = channels * wave_format.wBitsPerSample >> 3;
85 	wave_format.nAvgBytesPerSec = mix_rate * wave_format.nBlockAlign;
86 
87 	voice_callback = memnew(XAudio2DriverVoiceCallback);
88 
89 	hr = xaudio->CreateSourceVoice(&source_voice, &wave_format, 0, XAUDIO2_MAX_FREQ_RATIO, voice_callback);
90 	if (hr != S_OK) {
91 		ERR_EXPLAIN("Error creating XAudio2 source voice. " + itos(hr));
92 		ERR_FAIL_V(ERR_UNAVAILABLE);
93 	}
94 
95 	mutex = Mutex::create();
96 	thread = Thread::create(AudioDriverWinRT::thread_func, this);
97 
98 	return OK;
99 };
100 
thread_func(void * p_udata)101 void AudioDriverWinRT::thread_func(void *p_udata) {
102 
103 	AudioDriverWinRT *ad = (AudioDriverWinRT *)p_udata;
104 
105 	uint64_t usdelay = (ad->buffer_size / float(ad->mix_rate)) * 1000000;
106 
107 	while (!ad->exit_thread) {
108 
109 		if (!ad->active) {
110 
111 			for (int i = 0; i < AUDIO_BUFFERS; i++) {
112 				ad->xaudio_buffer[i].Flags = XAUDIO2_END_OF_STREAM;
113 			}
114 
115 		} else {
116 
117 			ad->lock();
118 
119 			ad->audio_server_process(ad->buffer_size, ad->samples_in);
120 
121 			ad->unlock();
122 
123 			for (unsigned int i = 0; i < ad->buffer_size * ad->channels; i++) {
124 
125 				ad->samples_out[ad->current_buffer][i] = ad->samples_in[i] >> 16;
126 			}
127 
128 			ad->xaudio_buffer[ad->current_buffer].Flags = 0;
129 			ad->xaudio_buffer[ad->current_buffer].AudioBytes = ad->buffer_size * ad->channels * sizeof(int16_t);
130 			ad->xaudio_buffer[ad->current_buffer].pAudioData = (const BYTE *)(ad->samples_out[ad->current_buffer]);
131 			ad->xaudio_buffer[ad->current_buffer].PlayBegin = 0;
132 			ad->source_voice->SubmitSourceBuffer(&(ad->xaudio_buffer[ad->current_buffer]));
133 
134 			ad->current_buffer = (ad->current_buffer + 1) % AUDIO_BUFFERS;
135 
136 			XAUDIO2_VOICE_STATE state;
137 			while (ad->source_voice->GetState(&state), state.BuffersQueued > AUDIO_BUFFERS - 1) {
138 				WaitForSingleObject(ad->voice_callback->buffer_end_event, INFINITE);
139 			}
140 		}
141 	};
142 
143 	ad->thread_exited = true;
144 };
145 
start()146 void AudioDriverWinRT::start() {
147 
148 	active = true;
149 	HRESULT hr = source_voice->Start(0);
150 	if (hr != S_OK) {
151 		ERR_EXPLAIN("XAudio2 start error " + itos(hr));
152 		ERR_FAIL();
153 	}
154 };
155 
get_mix_rate() const156 int AudioDriverWinRT::get_mix_rate() const {
157 
158 	return mix_rate;
159 };
160 
get_output_format() const161 AudioDriverSW::OutputFormat AudioDriverWinRT::get_output_format() const {
162 
163 	return output_format;
164 };
165 
get_latency()166 float AudioDriverWinRT::get_latency() {
167 
168 	XAUDIO2_PERFORMANCE_DATA perf_data;
169 	xaudio->GetPerformanceData(&perf_data);
170 	if (perf_data.CurrentLatencyInSamples) {
171 		return (float)(perf_data.CurrentLatencyInSamples / ((float)mix_rate));
172 	} else {
173 		return 0;
174 	}
175 }
176 
lock()177 void AudioDriverWinRT::lock() {
178 
179 	if (!thread || !mutex)
180 		return;
181 	mutex->lock();
182 };
unlock()183 void AudioDriverWinRT::unlock() {
184 
185 	if (!thread || !mutex)
186 		return;
187 	mutex->unlock();
188 };
189 
finish()190 void AudioDriverWinRT::finish() {
191 
192 	if (!thread)
193 		return;
194 
195 	exit_thread = true;
196 	Thread::wait_to_finish(thread);
197 
198 	if (source_voice) {
199 		source_voice->Stop(0);
200 		memdelete(source_voice);
201 	}
202 
203 	if (samples_in) {
204 		memdelete_arr(samples_in);
205 	};
206 	if (samples_out[0]) {
207 		for (int i = 0; i < AUDIO_BUFFERS; i++) {
208 			memdelete_arr(samples_out[i]);
209 		}
210 	};
211 
212 	memdelete(voice_callback);
213 	memdelete(mastering_voice);
214 
215 	memdelete(thread);
216 	if (mutex)
217 		memdelete(mutex);
218 	thread = NULL;
219 };
220 
AudioDriverWinRT()221 AudioDriverWinRT::AudioDriverWinRT() {
222 
223 	mutex = NULL;
224 	thread = NULL;
225 	wave_format = { 0 };
226 	for (int i = 0; i < AUDIO_BUFFERS; i++) {
227 		xaudio_buffer[i] = { 0 };
228 		samples_out[i] = 0;
229 	}
230 	current_buffer = 0;
231 };
232 
~AudioDriverWinRT()233 AudioDriverWinRT::~AudioDriverWinRT(){
234 
235 };
236