aboutsummaryrefslogtreecommitdiffstats
path: root/code/macosx/macosx_sndcore.m
blob: d478ea0263a03dd0c1bbe55c24e6c6600305efc8 (plain)
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
/*
===========================================================================
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
===========================================================================
*/

// mac_snddma.c
// all other sound mixing is portable

#include "../client/snd_local.h"

#include <CoreServices/CoreServices.h>
#include <CoreAudio/AudioHardware.h>
#include <QuickTime/QuickTime.h>

// For 'ri'
#include "../renderer/tr_local.h"

#import <Foundation/NSData.h>
#import <Foundation/NSString.h>

static unsigned int  submissionChunk;
static unsigned int  maxMixedSamples;
static short       *s_mixedSamples;
static int          s_chunkCount;		// number of chunks submitted
static qboolean     s_isRunning;

static AudioDeviceID outputDeviceID;
static AudioStreamBasicDescription outputStreamBasicDescription;

/*
===============
audioDeviceIOProc
===============
*/

OSStatus audioDeviceIOProc(AudioDeviceID inDevice,
                           const AudioTimeStamp *inNow,
                           const AudioBufferList *inInputData,
                           const AudioTimeStamp *inInputTime,
                           AudioBufferList *outOutputData,
                           const AudioTimeStamp *inOutputTime,
                           void *inClientData)
{
    int           offset;
    short        *samples;
    unsigned int  sampleIndex;
    float        *outBuffer;
    float         scale, temp;

    offset = ( s_chunkCount * submissionChunk ) % maxMixedSamples;
    samples = s_mixedSamples + offset;

    assert(outOutputData->mNumberBuffers == 1);
    assert(outOutputData->mBuffers[0].mNumberChannels == 2);
    //assert(outOutputData->mBuffers[0].mDataByteSize == (dma.submission_chunk * sizeof(float)));

    outBuffer = (float *)outOutputData->mBuffers[0].mData;
    
    // If we have run out of samples, return silence
    if (s_chunkCount * submissionChunk > dma.channels * s_paintedtime) {
        memset(outBuffer, 0, sizeof(*outBuffer) * dma.submission_chunk);
    } else {
        scale = (1.0f / SHRT_MAX);
        if (outputStreamBasicDescription.mSampleRate == 44100  && dma.speed == 22050) {
            for (sampleIndex = 0; sampleIndex < dma.submission_chunk; sampleIndex+=2) {
                // Convert the samples from shorts to floats.  Scale the floats to be [-1..1].
                temp = samples[sampleIndex + 0] * scale;
                outBuffer[(sampleIndex<<1)+0] = temp;
                outBuffer[(sampleIndex<<1)+2] = temp;

                temp = samples[sampleIndex + 1] * scale;
                outBuffer[(sampleIndex<<1)+1] = temp;
                outBuffer[(sampleIndex<<1)+3] = temp;
            }
        } else if (outputStreamBasicDescription.mSampleRate == 44100  && dma.speed == 11025) {
            for (sampleIndex = 0; sampleIndex < dma.submission_chunk; sampleIndex+=4) {
                // Convert the samples from shorts to floats.  Scale the floats to be [-1..1].
                temp = samples[sampleIndex + 0] * scale;
                outBuffer[(sampleIndex<<1)+0] = temp;
                outBuffer[(sampleIndex<<1)+2] = temp;
                outBuffer[(sampleIndex<<1)+4] = temp;
                outBuffer[(sampleIndex<<1)+6] = temp;

                temp = samples[sampleIndex + 1] * scale;
                outBuffer[(sampleIndex<<1)+1] = temp;
                outBuffer[(sampleIndex<<1)+3] = temp;
                outBuffer[(sampleIndex<<1)+5] = temp;
                outBuffer[(sampleIndex<<1)+7] = temp;
            }
        } else {
            for (sampleIndex = 0; sampleIndex < dma.submission_chunk; sampleIndex++) {
                // Convert the samples from shorts to floats.  Scale the floats to be [-1..1].
                outBuffer[sampleIndex] = samples[sampleIndex] * scale;
            }
        }
    }
    
    s_chunkCount++; // this is the next buffer we will submit
    return 0;
}


/*
===============
S_MakeTestPattern
===============
*/
void S_MakeTestPattern( void ) {
    int i;
    float v;
    int sample;
    
    for ( i = 0 ; i < dma.samples / 2 ; i ++ ) {
        v = sin( M_PI * 2 * i / 64 );
        sample = v * 0x4000;
        ((short *)dma.buffer)[i*2] = sample;	
        ((short *)dma.buffer)[i*2+1] = sample;	
    }
}

/*
===============
SNDDMA_Init
===============
*/
qboolean SNDDMA_Init(void)
{
    cvar_t *bufferSize;
    cvar_t *chunkSize;
    OSStatus status;
    UInt32 propertySize, bufferByteCount;

    if (s_isRunning)
        return qtrue;
        
    chunkSize = ri.Cvar_Get( "s_chunksize", "2048", CVAR_ARCHIVE );
    bufferSize = ri.Cvar_Get( "s_buffersize", "16384", CVAR_ARCHIVE );
    Com_Printf(" Chunk size = %d\n", chunkSize->integer);
    Com_Printf("Buffer size = %d\n", bufferSize->integer);

    if (!chunkSize->integer)
        ri.Error(ERR_FATAL, "s_chunksize must be non-zero\n");
    if (!bufferSize->integer)
        ri.Error(ERR_FATAL, "s_buffersize must be non-zero\n");
    if (chunkSize->integer >= bufferSize->integer)
        ri.Error(ERR_FATAL, "s_chunksize must be less than s_buffersize\n");
    if (bufferSize->integer % chunkSize->integer)
        ri.Error(ERR_FATAL, "s_buffersize must be an even multiple of s_chunksize\n");

    // Get the output device
    propertySize = sizeof(outputDeviceID);
    status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &outputDeviceID);
    if (status) {
        Com_Printf("AudioHardwareGetProperty returned %d\n", status);
        return qfalse;
    }
	
    if (outputDeviceID == kAudioDeviceUnknown) {
        Com_Printf("AudioHardwareGetProperty: outputDeviceID is kAudioDeviceUnknown\n");
        return qfalse;
    }

    // Configure the output device	
    propertySize = sizeof(bufferByteCount);
    bufferByteCount = chunkSize->integer * sizeof(float);
    status = AudioDeviceSetProperty(outputDeviceID, NULL, 0, NO, kAudioDevicePropertyBufferSize, propertySize, &bufferByteCount);
    if (status) {
        Com_Printf("AudioDeviceSetProperty: returned %d when setting kAudioDevicePropertyBufferSize to %d\n", status, chunkSize->integer);
        return qfalse;
    }
    
    propertySize = sizeof(bufferByteCount);
    status = AudioDeviceGetProperty(outputDeviceID, 0, NO, kAudioDevicePropertyBufferSize, &propertySize, &bufferByteCount);
    if (status) {
        Com_Printf("AudioDeviceGetProperty: returned %d when setting kAudioDevicePropertyBufferSize\n", status);
        return qfalse;
    }

    // Print out the device status
    propertySize = sizeof(outputStreamBasicDescription);
    status = AudioDeviceGetProperty(outputDeviceID, 0, NO, kAudioDevicePropertyStreamFormat, &propertySize, &outputStreamBasicDescription);
    if (status) {
        Com_Printf("AudioDeviceGetProperty: returned %d when getting kAudioDevicePropertyStreamFormat\n", status);
        return qfalse;
    }

    Com_Printf("Hardware format:\n");
    Com_Printf("  %f mSampleRate\n", outputStreamBasicDescription.mSampleRate);
    Com_Printf("  %c%c%c%c mFormatID\n",
               (outputStreamBasicDescription.mFormatID & 0xff000000) >> 24,
               (outputStreamBasicDescription.mFormatID & 0x00ff0000) >> 16,
               (outputStreamBasicDescription.mFormatID & 0x0000ff00) >>  8,
               (outputStreamBasicDescription.mFormatID & 0x000000ff) >>  0);
    Com_Printf("  %5d mBytesPerPacket\n", outputStreamBasicDescription.mBytesPerPacket);
    Com_Printf("  %5d mFramesPerPacket\n", outputStreamBasicDescription.mFramesPerPacket);
    Com_Printf("  %5d mBytesPerFrame\n", outputStreamBasicDescription.mBytesPerFrame);
    Com_Printf("  %5d mChannelsPerFrame\n", outputStreamBasicDescription.mChannelsPerFrame);
    Com_Printf("  %5d mBitsPerChannel\n", outputStreamBasicDescription.mBitsPerChannel);

    if(outputStreamBasicDescription.mFormatID != kAudioFormatLinearPCM) {
            Com_Printf("Default Audio Device doesn't support Linear PCM!");
            return qfalse;
    }
    
    // Start sound running
    status = AudioDeviceAddIOProc(outputDeviceID, audioDeviceIOProc, NULL);
    if (status) {
        Com_Printf("AudioDeviceAddIOProc: returned %d\n", status);
        return qfalse;
    }

    submissionChunk = chunkSize->integer;
    if (outputStreamBasicDescription.mSampleRate == 44100) {
        submissionChunk = chunkSize->integer/2;
    }
    maxMixedSamples = bufferSize->integer;
    s_mixedSamples = calloc(1, sizeof(*s_mixedSamples) * maxMixedSamples);
    Com_Printf("Chunk Count = %d\n", (maxMixedSamples / submissionChunk));
    
    // Tell the main app what we expect from it
    dma.samples = maxMixedSamples;
    dma.submission_chunk = submissionChunk;
    dma.samplebits = 16;
    dma.buffer = (byte *)s_mixedSamples;
    dma.channels = outputStreamBasicDescription.mChannelsPerFrame;
    dma.speed = 22050;	//(unsigned long)outputStreamBasicDescription.mSampleRate;

    // We haven't enqueued anything yet
    s_chunkCount = 0;

    status = AudioDeviceStart(outputDeviceID, audioDeviceIOProc);
    if (status) {
        Com_Printf("AudioDeviceStart: returned %d\n", status);
        return qfalse;
    }

    s_isRunning = qtrue;
    
    return qtrue;
}

/*
===============
SNDDMA_GetBufferDuration
===============
*/
float SNDDMA_GetBufferDuration(void)
{
    return (float)dma.samples / (float)(dma.channels * dma.speed);
}

/*
===============
SNDDMA_GetDMAPos
===============
*/
int SNDDMA_GetDMAPos(void)
{
    return s_chunkCount * dma.submission_chunk;
}

/*
===============
SNDDMA_Shutdown
===============
*/
void SNDDMA_Shutdown(void)
{
    OSStatus status;
    
    if (!s_isRunning)
        return;
        
    status = AudioDeviceStop(outputDeviceID, audioDeviceIOProc);
    if (status) {
        Com_Printf("AudioDeviceStop: returned %d\n", status);
        return;
    }
    
    s_isRunning = qfalse;
    
    status = AudioDeviceRemoveIOProc(outputDeviceID, audioDeviceIOProc);
    if (status) {
        Com_Printf("AudioDeviceRemoveIOProc: returned %d\n", status);
        return;
    }
    
    free(s_mixedSamples);
    s_mixedSamples = NULL;
    dma.samples = NULL;
}

/*
===============
SNDDMA_BeginPainting
===============
*/
void SNDDMA_BeginPainting(void) {
}

/*
===============
SNDDMA_Submit
===============
*/
void SNDDMA_Submit(void) {
}