File: snd_coreaudio.c

package info (click to toggle)
darkplaces 0~20180412~beta1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 18,200 kB
  • sloc: ansic: 176,886; makefile: 485; pascal: 455; perl: 372; objc: 245; sh: 102
file content (399 lines) | stat: -rw-r--r-- 11,758 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.

This file is part of Quake III Arena source code.

Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.

Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
===========================================================================
*/

#include "quakedef.h"

#include <limits.h>
#include <pthread.h>

#include <CoreAudio/AudioHardware.h>

#include "snd_main.h"


#define CHUNK_SIZE 1024

static unsigned int submissionChunk = 0;  // in sample frames
static unsigned int coreaudiotime = 0;  // based on the number of chunks submitted so far
static qboolean s_isRunning = false;
static pthread_mutex_t coreaudio_mutex;
static AudioDeviceID outputDeviceID = kAudioDeviceUnknown;
static short *mixbuffer = NULL;


/*
====================
audioDeviceIOProc
====================
*/
static OSStatus audioDeviceIOProc(AudioDeviceID inDevice,
								  const AudioTimeStamp *inNow,
								  const AudioBufferList *inInputData,
								  const AudioTimeStamp *inInputTime,
								  AudioBufferList *outOutputData,
								  const AudioTimeStamp *inOutputTime,
								  void *inClientData)
{
	float *outBuffer;
	unsigned int frameCount, factor, sampleIndex;
	float scale = 1.0f / SHRT_MAX;

	outBuffer = (float*)outOutputData->mBuffers[0].mData;
	factor = snd_renderbuffer->format.channels * snd_renderbuffer->format.width;
	frameCount = 0;
	if (snd_blocked)
		scale = 0;

	// Lock the snd_renderbuffer
	if (SndSys_LockRenderBuffer())
	{
		unsigned int maxFrames, sampleCount;
		unsigned int startOffset, endOffset;
		const short *samples;

		if (snd_usethreadedmixing)
		{
			S_MixToBuffer(mixbuffer, submissionChunk);
			sampleCount = submissionChunk * snd_renderbuffer->format.channels;
			for (sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++)
				outBuffer[sampleIndex] = mixbuffer[sampleIndex] * scale;
			// unlock the mutex now
			SndSys_UnlockRenderBuffer();
			return 0;
		}

		// Transfert up to a chunk of sample frames from snd_renderbuffer to outBuffer
		maxFrames = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
		if (maxFrames >= submissionChunk)
			frameCount = submissionChunk;
		else
			frameCount = maxFrames;

		// Convert the samples from shorts to floats.  Scale the floats to be [-1..1].
		startOffset = snd_renderbuffer->startframe % snd_renderbuffer->maxframes;
		endOffset = (snd_renderbuffer->startframe + frameCount) % snd_renderbuffer->maxframes;
		if (startOffset > endOffset)  // if the buffer wraps
		{
			sampleCount = (snd_renderbuffer->maxframes - startOffset) * snd_renderbuffer->format.channels;
			samples = (const short*)(&snd_renderbuffer->ring[startOffset * factor]);
			for (sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++)
				outBuffer[sampleIndex] = samples[sampleIndex] * scale;

			outBuffer = &outBuffer[sampleCount];
			sampleCount = frameCount * snd_renderbuffer->format.channels - sampleCount;
			samples = (const short*)(&snd_renderbuffer->ring[0]);
			for (sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++)
				outBuffer[sampleIndex] = samples[sampleIndex] * scale;
		}
		else
		{
			sampleCount = frameCount * snd_renderbuffer->format.channels;
			samples = (const short*)(&snd_renderbuffer->ring[startOffset * factor]);
			for (sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++)
				outBuffer[sampleIndex] = samples[sampleIndex] * scale;
		}

		snd_renderbuffer->startframe += frameCount;

		// unlock the mutex now
		SndSys_UnlockRenderBuffer();
	}

	// If there was not enough samples, complete with silence samples
	if (frameCount < submissionChunk)
	{
		unsigned int missingFrames;

		missingFrames = submissionChunk - frameCount;
		if (developer_insane.integer && vid_activewindow)
			Con_DPrintf("audioDeviceIOProc: %u sample frames missing\n", missingFrames);
		memset(&outBuffer[frameCount * snd_renderbuffer->format.channels], 0, missingFrames * sizeof(outBuffer[0]));
	}

	coreaudiotime += submissionChunk;
	return 0;
}


/*
====================
SndSys_Init

Create "snd_renderbuffer" with the proper sound format if the call is successful
May return a suggested format if the requested format isn't available
====================
*/
qboolean SndSys_Init (const snd_format_t* requested, snd_format_t* suggested)
{
	OSStatus status;
	UInt32 propertySize, bufferByteCount;
	AudioStreamBasicDescription streamDesc;

	if (s_isRunning)
		return true;

	Con_Printf("Initializing CoreAudio...\n");
	snd_threaded = false;

	if(requested->width != 2)
	{
		// we can only do 16bit per sample for now
		if(suggested != NULL)
		{
			memcpy (suggested, requested, sizeof (*suggested));
			suggested->width = 2;
		}
		return false;
	}

	// Get the output device
	propertySize = sizeof(outputDeviceID);
	status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &outputDeviceID);
	if (status)
	{
		Con_Printf("CoreAudio: AudioDeviceGetProperty() returned %d when getting kAudioHardwarePropertyDefaultOutputDevice\n", (int)status);
		return false;
	}
	if (outputDeviceID == kAudioDeviceUnknown)
	{
		Con_Printf("CoreAudio: outputDeviceID is kAudioDeviceUnknown\n");
		return false;
	}

	// Configure the output device
	propertySize = sizeof(bufferByteCount);
	bufferByteCount = CHUNK_SIZE * sizeof(float) * requested->channels;
	status = AudioDeviceSetProperty(outputDeviceID, NULL, 0, false, kAudioDevicePropertyBufferSize, propertySize, &bufferByteCount);
	if (status)
	{
		Con_Printf("CoreAudio: AudioDeviceSetProperty() returned %d when setting kAudioDevicePropertyBufferSize to %d\n", (int)status, CHUNK_SIZE);
		return false;
	}

	propertySize = sizeof(bufferByteCount);
	status = AudioDeviceGetProperty(outputDeviceID, 0, false, kAudioDevicePropertyBufferSize, &propertySize, &bufferByteCount);
	if (status)
	{
		Con_Printf("CoreAudio: AudioDeviceGetProperty() returned %d when setting kAudioDevicePropertyBufferSize\n", (int)status);
		return false;
	}

	submissionChunk = bufferByteCount / sizeof(float);
	if (submissionChunk % requested->channels != 0)
	{
		Con_Print("CoreAudio: chunk size is NOT a multiple of the number of channels\n");
		return false;
	}
	submissionChunk /= requested->channels;
	Con_Printf("   Chunk size = %d sample frames\n", submissionChunk);

	// Print out the device status
	propertySize = sizeof(streamDesc);
	status = AudioDeviceGetProperty(outputDeviceID, 0, false, kAudioDevicePropertyStreamFormat, &propertySize, &streamDesc);
	if (status)
	{
		Con_Printf("CoreAudio: AudioDeviceGetProperty() returned %d when getting kAudioDevicePropertyStreamFormat\n", (int)status);
		return false;
	}

	Con_Print ("   Hardware format:\n");
	Con_Printf("    %5d mSampleRate\n", (unsigned int)streamDesc.mSampleRate);
	Con_Printf("     %c%c%c%c mFormatID\n",
				(char)(streamDesc.mFormatID >> 24),
				(char)(streamDesc.mFormatID >> 16),
				(char)(streamDesc.mFormatID >>  8),
				(char)(streamDesc.mFormatID >>  0));
	Con_Printf("    %5u mBytesPerPacket\n", (unsigned int)streamDesc.mBytesPerPacket);
	Con_Printf("    %5u mFramesPerPacket\n", (unsigned int)streamDesc.mFramesPerPacket);
	Con_Printf("    %5u mBytesPerFrame\n", (unsigned int)streamDesc.mBytesPerFrame);
	Con_Printf("    %5u mChannelsPerFrame\n", (unsigned int)streamDesc.mChannelsPerFrame);
	Con_Printf("    %5u mBitsPerChannel\n", (unsigned int)streamDesc.mBitsPerChannel);

	// Suggest proper settings if they differ
	if (requested->channels != streamDesc.mChannelsPerFrame || requested->speed != streamDesc.mSampleRate)
	{
		if (suggested != NULL)
		{
			memcpy (suggested, requested, sizeof (*suggested));
			suggested->channels = streamDesc.mChannelsPerFrame;
			suggested->speed = streamDesc.mSampleRate;
		}
		return false;
	}

	if(streamDesc.mFormatID == kAudioFormatLinearPCM)
	{
		// Add the callback function
		status = AudioDeviceAddIOProc(outputDeviceID, audioDeviceIOProc, NULL);
		if (!status)
		{
			// We haven't sent any sample frames yet
			coreaudiotime = 0;
			if (pthread_mutex_init(&coreaudio_mutex, NULL) == 0)
			{
				if ((snd_renderbuffer = Snd_CreateRingBuffer(requested, 0, NULL)))
				{
					if ((mixbuffer = Mem_Alloc(snd_mempool, CHUNK_SIZE * sizeof(*mixbuffer) * requested->channels)))
					{
						// Start sound running
						status = AudioDeviceStart(outputDeviceID, audioDeviceIOProc);
						if (!status)
						{
							s_isRunning = true;
							snd_threaded = true;
							Con_Print("   Initialization successful\n");
							return true;
						}
						else
							Con_Printf("CoreAudio: AudioDeviceStart() returned %d\n", (int)status);
						Mem_Free(mixbuffer);
						mixbuffer = NULL;
					}
					else
						Con_Print("CoreAudio: can't allocate memory for mixbuffer\n");
					Mem_Free(snd_renderbuffer->ring);
					Mem_Free(snd_renderbuffer);
					snd_renderbuffer = NULL;
				}
				else
					Con_Print("CoreAudio: can't allocate memory for ringbuffer\n");
				pthread_mutex_destroy(&coreaudio_mutex);
			}
			else
				Con_Print("CoreAudio: can't create pthread mutex\n");
			AudioDeviceRemoveIOProc(outputDeviceID, audioDeviceIOProc);
		}
		else
			Con_Printf("CoreAudio: AudioDeviceAddIOProc() returned %d\n", (int)status);
	}
	else
		Con_Print("CoreAudio: Default audio device doesn't support linear PCM!\n");
	return false;
}


/*
====================
SndSys_Shutdown

Stop the sound card, delete "snd_renderbuffer" and free its other resources
====================
*/
void SndSys_Shutdown(void)
{
	OSStatus status;

	if (!s_isRunning)
		return;

	status = AudioDeviceStop(outputDeviceID, audioDeviceIOProc);
	if (status)
	{
		Con_Printf("AudioDeviceStop: returned %d\n", (int)status);
		return;
	}
	s_isRunning = false;

	pthread_mutex_destroy(&coreaudio_mutex);

	status = AudioDeviceRemoveIOProc(outputDeviceID, audioDeviceIOProc);
	if (status)
	{
		Con_Printf("AudioDeviceRemoveIOProc: returned %d\n", (int)status);
		return;
	}

	if (snd_renderbuffer != NULL)
	{
		Mem_Free(snd_renderbuffer->ring);
		Mem_Free(snd_renderbuffer);
		snd_renderbuffer = NULL;
	}

	if (mixbuffer != NULL)
		Mem_Free(mixbuffer);
	mixbuffer = NULL;
}


/*
====================
SndSys_Submit

Submit the contents of "snd_renderbuffer" to the sound card
====================
*/
void SndSys_Submit (void)
{
	// Nothing to do here (this sound module is callback-based)
}


/*
====================
SndSys_GetSoundTime

Returns the number of sample frames consumed since the sound started
====================
*/
unsigned int SndSys_GetSoundTime (void)
{
	return coreaudiotime;
}


/*
====================
SndSys_LockRenderBuffer

Get the exclusive lock on "snd_renderbuffer"
====================
*/
qboolean SndSys_LockRenderBuffer (void)
{
	return (pthread_mutex_lock(&coreaudio_mutex) == 0);
}


/*
====================
SndSys_UnlockRenderBuffer

Release the exclusive lock on "snd_renderbuffer"
====================
*/
void SndSys_UnlockRenderBuffer (void)
{
	pthread_mutex_unlock(&coreaudio_mutex);
}

/*
====================
SndSys_SendKeyEvents

Send keyboard events originating from the sound system (e.g. MIDI)
====================
*/
void SndSys_SendKeyEvents(void)
{
	// not supported
}