src/audio/dma/SDL_dmaaudio.c
author Sam Lantinga <slouken@libsdl.org>
Mon, 29 May 2006 04:04:35 +0000
branchSDL-1.3
changeset 1668 4da1ee79c9af
parent 1662 782fd950bd46
permissions -rw-r--r--
more tweaking indent options
     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 #include "SDL_config.h"
    23 
    24 /* Allow access to a raw mixing buffer */
    25 
    26 #include <stdio.h>
    27 #include <string.h>             /* For strerror() */
    28 #include <errno.h>
    29 #include <unistd.h>
    30 #include <fcntl.h>
    31 #include <signal.h>
    32 #include <sys/types.h>
    33 #include <sys/time.h>
    34 #include <sys/ioctl.h>
    35 #include <sys/stat.h>
    36 #include <sys/mman.h>
    37 
    38 #if SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H
    39 /* This is installed on some systems */
    40 #include <soundcard.h>
    41 #else
    42 /* This is recommended by OSS */
    43 #include <sys/soundcard.h>
    44 #endif
    45 
    46 #ifndef MAP_FAILED
    47 #define MAP_FAILED	((Uint8 *)-1)
    48 #endif
    49 
    50 #include "SDL_timer.h"
    51 #include "SDL_audio.h"
    52 #include "../SDL_audio_c.h"
    53 #include "../SDL_audiodev_c.h"
    54 #include "SDL_dmaaudio.h"
    55 
    56 /* The tag name used by DMA audio */
    57 #define DMA_DRIVER_NAME         "dma"
    58 
    59 /* Open the audio device for playback, and don't block if busy */
    60 #define OPEN_FLAGS	(O_RDWR|O_NONBLOCK)
    61 
    62 /* Audio driver functions */
    63 static int DMA_OpenAudio(_THIS, SDL_AudioSpec * spec);
    64 static void DMA_WaitAudio(_THIS);
    65 static void DMA_PlayAudio(_THIS);
    66 static Uint8 *DMA_GetAudioBuf(_THIS);
    67 static void DMA_CloseAudio(_THIS);
    68 
    69 /* Audio driver bootstrap functions */
    70 
    71 static int
    72 Audio_Available(void)
    73 {
    74     int available;
    75     int fd;
    76 
    77     available = 0;
    78 
    79     fd = SDL_OpenAudioPath(NULL, 0, OPEN_FLAGS, 0);
    80     if (fd >= 0) {
    81         int caps;
    82         struct audio_buf_info info;
    83 
    84         if ((ioctl(fd, SNDCTL_DSP_GETCAPS, &caps) == 0) &&
    85             (caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) &&
    86             (ioctl(fd, SNDCTL_DSP_GETOSPACE, &info) == 0)) {
    87             available = 1;
    88         }
    89         close(fd);
    90     }
    91     return (available);
    92 }
    93 
    94 static void
    95 Audio_DeleteDevice(SDL_AudioDevice * device)
    96 {
    97     SDL_free(device->hidden);
    98     SDL_free(device);
    99 }
   100 
   101 static SDL_AudioDevice *
   102 Audio_CreateDevice(int devindex)
   103 {
   104     SDL_AudioDevice *this;
   105 
   106     /* Initialize all variables that we clean on shutdown */
   107     this = (SDL_AudioDevice *) SDL_malloc(sizeof(SDL_AudioDevice));
   108     if (this) {
   109         SDL_memset(this, 0, (sizeof *this));
   110         this->hidden = (struct SDL_PrivateAudioData *)
   111             SDL_malloc((sizeof *this->hidden));
   112     }
   113     if ((this == NULL) || (this->hidden == NULL)) {
   114         SDL_OutOfMemory();
   115         if (this) {
   116             SDL_free(this);
   117         }
   118         return (0);
   119     }
   120     SDL_memset(this->hidden, 0, (sizeof *this->hidden));
   121     audio_fd = -1;
   122 
   123     /* Set the function pointers */
   124     this->OpenAudio = DMA_OpenAudio;
   125     this->WaitAudio = DMA_WaitAudio;
   126     this->PlayAudio = DMA_PlayAudio;
   127     this->GetAudioBuf = DMA_GetAudioBuf;
   128     this->CloseAudio = DMA_CloseAudio;
   129 
   130     this->free = Audio_DeleteDevice;
   131 
   132     return this;
   133 }
   134 
   135 AudioBootStrap DMA_bootstrap = {
   136     DMA_DRIVER_NAME, "OSS /dev/dsp DMA audio",
   137     Audio_Available, Audio_CreateDevice
   138 };
   139 
   140 /* This function waits until it is possible to write a full sound buffer */
   141 static void
   142 DMA_WaitAudio(_THIS)
   143 {
   144     fd_set fdset;
   145 
   146     /* Check to see if the thread-parent process is still alive */
   147     {
   148         static int cnt = 0;
   149         /* Note that this only works with thread implementations 
   150            that use a different process id for each thread.
   151          */
   152         if (parent && (((++cnt) % 10) == 0)) {  /* Check every 10 loops */
   153             if (kill(parent, 0) < 0) {
   154                 this->enabled = 0;
   155             }
   156         }
   157     }
   158 
   159     /* See if we need to use timed audio synchronization */
   160     if (frame_ticks) {
   161         /* Use timer for general audio synchronization */
   162         Sint32 ticks;
   163 
   164         ticks = ((Sint32) (next_frame - SDL_GetTicks())) - FUDGE_TICKS;
   165         if (ticks > 0) {
   166             SDL_Delay(ticks);
   167         }
   168     } else {
   169         /* Use select() for audio synchronization */
   170         struct timeval timeout;
   171         FD_ZERO(&fdset);
   172         FD_SET(audio_fd, &fdset);
   173         timeout.tv_sec = 10;
   174         timeout.tv_usec = 0;
   175 #ifdef DEBUG_AUDIO
   176         fprintf(stderr, "Waiting for audio to get ready\n");
   177 #endif
   178         if (select(audio_fd + 1, NULL, &fdset, NULL, &timeout) <= 0) {
   179             const char *message =
   180 #ifdef AUDIO_OSPACE_HACK
   181                 "Audio timeout - buggy audio driver? (trying ospace)";
   182 #else
   183                 "Audio timeout - buggy audio driver? (disabled)";
   184 #endif
   185             /* In general we should never print to the screen,
   186                but in this case we have no other way of letting
   187                the user know what happened.
   188              */
   189             fprintf(stderr, "SDL: %s\n", message);
   190 #ifdef AUDIO_OSPACE_HACK
   191             /* We may be able to use GET_OSPACE trick */
   192             frame_ticks = (float) (this->spec->samples * 1000) /
   193                 this->spec->freq;
   194             next_frame = SDL_GetTicks() + frame_ticks;
   195 #else
   196             this->enabled = 0;
   197             /* Don't try to close - may hang */
   198             audio_fd = -1;
   199 #ifdef DEBUG_AUDIO
   200             fprintf(stderr, "Done disabling audio\n");
   201 #endif
   202 #endif /* AUDIO_OSPACE_HACK */
   203         }
   204 #ifdef DEBUG_AUDIO
   205         fprintf(stderr, "Ready!\n");
   206 #endif
   207     }
   208 }
   209 
   210 static void
   211 DMA_PlayAudio(_THIS)
   212 {
   213     /* If timer synchronization is enabled, set the next write frame */
   214     if (frame_ticks) {
   215         next_frame += frame_ticks;
   216     }
   217     return;
   218 }
   219 
   220 static Uint8 *
   221 DMA_GetAudioBuf(_THIS)
   222 {
   223     count_info info;
   224     int playing;
   225     int filling;
   226 
   227     /* Get number of blocks, looping if we're not using select() */
   228     do {
   229         if (ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &info) < 0) {
   230             /* Uh oh... */
   231             this->enabled = 0;
   232             return (NULL);
   233         }
   234     }
   235     while (frame_ticks && (info.blocks < 1));
   236 #ifdef DEBUG_AUDIO
   237     if (info.blocks > 1) {
   238         printf("Warning: audio underflow (%d frags)\n", info.blocks - 1);
   239     }
   240 #endif
   241     playing = info.ptr / this->spec.size;
   242     filling = (playing + 1) % num_buffers;
   243     return (dma_buf + (filling * this->spec.size));
   244 }
   245 
   246 static void
   247 DMA_CloseAudio(_THIS)
   248 {
   249     if (dma_buf != NULL) {
   250         munmap(dma_buf, dma_len);
   251         dma_buf = NULL;
   252     }
   253     if (audio_fd >= 0) {
   254         close(audio_fd);
   255         audio_fd = -1;
   256     }
   257 }
   258 
   259 static int
   260 DMA_ReopenAudio(_THIS, const char *audiodev, int format, int stereo,
   261                 SDL_AudioSpec * spec)
   262 {
   263     int frag_spec;
   264     int value;
   265 
   266     /* Close and then reopen the audio device */
   267     close(audio_fd);
   268     audio_fd = open(audiodev, O_RDWR, 0);
   269     if (audio_fd < 0) {
   270         SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
   271         return (-1);
   272     }
   273 
   274     /* Calculate the final parameters for this audio specification */
   275     SDL_CalculateAudioSpec(spec);
   276 
   277     /* Determine the power of two of the fragment size */
   278     for (frag_spec = 0; (0x01 << frag_spec) < spec->size; ++frag_spec);
   279     if ((0x01 << frag_spec) != spec->size) {
   280         SDL_SetError("Fragment size must be a power of two");
   281         return (-1);
   282     }
   283 
   284     /* Set the audio buffering parameters */
   285     if (ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0) {
   286         SDL_SetError("Couldn't set audio fragment spec");
   287         return (-1);
   288     }
   289 
   290     /* Set the audio format */
   291     value = format;
   292     if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) {
   293         SDL_SetError("Couldn't set audio format");
   294         return (-1);
   295     }
   296 
   297     /* Set mono or stereo audio */
   298     value = (spec->channels > 1);
   299     if ((ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) < 0) ||
   300         (value != stereo)) {
   301         SDL_SetError("Couldn't set audio channels");
   302         return (-1);
   303     }
   304 
   305     /* Set the DSP frequency */
   306     value = spec->freq;
   307     if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0) {
   308         SDL_SetError("Couldn't set audio frequency");
   309         return (-1);
   310     }
   311     spec->freq = value;
   312 
   313     /* We successfully re-opened the audio */
   314     return (0);
   315 }
   316 
   317 static int
   318 DMA_OpenAudio(_THIS, SDL_AudioSpec * spec)
   319 {
   320     char audiodev[1024];
   321     int format;
   322     int stereo;
   323     int value;
   324     Uint16 test_format;
   325     struct audio_buf_info info;
   326 
   327     /* Reset the timer synchronization flag */
   328     frame_ticks = 0.0;
   329 
   330     /* Open the audio device */
   331     audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
   332     if (audio_fd < 0) {
   333         SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
   334         return (-1);
   335     }
   336     dma_buf = NULL;
   337     ioctl(audio_fd, SNDCTL_DSP_RESET, 0);
   338 
   339     /* Get a list of supported hardware formats */
   340     if (ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) {
   341         SDL_SetError("Couldn't get audio format list");
   342         return (-1);
   343     }
   344 
   345     /* Try for a closest match on audio format */
   346     format = 0;
   347     for (test_format = SDL_FirstAudioFormat(spec->format);
   348          !format && test_format;) {
   349 #ifdef DEBUG_AUDIO
   350         fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
   351 #endif
   352         switch (test_format) {
   353         case AUDIO_U8:
   354             if (value & AFMT_U8) {
   355                 format = AFMT_U8;
   356             }
   357             break;
   358         case AUDIO_S8:
   359             if (value & AFMT_S8) {
   360                 format = AFMT_S8;
   361             }
   362             break;
   363         case AUDIO_S16LSB:
   364             if (value & AFMT_S16_LE) {
   365                 format = AFMT_S16_LE;
   366             }
   367             break;
   368         case AUDIO_S16MSB:
   369             if (value & AFMT_S16_BE) {
   370                 format = AFMT_S16_BE;
   371             }
   372             break;
   373         case AUDIO_U16LSB:
   374             if (value & AFMT_U16_LE) {
   375                 format = AFMT_U16_LE;
   376             }
   377             break;
   378         case AUDIO_U16MSB:
   379             if (value & AFMT_U16_BE) {
   380                 format = AFMT_U16_BE;
   381             }
   382             break;
   383         default:
   384             format = 0;
   385             break;
   386         }
   387         if (!format) {
   388             test_format = SDL_NextAudioFormat();
   389         }
   390     }
   391     if (format == 0) {
   392         SDL_SetError("Couldn't find any hardware audio formats");
   393         return (-1);
   394     }
   395     spec->format = test_format;
   396 
   397     /* Set the audio format */
   398     value = format;
   399     if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) {
   400         SDL_SetError("Couldn't set audio format");
   401         return (-1);
   402     }
   403 
   404     /* Set mono or stereo audio (currently only two channels supported) */
   405     stereo = (spec->channels > 1);
   406     ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo);
   407     if (stereo) {
   408         spec->channels = 2;
   409     } else {
   410         spec->channels = 1;
   411     }
   412 
   413     /* Because some drivers don't allow setting the buffer size
   414        after setting the format, we must re-open the audio device
   415        once we know what format and channels are supported
   416      */
   417     if (DMA_ReopenAudio(this, audiodev, format, stereo, spec) < 0) {
   418         /* Error is set by DMA_ReopenAudio() */
   419         return (-1);
   420     }
   421 
   422     /* Memory map the audio buffer */
   423     if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
   424         SDL_SetError("Couldn't get OSPACE parameters");
   425         return (-1);
   426     }
   427     spec->size = info.fragsize;
   428     spec->samples = spec->size / ((spec->format & 0xFF) / 8);
   429     spec->samples /= spec->channels;
   430     num_buffers = info.fragstotal;
   431     dma_len = num_buffers * spec->size;
   432     dma_buf = (Uint8 *) mmap(NULL, dma_len, PROT_WRITE, MAP_SHARED,
   433                              audio_fd, 0);
   434     if (dma_buf == MAP_FAILED) {
   435         SDL_SetError("DMA memory map failed");
   436         dma_buf = NULL;
   437         return (-1);
   438     }
   439     SDL_memset(dma_buf, spec->silence, dma_len);
   440 
   441     /* Check to see if we need to use select() workaround */
   442     {
   443         char *workaround;
   444         workaround = SDL_getenv("SDL_DSP_NOSELECT");
   445         if (workaround) {
   446             frame_ticks = (float) (spec->samples * 1000) / spec->freq;
   447             next_frame = SDL_GetTicks() + frame_ticks;
   448         }
   449     }
   450 
   451     /* Trigger audio playback */
   452     value = 0;
   453     ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value);
   454     value = PCM_ENABLE_OUTPUT;
   455     if (ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value) < 0) {
   456         SDL_SetError("Couldn't trigger audio output");
   457         return (-1);
   458     }
   459 
   460     /* Get the parent process id (we're the parent of the audio thread) */
   461     parent = getpid();
   462 
   463     /* We're ready to rock and roll. :-) */
   464     return (0);
   465 }
   466 
   467 /* vi: set ts=4 sw=4 expandtab: */