src/audio/nas/SDL_nasaudio.c
author Ryan C. Gordon
Sat, 07 Oct 2006 07:25:30 +0000
branchSDL-ryan-multiple-audio-device
changeset 3825 76c5a414b996
parent 3822 748707e2ddd1
child 3846 66fb40445587
permissions -rw-r--r--
Dynamic loading for NAS audio driver.
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2006 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 
    22     This driver was written by:
    23     Erik Inge Bolsų
    24     knan@mo.himolde.no
    25 */
    26 #include "SDL_config.h"
    27 
    28 /* Allow access to a raw mixing buffer */
    29 
    30 #include <signal.h>
    31 #include <unistd.h>
    32 
    33 #include "SDL_timer.h"
    34 #include "SDL_audio.h"
    35 #include "SDL_loadso.h"
    36 #include "../SDL_audiomem.h"
    37 #include "../SDL_audio_c.h"
    38 #include "SDL_nasaudio.h"
    39 
    40 /* The tag name used by nas audio */
    41 #define NAS_DRIVER_NAME         "nas"
    42 
    43 static struct SDL_PrivateAudioData *this2 = NULL;
    44 
    45 
    46 static void (*NAS_AuCloseServer)(AuServer *);
    47 static void (*NAS_AuNextEvent)(AuServer *, AuBool, AuEvent *);
    48 static AuBool (*NAS_AuDispatchEvent)(AuServer *, AuEvent *);
    49 static AuFlowID (*NAS_AuCreateFlow)(AuServer *, AuStatus *);
    50 static void (*NAS_AuStartFlow)(AuServer *, AuFlowID, AuStatus *);
    51 static void (*NAS_AuSetElements)
    52     (AuServer *, AuFlowID, AuBool, int, AuElement *, AuStatus *);
    53 static void (*NAS_AuWriteElement)
    54     (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuBool, AuStatus *);
    55 static AuServer *(*NAS_AuOpenServer)
    56     (_AuConst char *, int, _AuConst char *, int, _AuConst char *, char **);
    57 static AuEventHandlerRec *(*NAS_AuRegisterEventHandler)
    58     (AuServer *, AuMask, int, AuID, AuEventHandlerCallback, AuPointer);
    59 
    60 
    61 #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC
    62 
    63 static const char *nas_library = SDL_AUDIO_DRIVER_NAS_DYNAMIC;
    64 static void *nas_handle = NULL;
    65 
    66 static int
    67 load_nas_sym(const char *fn, void **addr)
    68 {
    69     *addr = SDL_LoadFunction(nas_handle, fn);
    70     if (*addr == NULL) {
    71         return 0;
    72     }
    73     return 1;
    74 }
    75 
    76 /* cast funcs to char* first, to please GCC's strict aliasing rules. */
    77 #define SDL_NAS_SYM(x) \
    78     if (!load_nas_sym(#x, (void **) (char *) &NAS_##x)) return -1
    79 #else
    80 #define SDL_NAS_SYM(x) NAS_##x = x
    81 #endif
    82 
    83 static int load_nas_syms(void)
    84 {
    85     SDL_NAS_SYM(AuCloseServer);
    86     SDL_NAS_SYM(AuNextEvent);
    87     SDL_NAS_SYM(AuDispatchEvent);
    88     SDL_NAS_SYM(AuCreateFlow);
    89     SDL_NAS_SYM(AuStartFlow);
    90     SDL_NAS_SYM(AuSetElements);
    91     SDL_NAS_SYM(AuWriteElement);
    92     SDL_NAS_SYM(AuOpenServer);
    93     SDL_NAS_SYM(AuRegisterEventHandler);
    94     return 0;
    95 }
    96 #undef SDL_NAS_SYM
    97 
    98 #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC
    99 
   100 static int library_load_count = 0;
   101 
   102 static void
   103 UnloadNASLibrary(void)
   104 {
   105     if ((nas_handle != NULL) && (--library_load_count == 0)) {
   106         SDL_UnloadObject(nas_handle);
   107         nas_handle = NULL;
   108     }
   109 }
   110 
   111 static int
   112 LoadNASLibrary(void)
   113 {
   114     int retval = 0;
   115     if (library_load_count++ == 0) {
   116         nas_handle = SDL_LoadObject(nas_library);
   117         if (nas_handle == NULL) {
   118             /* Copy error string so we can use it in a new SDL_SetError(). */
   119             char *origerr = SDL_GetError();
   120             size_t len = SDL_strlen(origerr) + 1;
   121             char *err = (char *) alloca(len);
   122             SDL_strlcpy(err, origerr, len);
   123 
   124             library_load_count--;
   125             retval = -1;
   126             SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s\n",
   127                           nas_library, err);
   128         } else {
   129             retval = load_nas_syms();
   130             if (retval < 0) {
   131                 UnloadNASLibrary();
   132             }
   133         }
   134     }
   135     return retval;
   136 }
   137 
   138 #else
   139 
   140 static void
   141 UnloadNASLibrary(void)
   142 {
   143 }
   144 
   145 static int
   146 LoadNASLibrary(void)
   147 {
   148     load_nas_syms();
   149     return 0;
   150 }
   151 
   152 #endif /* SDL_AUDIO_DRIVER_NAS_DYNAMIC */
   153 
   154 static int
   155 NAS_Available(void)
   156 {
   157     int available = 0;
   158     if (LoadNASLibrary() >= 0) {
   159         AuServer *aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL);
   160         if (aud != NULL) {
   161             available = 1;
   162             NAS_AuCloseServer(aud);
   163         }
   164         UnloadNASLibrary();
   165     }
   166     return available;
   167 }
   168 
   169 /* This function waits until it is possible to write a full sound buffer */
   170 static void
   171 NAS_WaitDevice(_THIS)
   172 {
   173     while (this->hidden->buf_free < this->hidden->mixlen) {
   174         AuEvent ev;
   175         NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev);
   176         NAS_AuDispatchEvent(this->hidden->aud, &ev);
   177     }
   178 }
   179 
   180 static void
   181 NAS_PlayDevice(_THIS)
   182 {
   183     while (this->hidden->mixlen > this->hidden->buf_free) {
   184         /*
   185          * We think the buffer is full? Yikes! Ask the server for events,
   186          *  in the hope that some of them is LowWater events telling us more
   187          *  of the buffer is free now than what we think.
   188          */
   189         AuEvent ev;
   190         NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev);
   191         NAS_AuDispatchEvent(this->hidden->aud, &ev);
   192     }
   193     this->hidden->buf_free -= this->hidden->mixlen;
   194 
   195     /* Write the audio data */
   196     NAS_AuWriteElement(this->hidden->aud, this->hidden->flow, 0,
   197                    this->hidden->mixlen, this->hidden->mixbuf, AuFalse, NULL);
   198 
   199     this->hidden->written += this->hidden->mixlen;
   200 
   201 #ifdef DEBUG_AUDIO
   202     fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen);
   203 #endif
   204 }
   205 
   206 static Uint8 *
   207 NAS_GetDeviceBuf(_THIS)
   208 {
   209     return (this->hidden->mixbuf);
   210 }
   211 
   212 static void
   213 NAS_CloseDevice(_THIS)
   214 {
   215     if (this->hidden != NULL) {
   216         if (this->hidden->mixbuf != NULL) {
   217             SDL_FreeAudioMem(this->hidden->mixbuf);
   218             this->hidden->mixbuf = NULL;
   219         }
   220         if (this->hidden->aud) {
   221             NAS_AuCloseServer(this->hidden->aud);
   222             this->hidden->aud = 0;
   223         }
   224         SDL_free(this->hidden);
   225         this2 = this->hidden = NULL;
   226         UnloadNASLibrary();
   227     }
   228 }
   229 
   230 static unsigned char
   231 sdlformat_to_auformat(unsigned int fmt)
   232 {
   233     switch (fmt) {
   234     case AUDIO_U8:
   235         return AuFormatLinearUnsigned8;
   236     case AUDIO_S8:
   237         return AuFormatLinearSigned8;
   238     case AUDIO_U16LSB:
   239         return AuFormatLinearUnsigned16LSB;
   240     case AUDIO_U16MSB:
   241         return AuFormatLinearUnsigned16MSB;
   242     case AUDIO_S16LSB:
   243         return AuFormatLinearSigned16LSB;
   244     case AUDIO_S16MSB:
   245         return AuFormatLinearSigned16MSB;
   246     }
   247     return AuNone;
   248 }
   249 
   250 static AuBool
   251 event_handler(AuServer * aud, AuEvent * ev, AuEventHandlerRec * hnd)
   252 {
   253     switch (ev->type) {
   254     case AuEventTypeElementNotify:
   255         {
   256             AuElementNotifyEvent *event = (AuElementNotifyEvent *) ev;
   257 
   258             switch (event->kind) {
   259             case AuElementNotifyKindLowWater:
   260                 if (this2->buf_free >= 0) {
   261                     this2->really += event->num_bytes;
   262                     gettimeofday(&this2->last_tv, 0);
   263                     this2->buf_free += event->num_bytes;
   264                 } else {
   265                     this2->buf_free = event->num_bytes;
   266                 }
   267                 break;
   268             case AuElementNotifyKindState:
   269                 switch (event->cur_state) {
   270                 case AuStatePause:
   271                     if (event->reason != AuReasonUser) {
   272                         if (this2->buf_free >= 0) {
   273                             this2->really += event->num_bytes;
   274                             gettimeofday(&this2->last_tv, 0);
   275                             this2->buf_free += event->num_bytes;
   276                         } else {
   277                             this2->buf_free = event->num_bytes;
   278                         }
   279                     }
   280                     break;
   281                 }
   282             }
   283         }
   284     }
   285     return AuTrue;
   286 }
   287 
   288 static AuDeviceID
   289 find_device(_THIS, int nch)
   290 {
   291     /* These "Au" things are all macros, not functions... */
   292     int i;
   293     for (i = 0; i < AuServerNumDevices(this->hidden->aud); i++) {
   294         if ((AuDeviceKind(AuServerDevice(this->hidden->aud, i)) ==
   295              AuComponentKindPhysicalOutput) &&
   296             AuDeviceNumTracks(AuServerDevice(this->hidden->aud, i)) == nch) {
   297             return AuDeviceIdentifier(AuServerDevice(this->hidden->aud, i));
   298         }
   299     }
   300     return AuNone;
   301 }
   302 
   303 static int
   304 NAS_OpenDevice(_THIS, const char *devname, int iscapture)
   305 {
   306     AuElement elms[3];
   307     int buffer_size;
   308     SDL_AudioFormat test_format, format;
   309 
   310     /* Initialize all variables that we clean on shutdown */
   311     this->hidden = (struct SDL_PrivateAudioData *)
   312                         SDL_malloc((sizeof *this->hidden));
   313     if (this->hidden == NULL) {
   314         SDL_OutOfMemory();
   315         return 0;
   316     }
   317     SDL_memset(this->hidden, 0, (sizeof *this->hidden));
   318 
   319     if (LoadNASLibrary() < 0) {
   320         NAS_CloseDevice(this);
   321         return 0;
   322     }
   323 
   324     /* Try for a closest match on audio format */
   325     format = 0;
   326     for (test_format = SDL_FirstAudioFormat(this->spec.format);
   327          !format && test_format;) {
   328         format = sdlformat_to_auformat(test_format);
   329         if (format == AuNone) {
   330             test_format = SDL_NextAudioFormat();
   331         }
   332     }
   333     if (format == 0) {
   334         NAS_CloseDevice(this);
   335         SDL_SetError("NAS: Couldn't find any hardware audio formats");
   336         return 0;
   337     }
   338     this->spec.format = test_format;
   339 
   340     this->hidden->aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL);
   341     if (this->hidden->aud == 0) {
   342         NAS_CloseDevice(this);
   343         SDL_SetError("NAS: Couldn't open connection to NAS server");
   344         return 0;
   345     }
   346 
   347     this->hidden->dev = find_device(this, this->spec.channels);
   348     if ((this->hidden->dev == AuNone)
   349         || (!(this->hidden->flow = NAS_AuCreateFlow(this->hidden->aud, 0)))) {
   350         NAS_CloseDevice(this);
   351         SDL_SetError("NAS: Couldn't find a fitting device on NAS server");
   352         return 0;
   353     }
   354 
   355     buffer_size = this->spec.freq;
   356     if (buffer_size < 4096)
   357         buffer_size = 4096;
   358 
   359     if (buffer_size > 32768)
   360         buffer_size = 32768;    /* So that the buffer won't get unmanageably big. */
   361 
   362     /* Calculate the final parameters for this audio specification */
   363     SDL_CalculateAudioSpec(&this->spec);
   364 
   365     this2 = this->hidden;
   366 
   367     AuMakeElementImportClient(elms,this->spec.freq,format,this->spec.channels,
   368                               AuTrue, buffer_size, buffer_size / 4, 0, NULL);
   369     AuMakeElementExportDevice(elms + 1, 0, this->hidden->dev, this->spec.freq,
   370                               AuUnlimitedSamples, 0, NULL);
   371     NAS_AuSetElements(this->hidden->aud, this->hidden->flow,
   372                       AuTrue, 2, elms, NULL);
   373     NAS_AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0,
   374                                this->hidden->flow, event_handler,
   375                                (AuPointer) NULL);
   376 
   377     NAS_AuStartFlow(this->hidden->aud, this->hidden->flow, NULL);
   378 
   379     /* Allocate mixing buffer */
   380     this->hidden->mixlen = this->spec.size;
   381     this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
   382     if (this->hidden->mixbuf == NULL) {
   383         NAS_CloseDevice(this);
   384         SDL_OutOfMemory();
   385         return 0;
   386     }
   387     SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
   388 
   389     /* We're ready to rock and roll. :-) */
   390     return 1;
   391 }
   392 
   393 static int
   394 NAS_Init(SDL_AudioDriverImpl *impl)
   395 {
   396     /* Set the function pointers */
   397     impl->OpenDevice = NAS_OpenDevice;
   398     impl->PlayDevice = NAS_PlayDevice;
   399     impl->WaitDevice = NAS_WaitDevice;
   400     impl->GetDeviceBuf = NAS_GetDeviceBuf;
   401     impl->CloseDevice = NAS_CloseDevice;
   402     impl->OnlyHasDefaultOutputDevice = 1;  /* !!! FIXME: is this true? */
   403 
   404     return 1;
   405 }
   406 
   407 AudioBootStrap NAS_bootstrap = {
   408     NAS_DRIVER_NAME, "Network Audio System",
   409     NAS_Available, NAS_Init, 0
   410 };
   411 
   412 /* vi: set ts=4 sw=4 expandtab: */