view src/audio/macrom/SDL_romaudio.c @ 942:41a59de7f2ed

Here are patches for SDL12 and SDL_mixer for 4 or 6 channel surround sound on Linux using the Alsa driver. To use them, naturally you need a sound card that will do 4 or 6 channels and probably also a recent version of the Alsa drivers and library. Since the only SDL output driver that knows about surround sound is the Alsa driver, you���ll want to choose it, using: export SDL_AUDIODRIVER=alsa There are no syntactic changes to the programming API. No new library calls, no differences in arguments. There are two semantic changes: (1) For library calls with number of channels as an argument, formerly you could use only 1 or 2 for the number of channels. Now you can also use 4 or 6. (2) The two "left" and "right" arguments to Mix_SetPanning, for the case of 4 or 6 channels, no longer simply control the volumes of the left and right channels. Now the "left" argument is converted to an angle and Mix_SetPosition is called, and the "right" argu- ment is ignored. With two exceptions, so far as I know, the modified SDL12 and SDL_mixer work the same way as the original versions, when opened for 1 or 2 channel output. The two exceptions are bugs which I fixed. Well, the first, anyway, is a bug for sure. When rate conversions up or down by a factor of two are applied (in src/audio/SDL_audiocvt.c), streams with different numbers of channels (that is, mono and stereo) are treated the same way: either each sample is copied or every other sample is omitted. This is ok for mono, but for stereo, it is frames that should be copied or omitted, where by "frame" I mean a portion of the stream containing one sample for each channel. (In the SDL source, confusingly, sometimes frames are called "samples".) So for these rate conversions, stereo streams have to be treated differently, and they are, in my modified version. The other problem that might be characterized as a bug arises when SDL_mixer is passed a multichannel chunk which does not have an integral number of frames. Due to the way the effect_position code loops over frames, when the chunk ends with a partial frame, memory outside the chunk buffer will be accessed. In the case of stereo, it���s possible that because malloc may give more memory than requested, this potential problem never actually causes a segment fault. I don���t know. For 6 channel chunks, I do know, and it does cause segment faults. If SDL_mixer is passed defective chunks and this causes a segment fault, arguably, that���s not a bug in SDL_mixer. Still, whether or not it counts as a bug, it���s easy to protect against, so why not? I added code in mixer.c to discard any partial frame at the end of a chunk. Then what about when SDL or SDL_mixer is opened for 4 or 6 chan- nel output? What happens with the parts of the current library designed for stereo? I don���t know whether I���ve covered all the bases, but I���ve tried: (1) For playing 2 channel waves, or other cases where SDL knows it has to match up a 2 channel source with a 4 or 6 channel output, I���ve added code in SDL_audiocvt.c to make the necessary conversions. (2) For playing midis using timidity, I���ve converted timidity to do 4 or 6 channel output, upon request. (3) For playing mods using mikmod, I put ad hoc code in music.c to convert the stereo output that mikmod produces to 4 or 6 chan- nels. Obviously it would be better to change the mikmod code to mix down into 4 or 6 channels, but I have a hard time following the code in mikmod, so I didn���t do that. (4) For playing mp3s, I put ad hoc code in smpeg to copy channels in the case when 4 or 6 channel output is needed. (5) There seems to be no problem with .ogg files - stereo .oggs can be up converted as .wavs are. (6) The effect_position code in SDL_mixer is now generalized to in- clude the cases of 4 and 6 channel streams. I���ve done a very limited amount of compatibility testing for some of the games using SDL I happen to have. For details, see the file TESTS. I���ve put into a separate archive, Surround-SDL-testfiles.tgz, a couple of 6 channel wave files for testing and a 6 channel ogg file. If you have the right hardware and version of Alsa, you should be able to play the wave files with the Alsa utility aplay (and hear all channels, except maybe lfe, for chan-id.wav, since it���s rather faint). Don���t expect aplay to give good sound, though. There���s something wrong with the current version of aplay. The canyon.ogg file is to test loading of 6 channel oggs. After patching and compiling, you can play it with playmus. (My version of ogg123 will not play it, and I had to patch mplayer to get it to play 6 channel oggs.) Greg Lee <greg@ling.lll.hawaii.edu> Thus, July 1, 2004
author Sam Lantinga <slouken@libsdl.org>
date Sat, 21 Aug 2004 12:27:02 +0000
parents b8d311d90021
children 609c060fd2a2
line wrap: on
line source

/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2004 Sam Lantinga

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

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Sam Lantinga
    slouken@libsdl.org
*/

#ifdef SAVE_RCSID
static char rcsid =
 "@(#) $Id$";
#endif

#if TARGET_API_MAC_CARBON
#  include <Carbon.h>
#else
#  include <Sound.h> /* SoundManager interface */
#  include <Gestalt.h>
#  include <DriverServices.h>
#endif

#include <stdlib.h>
#include <stdio.h>

#include "SDL_endian.h"
#include "SDL_audio.h"
#include "SDL_audio_c.h"
#include "SDL_audiomem.h"
#include "SDL_sysaudio.h"
#include "SDL_romaudio.h"

/* Audio driver functions */

static void Mac_CloseAudio(_THIS);
static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec);
static void Mac_LockAudio(_THIS);
static void Mac_UnlockAudio(_THIS);

/* Audio driver bootstrap functions */


static int Audio_Available(void)
{
    return(1);
}

static void Audio_DeleteDevice(SDL_AudioDevice *device)
{
    free(device->hidden);
    free(device);
}

static SDL_AudioDevice *Audio_CreateDevice(int devindex)
{
    SDL_AudioDevice *this;

    /* Initialize all variables that we clean on shutdown */
    this = (SDL_AudioDevice *)malloc(sizeof(SDL_AudioDevice));
    if ( this ) {
        memset(this, 0, (sizeof *this));
        this->hidden = (struct SDL_PrivateAudioData *)
                malloc((sizeof *this->hidden));
    }
    if ( (this == NULL) || (this->hidden == NULL) ) {
        SDL_OutOfMemory();
        if ( this ) {
            free(this);
        }
        return(0);
    }
    memset(this->hidden, 0, (sizeof *this->hidden));

    /* Set the function pointers */
    this->OpenAudio   = Mac_OpenAudio;
    this->CloseAudio  = Mac_CloseAudio;
    this->LockAudio   = Mac_LockAudio;
    this->UnlockAudio = Mac_UnlockAudio;
    this->free        = Audio_DeleteDevice;

#ifdef MACOSX	/* MacOS X uses threaded audio, so normal thread code is okay */
    this->LockAudio   = NULL;
    this->UnlockAudio = NULL;
#endif
    return this;
}

AudioBootStrap SNDMGR_bootstrap = {
	"sndmgr", "MacOS SoundManager 3.0",
	Audio_Available, Audio_CreateDevice
};

#if defined(TARGET_API_MAC_CARBON) || defined(USE_RYANS_SOUNDCODE)
/* This works correctly on MacOS X */

#pragma options align=power

static volatile SInt32 audio_is_locked = 0;
static volatile SInt32 need_to_mix = 0;

static UInt8  *buffer[2];
static volatile UInt32 running = 0;
static CmpSoundHeader header;
static volatile Uint32 fill_me = 0;

static void mix_buffer(SDL_AudioDevice *audio, UInt8 *buffer)
{
   if ( ! audio->paused ) {
#ifdef MACOSX
        SDL_mutexP(audio->mixer_lock);
#endif
        if ( audio->convert.needed ) {
            audio->spec.callback(audio->spec.userdata,
                    (Uint8 *)audio->convert.buf,audio->convert.len);
            SDL_ConvertAudio(&audio->convert);
            if ( audio->convert.len_cvt != audio->spec.size ) {
                /* Uh oh... probably crashes here */;
            }
            memcpy(buffer, audio->convert.buf, audio->convert.len_cvt);
        } else {
            audio->spec.callback(audio->spec.userdata, buffer, audio->spec.size);
        }
#ifdef MACOSX
        SDL_mutexV(audio->mixer_lock);
#endif
    }

    DecrementAtomic((SInt32 *) &need_to_mix);
}

static void Mac_LockAudio(_THIS)
{
    IncrementAtomic((SInt32 *) &audio_is_locked);
}

static void Mac_UnlockAudio(_THIS)
{
    SInt32 oldval;
         
    oldval = DecrementAtomic((SInt32 *) &audio_is_locked);
    if ( oldval != 1 )  /* != 1 means audio is still locked. */
        return;

    /* Did we miss the chance to mix in an interrupt? Do it now. */
    if ( BitAndAtomic (0xFFFFFFFF, (UInt32 *) &need_to_mix) ) {
        /*
         * Note that this could be a problem if you missed an interrupt
         *  while the audio was locked, and get preempted by a second
         *  interrupt here, but that means you locked for way too long anyhow.
         */
        mix_buffer (this, buffer[fill_me]);
    }
}

static void callBackProc (SndChannel *chan, SndCommand *cmd_passed ) {
   UInt32 play_me;
   SndCommand cmd; 
   SDL_AudioDevice *audio = (SDL_AudioDevice *)chan->userInfo;

   IncrementAtomic((SInt32 *) &need_to_mix);

   fill_me = cmd_passed->param2;  /* buffer that has just finished playing, so fill it */      
   play_me = ! fill_me;           /* filled buffer to play _now_ */

   if ( ! audio->enabled ) {
      return;
   }
   
   /* queue previously mixed buffer for playback. */
   header.samplePtr = (Ptr)buffer[play_me];
   cmd.cmd = bufferCmd;
   cmd.param1 = 0; 
   cmd.param2 = (long)&header;
   SndDoCommand (chan, &cmd, 0);

   memset (buffer[fill_me], 0, audio->spec.size);

   /*
    * if audio device isn't locked, mix the next buffer to be queued in
    *  the memory block that just finished playing.
    */
   if ( ! BitAndAtomic(0xFFFFFFFF, (UInt32 *) &audio_is_locked) ) {
      mix_buffer (audio, buffer[fill_me]);
   } 

   /* set this callback to run again when current buffer drains. */
   if ( running ) {
      cmd.cmd = callBackCmd;
      cmd.param1 = 0;
      cmd.param2 = play_me;
   
      SndDoCommand (chan, &cmd, 0);
   }
}

static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec) {

   SndCallBackUPP callback;
   int sample_bits;
   int i;
   long initOptions;
      
   /* Very few conversions are required, but... */
    switch (spec->format) {
        case AUDIO_S8:
        spec->format = AUDIO_U8;
        break;
        case AUDIO_U16LSB:
        spec->format = AUDIO_S16LSB;
        break;
        case AUDIO_U16MSB:
        spec->format = AUDIO_S16MSB;
        break;
    }
    SDL_CalculateAudioSpec(spec);
    
    /* initialize bufferCmd header */
    memset (&header, 0, sizeof(header));
    callback = NewSndCallBackUPP (callBackProc);
    sample_bits = spec->size / spec->samples / spec->channels * 8;

#ifdef DEBUG_AUDIO
    fprintf(stderr,
	"Audio format 0x%x, channels = %d, sample_bits = %d, frequency = %d\n",
	spec->format, spec->channels, sample_bits, spec->freq);
#endif /* DEBUG_AUDIO */
    
    header.numChannels = spec->channels;
    header.sampleSize  = sample_bits;
    header.sampleRate  = spec->freq << 16;
    header.numFrames   = spec->samples;
    header.encode      = cmpSH;
    
    /* Note that we install the 16bitLittleEndian Converter if needed. */
    if ( spec->format == 0x8010 ) {
        header.compressionID = fixedCompression;
        header.format = k16BitLittleEndianFormat;
    }
    
    /* allocate 2 buffers */
    for (i=0; i<2; i++) {
       buffer[i] = (UInt8*)malloc (sizeof(UInt8) * spec->size);
      if (buffer[i] == NULL) {
         SDL_OutOfMemory();
         return (-1);
      }
     memset (buffer[i], 0, spec->size);
   }
   
   /* Create the sound manager channel */
    channel = (SndChannelPtr)malloc(sizeof(*channel));
    if ( channel == NULL ) {
        SDL_OutOfMemory();
        return(-1);
    }
    if ( spec->channels >= 2 ) {
        initOptions = initStereo;
    } else {
        initOptions = initMono;
    }
    channel->userInfo = (long)this;
    channel->qLength = 128;
    if ( SndNewChannel(&channel, sampledSynth, initOptions, callback) != noErr ) {
        SDL_SetError("Unable to create audio channel");
        free(channel);
        channel = NULL;
        return(-1);
    }
   
   /* start playback */
   {
      SndCommand cmd;
      cmd.cmd = callBackCmd;
      cmd.param2 = 0;
      running = 1;
      SndDoCommand (channel, &cmd, 0);
   }
   
   return 1;
}

static void Mac_CloseAudio(_THIS) {
   
   int i;
   
   running = 0;
   
   if (channel) {
      SndDisposeChannel (channel, true);
      channel = NULL;
   }
   
    for ( i=0; i<2; ++i ) {
        if ( buffer[i] ) {
            free(buffer[i]);
            buffer[i] = NULL;
        }
    }
}

#else /* !TARGET_API_MAC_CARBON && !USE_RYANS_SOUNDCODE */

static void Mac_LockAudio(_THIS)
{
    /* no-op. */
}

static void Mac_UnlockAudio(_THIS)
{
    /* no-op. */
}


/* This function is called by Sound Manager when it has exhausted one of
   the buffers, so we'll zero it to silence and fill it with audio if
   we're not paused.
*/
static pascal
void sndDoubleBackProc (SndChannelPtr chan, SndDoubleBufferPtr newbuf)
{
    SDL_AudioDevice *audio = (SDL_AudioDevice *)newbuf->dbUserInfo[0];

    /* If audio is quitting, don't do anything */
    if ( ! audio->enabled ) {
        return;
    }
    memset (newbuf->dbSoundData, 0, audio->spec.size);
    newbuf->dbNumFrames = audio->spec.samples;
    if ( ! audio->paused ) {
        if ( audio->convert.needed ) {
            audio->spec.callback(audio->spec.userdata,
                (Uint8 *)audio->convert.buf,audio->convert.len);
            SDL_ConvertAudio(&audio->convert);
#if 0
            if ( audio->convert.len_cvt != audio->spec.size ) {
                /* Uh oh... probably crashes here */;
            }
#endif
            memcpy(newbuf->dbSoundData, audio->convert.buf,
                            audio->convert.len_cvt);
        } else {
            audio->spec.callback(audio->spec.userdata,
                (Uint8 *)newbuf->dbSoundData, audio->spec.size);
        }
    }
    newbuf->dbFlags    |= dbBufferReady;
}

static int DoubleBufferAudio_Available(void)
{
    int available;
    NumVersion sndversion;
    long response;

    available = 0;
    sndversion = SndSoundManagerVersion();
    if ( sndversion.majorRev >= 3 ) {
        if ( Gestalt(gestaltSoundAttr, &response) == noErr ) {
            if ( (response & (1 << gestaltSndPlayDoubleBuffer)) ) {
                available = 1;
            }
        }
    } else {
        if ( Gestalt(gestaltSoundAttr, &response) == noErr ) {
            if ( (response & (1 << gestaltHasASC)) ) {
                available = 1;
            }
        }
    }
    return(available);
}

static void Mac_CloseAudio(_THIS)
{
    int i;

    if ( channel != NULL ) {
        /* Clean up the audio channel */
        SndDisposeChannel(channel, true);
        channel = NULL;
    }
    for ( i=0; i<2; ++i ) {
        if ( audio_buf[i] ) {
            free(audio_buf[i]);
            audio_buf[i] = NULL;
        }
    }
}

static int Mac_OpenAudio(_THIS, SDL_AudioSpec *spec)
{
    SndDoubleBufferHeader2 audio_dbh;
    int i;
    long initOptions;
    int sample_bits;
    SndDoubleBackUPP doubleBackProc;

    /* Check to make sure double-buffered audio is available */
    if ( ! DoubleBufferAudio_Available() ) {
        SDL_SetError("Sound manager doesn't support double-buffering");
        return(-1);
    }

    /* Very few conversions are required, but... */
    switch (spec->format) {
        case AUDIO_S8:
        spec->format = AUDIO_U8;
        break;
        case AUDIO_U16LSB:
        spec->format = AUDIO_S16LSB;
        break;
        case AUDIO_U16MSB:
        spec->format = AUDIO_S16MSB;
        break;
    }
    SDL_CalculateAudioSpec(spec);

    /* initialize the double-back header */
    memset(&audio_dbh, 0, sizeof(audio_dbh));
    doubleBackProc = NewSndDoubleBackProc (sndDoubleBackProc);
    sample_bits = spec->size / spec->samples / spec->channels * 8;
    
    audio_dbh.dbhNumChannels = spec->channels;
    audio_dbh.dbhSampleSize    = sample_bits;
    audio_dbh.dbhCompressionID = 0;
    audio_dbh.dbhPacketSize    = 0;
    audio_dbh.dbhSampleRate    = spec->freq << 16;
    audio_dbh.dbhDoubleBack    = doubleBackProc;
    audio_dbh.dbhFormat    = 0;

    /* Note that we install the 16bitLittleEndian Converter if needed. */
    if ( spec->format == 0x8010 ) {
        audio_dbh.dbhCompressionID = fixedCompression;
        audio_dbh.dbhFormat = k16BitLittleEndianFormat;
    }

    /* allocate the 2 double-back buffers */
    for ( i=0; i<2; ++i ) {
        audio_buf[i] = calloc(1, sizeof(SndDoubleBuffer)+spec->size);
        if ( audio_buf[i] == NULL ) {
            SDL_OutOfMemory();
            return(-1);
        }
        audio_buf[i]->dbNumFrames = spec->samples;
        audio_buf[i]->dbFlags = dbBufferReady;
        audio_buf[i]->dbUserInfo[0] = (long)this;
        audio_dbh.dbhBufferPtr[i] = audio_buf[i];
    }

    /* Create the sound manager channel */
    channel = (SndChannelPtr)malloc(sizeof(*channel));
    if ( channel == NULL ) {
        SDL_OutOfMemory();
        return(-1);
    }
    if ( spec->channels >= 2 ) {
        initOptions = initStereo;
    } else {
        initOptions = initMono;
    }
    channel->userInfo = 0;
    channel->qLength = 128;
    if ( SndNewChannel(&channel, sampledSynth, initOptions, 0L) != noErr ) {
        SDL_SetError("Unable to create audio channel");
        free(channel);
        channel = NULL;
        return(-1);
    }
 
    /* Start playback */
    if ( SndPlayDoubleBuffer(channel, (SndDoubleBufferHeaderPtr)&audio_dbh)
                                != noErr ) {
        SDL_SetError("Unable to play double buffered audio");
        return(-1);
    }
    
    return 1;
}

#endif /* TARGET_API_MAC_CARBON || USE_RYANS_SOUNDCODE */