Ticket #13412: patch-src__plugins__macosx__ao_macosx.c

File patch-src__plugins__macosx__ao_macosx.c, 27.2 KB (added by mike@…, 16 years ago)

Revised patch, that takes PPC machines into account

Line 
1--- src/plugins/macosx/ao_macosx.c.orig 2004-11-09 09:20:26.000000000 +0100
2+++ src/plugins/macosx/ao_macosx.c      2007-11-30 13:37:22.000000000 +0100
3@@ -29,7 +29,7 @@
4   audio samples rather than having them pushed at it (which is nice
5   when you are wanting to do good buffering of audio).  */
6 
7-#include <CoreAudio/AudioHardware.h>
8+#include <AudioUnit/AudioUnit.h>
9 #include <stdio.h>
10 #include <pthread.h>
11 
12@@ -39,8 +39,7 @@
13 // Set this to 1 to see FIFO debugging messages
14 #define DEBUG_PIPE 0
15 
16-//#define BUFFER_COUNT (323)
17-#define BUFFER_COUNT (2)
18+#define DEFAULT_BUFFER_TIME (250);
19 
20 #ifndef MIN
21 #define MIN(a,b) ((a) < (b) ? (a) : (b))
22@@ -52,9 +51,9 @@
23 static ao_info ao_macosx_info =
24 {
25        AO_TYPE_LIVE,
26-       "MacOS X output",
27-       "macosx",
28-       "Timothy J. Wood <tjw@omnigroup.com>",
29+       "MacOS X AUHAL output",
30+       "macosxau",
31+       "Michael Guntsche <mike@it-loops.com>",
32        "",
33        AO_FMT_NATIVE,
34        30,
35@@ -65,374 +64,407 @@
36 
37 typedef struct ao_macosx_internal
38 {
39-    // Stuff describing the CoreAudio device
40-    AudioDeviceID                outputDeviceID;
41-    AudioStreamBasicDescription  outputStreamBasicDescription;
42-   
43-    // The amount of data CoreAudio wants each time it calls our IO function
44-    UInt32                       outputBufferByteCount;
45-   
46-    // Keep track of whether the output stream has actually been started/stopped
47-    Boolean                      started;
48-    Boolean                      isStopping;
49-   
50-    // Synchronization objects between the CoreAudio thread and the enqueuing thread
51-    pthread_mutex_t              mutex;
52-    pthread_cond_t               condition;
53-
54-    // Our internal queue of samples waiting to be consumed by CoreAudio
55-    void                        *buffer;
56-    unsigned int                 bufferByteCount;
57-    unsigned int                 firstValidByteOffset;
58-    unsigned int                 validByteCount;
59-   
60-    // Temporary debugging state
61-    unsigned int bytesQueued;
62-    unsigned int bytesDequeued;
63+  // Stuff describing the CoreAudio device
64+  AudioUnit                    outputAudioUnit;
65+
66+  // Keep track of whether the output stream has actually been started/stopped
67+  Boolean                      started;
68+  Boolean                      isStopping;
69+
70+  // Synchronization objects between the CoreAudio thread and the enqueuing thread
71+  pthread_mutex_t              mutex;
72+  pthread_cond_t               condition;
73+
74+  // Our internal queue of samples waiting to be consumed by CoreAudio
75+  void                        *buffer;
76+  unsigned int                 bufferByteCount;
77+  unsigned int                 firstValidByteOffset;
78+  unsigned int                 validByteCount;
79+
80+  unsigned int                 buffer_time;
81+  // Temporary debugging state
82+  unsigned int bytesQueued;
83+  unsigned int bytesDequeued;
84 } ao_macosx_internal;
85 
86 // The function that the CoreAudio thread calls when it wants more data
87-static OSStatus audioDeviceIOProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData);
88+static OSStatus     audioCallback (void                             *inRefCon, 
89+                                                                  AudioUnitRenderActionFlags      inActionFlags,
90+                                                                  const AudioTimeStamp            *inTimeStamp, 
91+                                                                  UInt32                          inBusNumber, 
92+                                                                  AudioBuffer                     *ioData)
93+
94+{
95+  ao_macosx_internal *internal = (ao_macosx_internal *)inRefCon;
96+  short *sample;
97+  unsigned int validByteCount;
98+  unsigned char *outBuffer;
99+  unsigned int bytesToCopy, samplesToCopy, firstFrag;
100+
101+
102+
103+  // Find the first valid frame and the number of valid frames
104+  pthread_mutex_lock(&internal->mutex);
105+
106+
107+  bytesToCopy = ioData->mDataByteSize;
108+  firstFrag = bytesToCopy;
109+  validByteCount = internal->validByteCount;
110+  outBuffer = ioData->mData;
111+
112+
113+#if DEBUG_PIPE
114+  fprintf(stderr,"BTC: %i Valid: %i\n",bytesToCopy,validByteCount);
115+#endif
116+
117+  if (validByteCount < bytesToCopy && !internal->isStopping) {
118+    // Not enough data ... let it build up a bit more before we start copying stuff over.
119+    // If we are stopping, of course, we should just copy whatever we have.
120+    // This also happens if an application pauses output.
121+    inActionFlags = kAudioUnitRenderAction_OutputIsSilence;
122+    memset(outBuffer, 0, ioData->mDataByteSize);
123+    pthread_mutex_unlock(&internal->mutex);
124+    return 0;
125+  }
126+
127+
128+  bytesToCopy = MIN(bytesToCopy, validByteCount);
129+  sample = internal->buffer + internal->firstValidByteOffset;
130+  samplesToCopy = bytesToCopy / sizeof(*sample);
131+
132+  /* Check if we habe a wrap around in the ring buffer
133+   * If yes then find out how many bytes we have */
134+  if (internal->firstValidByteOffset + bytesToCopy > internal->bufferByteCount) 
135+    firstFrag = internal->bufferByteCount - internal->firstValidByteOffset;
136+
137+  #if DEBUG_PIPE
138+  fprintf(stderr, "IO: firstValid=%d valid=%d toCopy=%d queued=%d dequeued=%d sample=0x%08x\n",
139+     
140+      internal->firstValidByteOffset, internal->validByteCount, samplesToCopy, internal->bytesQueued, internal->bytesDequeued, sample);
141+  #endif
142+
143+  internal->validByteCount -= bytesToCopy;
144+  internal->firstValidByteOffset = (internal->firstValidByteOffset + bytesToCopy) % internal->bufferByteCount;
145+
146+  /* If we have a wraparound first copy the remaining bytes off the end
147+   * and then the rest from the beginning of the ringbuffer */
148+  if (firstFrag < bytesToCopy) {
149+    memcpy(outBuffer,sample,firstFrag);
150+    memcpy(outBuffer+firstFrag,internal->buffer,bytesToCopy-firstFrag);
151+  }
152+  else {
153+    memcpy(outBuffer,sample,bytesToCopy);
154+  }
155+
156+  pthread_mutex_unlock(&internal->mutex);
157+  pthread_cond_signal(&internal->condition);
158+
159+  return 0;
160+}
161+
162+
163+
164 
165 int ao_plugin_test()
166 {
167       
168-       if (/* FIXME */ 0 )
169-               return 0; /* Cannot use this plugin with default parameters */
170-       else {
171-               return 1; /* This plugin works in default mode */
172-       }
173+  if (/* FIXME */ 0 )
174+    return 0; /* Cannot use this plugin with default parameters */
175+  else {
176+    return 1; /* This plugin works in default mode */
177+  }
178 }
179 
180 ao_info *ao_plugin_driver_info(void)
181 {
182-       return &ao_macosx_info;
183+  return &ao_macosx_info;
184 }
185 
186 
187 int ao_plugin_device_init(ao_device *device)
188 {
189-       ao_macosx_internal *internal;
190+  ao_macosx_internal *internal;
191 
192-       internal = (ao_macosx_internal *) malloc(sizeof(ao_macosx_internal));
193+  internal = (ao_macosx_internal *) malloc(sizeof(ao_macosx_internal));
194 
195-       if (internal == NULL)   
196-               return 0; /* Could not initialize device memory */
197-       
198+  if (internal == NULL)       
199+    return 0; /* Could not initialize device memory */
200 
201-       
202-       device->internal = internal;
203+  internal->buffer_time = DEFAULT_BUFFER_TIME;
204 
205-       return 1; /* Memory alloc successful */
206-}
207+  device->internal = internal;
208 
209+  return 1; /* Memory alloc successful */
210+  }
211 
212-int ao_plugin_set_option(ao_device *device, const char *key, const char *value)
213-{
214-       ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
215 
216-       /* No options */
217-
218-       return 1;
219+int ao_plugin_set_option(ao_device *device, const char *key, const char *value)
220+  {
221+  ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
222+  int buffer;
223+
224+  if (!strcmp(key,"buffer_time")) {
225+    buffer = atoi(value);
226+    if (buffer < 100) {
227+      fprintf(stderr,"Buffer time clipped to 100ms\n");
228+      buffer = DEFAULT_BUFFER_TIME;
229+    }
230+    internal->buffer_time = buffer;
231+  }
232+ 
233+  /* No options */
234+  return 1;
235 }
236 
237 
238 int ao_plugin_open(ao_device *device, ao_sample_format *format)
239 {
240-    ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
241-    OSStatus status;
242-    UInt32 propertySize;
243-    int rc;
244-   
245-    if (format->rate != 44100) {
246-        fprintf(stderr, "ao_macosx_open: Only support 44.1kHz right now\n");
247-        return 0;
248-    }
249-   
250-    if (format->channels != 2) {
251-        fprintf(stderr, "ao_macosx_open: Only two channel audio right now\n");
252-        return 0;
253-    }
254+  ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
255 
256-    propertySize = sizeof(internal->outputDeviceID);
257-    status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &(internal->outputDeviceID));
258-    if (status) {
259-        fprintf(stderr, "ao_macosx_open: AudioHardwareGetProperty returned %d\n", (int)status);
260-       return 0;
261-    }
262-   
263-    if (internal->outputDeviceID == kAudioDeviceUnknown) {
264-        fprintf(stderr, "ao_macosx_open: AudioHardwareGetProperty: outputDeviceID is kAudioDeviceUnknown\n");
265-       return 0;
266-    }
267-   
268-    propertySize = sizeof(internal->outputStreamBasicDescription);
269-    status = AudioDeviceGetProperty(internal->outputDeviceID, 0, false, kAudioDevicePropertyStreamFormat, &propertySize, &internal->outputStreamBasicDescription);
270-    if (status) {
271-        fprintf(stderr, "ao_macosx_open: AudioDeviceGetProperty returned %d when getting kAudioDevicePropertyStreamFormat\n", (int)status);
272-       return 0;
273-    }
274+  OSStatus result = noErr;
275+  Component comp;
276+  ComponentDescription desc;
277+  struct AudioUnitInputCallback callback;
278+  AudioStreamBasicDescription requestedDesc;
279+  UInt32 i_param_size;
280+  int rc;
281+
282+
283+  /* Setup a AudioStreamBasicDescription with the requested format */
284+  requestedDesc.mFormatID = kAudioFormatLinearPCM;
285+  requestedDesc.mFormatFlags = kAudioFormatFlagIsPacked;
286+
287+       if (ao_is_big_endian())
288+               requestedDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;
289+
290+  if (format->bits > 8)
291+    requestedDesc.mFormatFlags |= kAudioFormatFlagIsSignedInteger;
292+
293+  requestedDesc.mChannelsPerFrame = format->channels;
294+  requestedDesc.mSampleRate = format->rate;
295+  requestedDesc.mBitsPerChannel = format->bits;
296+  requestedDesc.mFramesPerPacket = 1;
297+  requestedDesc.mBytesPerFrame = requestedDesc.mBitsPerChannel * requestedDesc.mChannelsPerFrame / 8;
298+  requestedDesc.mBytesPerPacket = requestedDesc.mBytesPerFrame * requestedDesc.mFramesPerPacket;
299+
300+  /* Locate the default output audio unit */
301+  desc.componentType = kAudioUnitComponentType;
302+  desc.componentSubType = kAudioUnitSubType_Output;
303+  desc.componentManufacturer = kAudioUnitID_DefaultOutput;
304+  desc.componentFlags = 0;
305+  desc.componentFlagsMask = 0;
306+
307+
308+  comp = FindNextComponent (NULL, &desc);
309+  if (comp == NULL) {
310+    fprintf (stderr,"Failed to start CoreAudio: FindNextComponent returned NULL");
311+    return 0;
312+  }
313 
314-    fprintf(stderr, "hardware format...\n");
315-    fprintf(stderr, "%f mSampleRate\n", internal->outputStreamBasicDescription.mSampleRate);
316-    fprintf(stderr, "%c%c%c%c mFormatID\n", (int)(internal->outputStreamBasicDescription.mFormatID & 0xff000000) >> 24,
317-                                            (int)(internal->outputStreamBasicDescription.mFormatID & 0x00ff0000) >> 16,
318-                                            (int)(internal->outputStreamBasicDescription.mFormatID & 0x0000ff00) >>  8,
319-                                            (int)(internal->outputStreamBasicDescription.mFormatID & 0x000000ff) >>  0);
320-    fprintf(stderr, "%5d mBytesPerPacket\n", (int)internal->outputStreamBasicDescription.mBytesPerPacket);
321-    fprintf(stderr, "%5d mFramesPerPacket\n", (int)internal->outputStreamBasicDescription.mFramesPerPacket);
322-    fprintf(stderr, "%5d mBytesPerFrame\n", (int)internal->outputStreamBasicDescription.mBytesPerFrame);
323-    fprintf(stderr, "%5d mChannelsPerFrame\n", (int)internal->outputStreamBasicDescription.mChannelsPerFrame);
324-
325-    if (internal->outputStreamBasicDescription.mFormatID != kAudioFormatLinearPCM) {
326-        fprintf(stderr, "ao_macosx_open: Default Audio Device doesn't support Linear PCM!\n");
327-       return 0;
328-    }
329+  /* Open & initialize the default output audio unit */
330+    result = OpenAComponent (comp, &internal->outputAudioUnit);
331+  if (result) 
332+    fprintf(stderr,"Comp error\n");
333+  result = AudioUnitInitialize (internal->outputAudioUnit);
334+  if (result) 
335+    fprintf(stderr,"Init error\n");
336+
337+  /* Set the audio callback */
338+  callback.inputProc = audioCallback;
339+  callback.inputProcRefCon = internal;
340+  result = AudioUnitSetProperty (internal->outputAudioUnit, 
341+      kAudioUnitProperty_SetInputCallback, 
342+      kAudioUnitScope_Input, 
343+      0,
344+      &callback, 
345+      sizeof(callback));
346 
347-    propertySize = sizeof(internal->outputBufferByteCount);
348-   
349-    internal->outputBufferByteCount = 8192;
350-    status = AudioDeviceSetProperty(internal->outputDeviceID, 0, 0, false, kAudioDevicePropertyBufferSize,
351-        propertySize, &internal->outputBufferByteCount);
352-       
353-    status = AudioDeviceGetProperty(internal->outputDeviceID, 0, false, kAudioDevicePropertyBufferSize, &propertySize, &internal->outputBufferByteCount);
354-    if (status) {
355-        fprintf(stderr, "ao_macosx_open: AudioDeviceGetProperty returned %d when getting kAudioDevicePropertyBufferSize\n", (int)status);
356-       return 0;
357-    }
358+  if (result) {
359 
360-    fprintf(stderr, "%5d outputBufferByteCount\n", (int)internal->outputBufferByteCount);
361+    fprintf(stderr,"Callback %i\n",result);
362+    return 0;
363+  }
364 
365-    // It appears that AudioDeviceGetProperty lies about this property in DP4
366-    // Set the actual value
367-    //internal->outputBufferByteCount = 32768;
368-
369-    // Set the IO proc that CoreAudio will call when it needs data, but don't start
370-    // the stream yet.
371-    internal->started = false;
372-    status = AudioDeviceAddIOProc(internal->outputDeviceID, audioDeviceIOProc, internal);
373-    if (status) {
374-        fprintf(stderr, "ao_macosx_open: AudioDeviceAddIOProc returned %d\n", (int)status);
375-       return 0;
376-    }
377 
378-    rc = pthread_mutex_init(&internal->mutex, NULL);
379-    if (rc) {
380-        fprintf(stderr, "ao_macosx_open: pthread_mutex_init returned %d\n", rc);
381-       return 0;
382-    }
383-   
384-    rc = pthread_cond_init(&internal->condition, NULL);
385-    if (rc) {
386-        fprintf(stderr, "ao_macosx_open: pthread_cond_init returned %d\n", rc);
387-       return 0;
388-    }
389+  /* Set the input format of the audio unit. */
390     
391-    /* Since we don't know how big to make the buffer until we open the device
392-       we allocate the buffer here instead of ao_plugin_device_init() */
393-    internal->bufferByteCount = BUFFER_COUNT * internal->outputBufferByteCount;
394-    internal->firstValidByteOffset = 0;
395-    internal->validByteCount = 0;
396-    internal->buffer = malloc(internal->bufferByteCount);
397-    memset(internal->buffer, 0, internal->bufferByteCount);
398-    if (!internal->buffer) {
399-        fprintf(stderr, "ao_macosx_open: Unable to allocate queue buffer.\n");
400-       return 0;
401-    }
402+  result = AudioUnitSetProperty (internal->outputAudioUnit,
403+                   kAudioUnitProperty_StreamFormat,
404+                   kAudioUnitScope_Input,
405+                   0,
406+                   &requestedDesc,
407+                   sizeof(AudioStreamBasicDescription));
408 
409-    /* initialize debugging state */
410-    internal->bytesQueued = 0;
411-    internal->bytesDequeued = 0;
412-   
413-    device->driver_byte_format = AO_FMT_NATIVE;
414+  if (result) {
415+
416+    fprintf(stderr,"Output %i\n",result);
417+    return 0;
418+  }
419+
420+  rc = pthread_mutex_init(&internal->mutex, NULL);
421+  if (rc) {
422+    fprintf(stderr, "ao_macosx_open: pthread_mutex_init returned %d\n", rc);
423+    return 0;
424+  }
425+
426+  rc = pthread_cond_init(&internal->condition, NULL);
427+  if (rc) {
428+    fprintf(stderr, "ao_macosx_open: pthread_cond_init returned %d\n", rc);
429+    return 0;
430+  }
431+
432+  /* Since we don't know how big to make the buffer until we open the device
433+     we allocate the buffer here instead of ao_plugin_device_init() */
434+
435+  internal->bufferByteCount =  (internal->buffer_time * format->rate / 1000) * (format->channels * format->bits / 8);
436+
437+  internal->firstValidByteOffset = 0;
438+  internal->validByteCount = 0;
439+  internal->buffer = malloc(internal->bufferByteCount);
440+  memset(internal->buffer, 0, internal->bufferByteCount);
441+  if (!internal->buffer) {
442+    fprintf(stderr, "ao_macosx_open: Unable to allocate queue buffer.\n");
443+    return 0;
444+  }
445+
446+  /* initialize debugging state */
447+  internal->bytesQueued = 0;
448+  internal->bytesDequeued = 0;
449+
450+  device->driver_byte_format = AO_FMT_NATIVE;
451+
452+
453+  return 1;
454 
455-    return 1;
456 }
457 
458 
459 int ao_plugin_play(ao_device *device, const char *output_samples, 
460                uint_32 num_bytes)
461 {
462-    ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
463-    OSStatus status;
464+  ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
465+  OSStatus status;
466+       int err;
467+  unsigned int bytesToCopy;
468+  unsigned int firstEmptyByteOffset, emptyByteCount;
469 
470-#if DEBUG_PIPE
471-    fprintf(stderr, "Enqueue: 0x%08x %d bytes\n", output_samples, num_bytes);
472-#endif
473 
474-    while (num_bytes) {
475-        unsigned int bytesToCopy;
476-        unsigned int firstEmptyByteOffset, emptyByteCount;
477-       
478-        // Get a consistent set of data about the available space in the queue,
479-        // figure out the maximum number of bytes we can copy in this chunk,
480-        // and claim that amount of space
481-        pthread_mutex_lock(&internal->mutex);
482-
483-        // Wait until there is some empty space in the queue
484-        emptyByteCount = internal->bufferByteCount - internal->validByteCount;
485-        while (emptyByteCount == 0) {
486-            pthread_cond_wait(&internal->condition, &internal->mutex);
487-            emptyByteCount = internal->bufferByteCount - internal->validByteCount;
488-        }
489-
490-        // Compute the offset to the first empty byte and the maximum number of
491-        // bytes we can copy given the fact that the empty space might wrap
492-        // around the end of the queue.
493-        firstEmptyByteOffset = (internal->firstValidByteOffset + internal->validByteCount) % internal->bufferByteCount;
494-        if (firstEmptyByteOffset + emptyByteCount > internal->bufferByteCount)
495-            bytesToCopy = MIN(num_bytes, internal->bufferByteCount - firstEmptyByteOffset);
496-        else
497-            bytesToCopy = MIN(num_bytes, emptyByteCount);
498+  while (num_bytes) {
499+               
500+    // Get a consistent set of data about the available space in the queue,
501+    // figure out the maximum number of bytes we can copy in this chunk,
502+    // and claim that amount of space
503+    pthread_mutex_lock(&internal->mutex);
504+
505+    // Wait until there is some empty space in the queue
506+    emptyByteCount = internal->bufferByteCount - internal->validByteCount;
507+    while (emptyByteCount == 0) {
508+      err = pthread_cond_wait(&internal->condition, &internal->mutex);
509+      if (err)
510+        fprintf(stderr,"Whatever: %i\n",err);
511+      emptyByteCount = internal->bufferByteCount - internal->validByteCount;
512+    }
513+
514+    // Compute the offset to the first empty byte and the maximum number of
515+    // bytes we can copy given the fact that the empty space might wrap
516+    // around the end of the queue.
517+    firstEmptyByteOffset = (internal->firstValidByteOffset + internal->validByteCount) % internal->bufferByteCount;
518+    if (firstEmptyByteOffset + emptyByteCount > internal->bufferByteCount)
519+      bytesToCopy = MIN(num_bytes, internal->bufferByteCount - firstEmptyByteOffset);
520+    else
521+      bytesToCopy = MIN(num_bytes, emptyByteCount);
522+
523+    // Copy the bytes and get ready for the next chunk, if any
524+  #if DEBUG_PIPE
525+    fprintf(stderr, "Enqueue:\tdst = 0x%08x src=0x%08x count=%d\n",
526+        internal->buffer + firstEmptyByteOffset, output_samples, bytesToCopy);
527+  #endif
528+
529+    memcpy(internal->buffer + firstEmptyByteOffset, output_samples, bytesToCopy);
530+
531+
532+
533+    num_bytes -= bytesToCopy;
534+    output_samples += bytesToCopy;
535+    internal->validByteCount += bytesToCopy;
536+
537+    internal->bytesQueued += bytesToCopy;
538+
539+    pthread_mutex_unlock(&internal->mutex);
540+
541+    // We have to wait to start the device until we have some data queued.
542+    // It might be better to wait until we have some minimum amount of data
543+    // larger than whatever blob got enqueued here, but if we had a short
544+    // stream, we'd have to make sure that ao_macosx_close() would start
545+    // AND stop the stream when it had finished.  Yuck.  If the first
546+    // blob that is passed to us is large enough (and the caller passes
547+    // data quickly enough, this shouldn't be a problem.
548+  #if 1
549+    if (!internal->started) {
550+      internal->started = true;
551+      if(AudioOutputUnitStart(internal->outputAudioUnit)) fprintf(stderr,"asdfsadf\n");
552 
553-        // Copy the bytes and get ready for the next chunk, if any
554-#if DEBUG_PIPE
555-        fprintf(stderr, "Enqueue:\tdst = 0x%08x src=0x%08x count=%d\n",
556-                internal->buffer + firstEmptyByteOffset, output_samples, bytesToCopy);
557-#endif
558-               
559-        memcpy(internal->buffer + firstEmptyByteOffset, output_samples, bytesToCopy);
560-        /*{
561-            unsigned int i;
562-            static unsigned char bufferIndex;
563-           
564-            bufferIndex++;
565-            memset(internal->buffer + firstEmptyByteOffset, bufferIndex, bytesToCopy);
566-        }*/
567-       
568-        num_bytes -= bytesToCopy;
569-        output_samples += bytesToCopy;
570-        internal->validByteCount += bytesToCopy;
571-       
572-        internal->bytesQueued += bytesToCopy;
573-       
574-        //fprintf(stderr, "Copy: %d bytes, %d bytes left\n", bytesToCopy, internal->availableByteCount);
575-        pthread_mutex_unlock(&internal->mutex);
576-       
577-        // We have to wait to start the device until we have some data queued.
578-        // It might be better to wait until we have some minimum amount of data
579-        // larger than whatever blob got enqueued here, but if we had a short
580-        // stream, we'd have to make sure that ao_macosx_close() would start
581-        // AND stop the stream when it had finished.  Yuck.  If the first
582-        // blob that is passed to us is large enough (and the caller passes
583-        // data quickly enough, this shouldn't be a problem.
584-#if 1
585-        if (!internal->started) {
586-            internal->started = true;
587-            status = AudioDeviceStart(internal->outputDeviceID, audioDeviceIOProc);
588-            if (status) {
589-                fprintf(stderr, "ao_macosx_open: AudioDeviceStart returned %d\n", (int)status);
590-               
591-                // Can we do anything useful here?  The library doesn't expect this call
592-                // to be able to fail.
593-               return 0;
594-            }
595-        }
596-#endif
597     }
598+  #endif
599+  }
600 
601-    return 1;
602+  return 1;
603 }
604 
605 
606 int ao_plugin_close(ao_device *device)
607 {
608-    ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
609-    OSStatus status;
610+  ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
611+  OSStatus status;
612+  UInt32 running;
613+  UInt32 sizeof_running;
614 
615-    // Only stop if we ever got started
616-    if (internal->started) {
617 
618-        internal->isStopping = true;
619-       
620-        // Wait for any pending data to get flushed
621-        pthread_mutex_lock(&internal->mutex);
622-        while (internal->validByteCount)
623-            pthread_cond_wait(&internal->condition, &internal->mutex);
624-        pthread_mutex_unlock(&internal->mutex);
625-       
626-        status = AudioDeviceStop(internal->outputDeviceID, audioDeviceIOProc);
627-        if (status) {
628-            fprintf(stderr, "ao_macosx_close: AudioDeviceStop returned %d\n", (int)status);
629-            return 0;
630-        }
631+
632+  // For some rare cases (using atexit in your program) Coreaudio tears
633+  // down the HAL itself, so we do not need to do that here.
634+  // We wouldn't get an error if we did, but AO would hang waiting for the AU to flush the buffer
635+  /*sizeof_running = sizeof(UInt32);
636+  AudioUnitGetProperty(internal->outputAudioUnit, 0, false, kAudioDevicePropertyDeviceIsRunning, &sizeof_running, &running);
637+  if (!running) {
638+    return 1;
639+  }
640+  */
641+
642+  // Only stop if we ever got started
643+  if (internal->started) {
644+
645+    internal->isStopping = true;
646+
647+    // Wait for any pending data to get flushed
648+    /*pthread_mutex_lock(&internal->mutex);
649+    while (internal->validByteCount)
650+      pthread_cond_wait(&internal->condition, &internal->mutex);
651+    pthread_mutex_unlock(&internal->mutex);
652+    */
653+    status = AudioOutputUnitStop(internal->outputAudioUnit);
654+    if (status) {
655+      fprintf(stderr, "ao_macosx_close: AudioDeviceStop returned %d\n", (int)status);
656+      return 0;
657     }
658-   
659-    status = AudioDeviceRemoveIOProc(internal->outputDeviceID, audioDeviceIOProc);
660+    status = AudioUnitUninitialize(internal->outputAudioUnit);
661     if (status) {
662-        fprintf(stderr, "ao_macosx_close: AudioDeviceRemoveIOProc returned %d\n", (int)status);
663-        return 0;
664+      fprintf(stderr, "ao_macosx_close: AudioUnitUninitialize returned %d\n", (int)status);
665+      return 0;
666     }
667+  }
668 
669-    return 1;
670+  return 1;
671 }
672 
673 
674 void ao_plugin_device_clear(ao_device *device)
675 {
676-       ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
677+  ao_macosx_internal *internal = (ao_macosx_internal *) device->internal;
678 
679-       free(internal->buffer);
680-       free(internal);
681+  free(internal->buffer);
682+  free(internal);
683 }
684 
685 
686-static OSStatus audioDeviceIOProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData)
687-{
688-    ao_macosx_internal *internal = (ao_macosx_internal *)inClientData;
689-    short *sample;
690-    unsigned int validByteCount;
691-    float scale = (0.5f / SHRT_MAX), *outBuffer;
692-    unsigned int bytesToCopy, samplesToCopy;
693-
694-    // Find the first valid frame and the number of valid frames
695-    pthread_mutex_lock(&internal->mutex);
696-
697-    bytesToCopy = internal->outputBufferByteCount/2;
698-    validByteCount = internal->validByteCount;
699-    outBuffer = (float *)outOutputData->mBuffers[0].mData;
700-   
701-    if (validByteCount < bytesToCopy && !internal->isStopping) {
702-        // Not enough data ... let it build up a bit more before we start copying stuff over.
703-        // If we are stopping, of course, we should just copy whatever we have.
704-        memset(outBuffer, 0, bytesToCopy);
705-        pthread_mutex_unlock(&internal->mutex);
706-        return 0;
707-    }
708-   
709-    bytesToCopy = MIN(bytesToCopy, validByteCount);
710-    sample = internal->buffer + internal->firstValidByteOffset;
711-    samplesToCopy = bytesToCopy / sizeof(*sample);
712-
713-    internal->bytesDequeued += bytesToCopy;
714-
715-#if DEBUG_PIPE
716-    fprintf(stderr, "IO: outputTime=%f firstValid=%d valid=%d toCopy=%d queued=%d dequeued=%d sample=0x%08x\n",
717-            inOutputTime->mSampleTime,
718-            internal->firstValidByteOffset, internal->validByteCount, samplesToCopy, internal->bytesQueued, internal->bytesDequeued, sample);
719-#endif
720-   
721-    internal->validByteCount -= bytesToCopy;
722-    internal->firstValidByteOffset = (internal->firstValidByteOffset + bytesToCopy) % internal->bufferByteCount;
723-   
724-    // We don't have to deal with wrapping around in the buffer since the buffer is a
725-    // multiple of the output buffer size and we only copy on buffer at a time
726-    // (except on the last buffer when we may copy only a partial output buffer).
727-#warning On the last buffer, zero out the part of the buffer that does not have valid samples
728-    while (samplesToCopy--) {
729-        short x = *sample;
730-#warning The bytes in the buffer are currently in little endian, but we need big endian.  Supposedly these are going to be host endian at some point and the following line of code can go away.
731-/* They will go away now, I think. --- Stan */
732-/*        x = ((x & 0xff00) >> 8) | ((x & 0x00ff) << 8); */
733-        *outBuffer = x * scale;
734-        outBuffer++;
735-        sample++;
736-    }
737-   
738-    pthread_mutex_unlock(&internal->mutex);
739-    pthread_cond_signal(&internal->condition);
740-   
741-    return 0;
742-}
743-
744