timidity/timidity.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 21 Aug 2004 12:27:02 +0000
changeset 245 63b3650714de
parent 24 a25bb2d59ce8
child 263 5cd1ec721824
permissions -rw-r--r--
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
     1 /*
     2 
     3     TiMidity -- Experimental MIDI to WAVE converter
     4     Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
     5 
     6 	 This program is free software; you can redistribute it and/or modify
     7 	 it under the terms of the GNU General Public License as published by
     8     the Free Software Foundation; either version 2 of the License, or
     9 	 (at your option) any later version.
    10 
    11     This program is distributed in the hope that it will be useful,
    12     but WITHOUT ANY WARRANTY; without even the implied warranty of
    13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14 	 GNU General Public License for more details.
    15 
    16     You should have received a copy of the GNU General Public License
    17     along with this program; if not, write to the Free Software
    18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
    19 
    20 */
    21 #include <stdio.h>
    22 #include <stdlib.h>
    23 #include <string.h>
    24 
    25 #include "SDL.h"
    26 #include "config.h"
    27 #include "common.h"
    28 #include "instrum.h"
    29 #include "playmidi.h"
    30 #include "readmidi.h"
    31 #include "output.h"
    32 #include "controls.h"
    33 #include "timidity.h"
    34 
    35 #include "tables.h"
    36 
    37 void (*s32tobuf)(void *dp, int32 *lp, int32 c);
    38 int free_instruments_afterwards=0;
    39 static char def_instr_name[256]="";
    40 
    41 int AUDIO_BUFFER_SIZE;
    42 resample_t *resample_buffer;
    43 int32 *common_buffer;
    44 int num_ochannels;
    45 
    46 #define MAXWORDS 10
    47 
    48 static int read_config_file(char *name)
    49 {
    50   FILE *fp;
    51   char tmp[1024], *w[MAXWORDS], *cp;
    52   ToneBank *bank=0;
    53   int i, j, k, line=0, words;
    54   static int rcf_count=0;
    55 
    56   if (rcf_count>50)
    57    {
    58     ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
    59       "Probable source loop in configuration files");
    60     return (-1);
    61    }
    62 
    63   if (!(fp=open_file(name, 1, OF_VERBOSE)))
    64    return -1;
    65 
    66   while (fgets(tmp, sizeof(tmp), fp))
    67   {
    68     line++;
    69     w[words=0]=strtok(tmp, " \t\r\n\240");
    70     if (!w[0] || (*w[0]=='#')) continue;
    71     while (w[words] && (words < MAXWORDS))
    72       {
    73         w[++words]=strtok(0," \t\r\n\240");
    74         if (w[words] && w[words][0]=='#') break;
    75       }
    76     if (!strcmp(w[0], "map")) continue;
    77     if (!strcmp(w[0], "dir"))
    78     {
    79       if (words < 2)
    80        {
    81         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
    82           "%s: line %d: No directory given\n", name, line);
    83         return -2;
    84        }
    85       for (i=1; i<words; i++)
    86         add_to_pathlist(w[i]);
    87     }
    88   else if (!strcmp(w[0], "source"))
    89   {
    90     if (words < 2)
    91       {
    92         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
    93           "%s: line %d: No file name given\n", name, line);
    94         return -2;
    95      }
    96     for (i=1; i<words; i++)
    97       {
    98         rcf_count++;
    99       read_config_file(w[i]);
   100         rcf_count--;
   101       }
   102   }
   103       else if (!strcmp(w[0], "default"))
   104   {
   105     if (words != 2)
   106       {
   107         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   108         "%s: line %d: Must specify exactly one patch name\n",
   109           name, line);
   110         return -2;
   111       }
   112     strncpy(def_instr_name, w[1], 255);
   113     def_instr_name[255]='\0';
   114   }
   115     else if (!strcmp(w[0], "drumset"))
   116   {
   117     if (words < 2)
   118       {
   119         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
   120           "%s: line %d: No drum set number given\n", 
   121           name, line);
   122       return -2;
   123       }
   124     i=atoi(w[1]);
   125     if (i<0 || i>127)
   126      {
   127         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   128           "%s: line %d: Drum set must be between 0 and 127\n",
   129         name, line);
   130         return -2;
   131      }
   132     if (!drumset[i])
   133       {
   134         drumset[i]=safe_malloc(sizeof(ToneBank));
   135       memset(drumset[i], 0, sizeof(ToneBank));
   136      }
   137     bank=drumset[i];
   138   }
   139     else if (!strcmp(w[0], "bank"))
   140   {
   141     if (words < 2)
   142      {
   143         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
   144           "%s: line %d: No bank number given\n", 
   145         name, line);
   146         return -2;
   147      }
   148     i=atoi(w[1]);
   149     if (i<0 || i>127)
   150       {
   151         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   152           "%s: line %d: Tone bank must be between 0 and 127\n",
   153         name, line);
   154         return -2;
   155       }
   156     if (!tonebank[i])
   157      {
   158       tonebank[i]=safe_malloc(sizeof(ToneBank));
   159         memset(tonebank[i], 0, sizeof(ToneBank));
   160       }
   161     bank=tonebank[i];
   162   }
   163       else {
   164   if ((words < 2) || (*w[0] < '0' || *w[0] > '9'))
   165     {
   166      ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
   167         "%s: line %d: syntax error\n", name, line);
   168      return -2;
   169     }
   170   i=atoi(w[0]);
   171   if (i<0 || i>127)
   172     {
   173       ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
   174         "%s: line %d: Program must be between 0 and 127\n",
   175         name, line);
   176       return -2;
   177     }
   178   if (!bank)
   179     {
   180       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   181        "%s: line %d: Must specify tone bank or drum set "
   182         "before assignment\n",
   183         name, line);
   184      return -2;
   185     }
   186   if (bank->tone[i].name)
   187     free(bank->tone[i].name);
   188   strcpy((bank->tone[i].name=safe_malloc(strlen(w[1])+1)),w[1]);
   189   bank->tone[i].note=bank->tone[i].amp=bank->tone[i].pan=
   190     bank->tone[i].strip_loop=bank->tone[i].strip_envelope=
   191       bank->tone[i].strip_tail=-1;
   192 
   193   for (j=2; j<words; j++)
   194     {
   195       if (!(cp=strchr(w[j], '=')))
   196         {
   197     ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: line %d: bad patch option %s\n",
   198       name, line, w[j]);
   199     return -2;
   200         }
   201       *cp++=0;
   202       if (!strcmp(w[j], "amp"))
   203       {
   204     k=atoi(cp);
   205     if ((k<0 || k>MAX_AMPLIFICATION) || (*cp < '0' || *cp > '9'))
   206       {
   207        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   208           "%s: line %d: amplification must be between "
   209          "0 and %d\n", name, line, MAX_AMPLIFICATION);
   210        return -2;
   211       }
   212     bank->tone[i].amp=k;
   213         }
   214       else if (!strcmp(w[j], "note"))
   215         {
   216     k=atoi(cp);
   217     if ((k<0 || k>127) || (*cp < '0' || *cp > '9'))
   218       {
   219        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   220          "%s: line %d: note must be between 0 and 127\n",
   221           name, line);
   222         return -2;
   223       }
   224     bank->tone[i].note=k;
   225       }
   226      else if (!strcmp(w[j], "pan"))
   227       {
   228     if (!strcmp(cp, "center"))
   229       k=64;
   230     else if (!strcmp(cp, "left"))
   231       k=0;
   232     else if (!strcmp(cp, "right"))
   233       k=127;
   234     else
   235       k=((atoi(cp)+100) * 100) / 157;
   236     if ((k<0 || k>127) ||
   237        (k==0 && *cp!='-' && (*cp < '0' || *cp > '9')))
   238       {
   239        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   240          "%s: line %d: panning must be left, right, "
   241          "center, or between -100 and 100\n",
   242          name, line);
   243        return -2;
   244       }
   245     bank->tone[i].pan=k;
   246       }
   247      else if (!strcmp(w[j], "keep"))
   248       {
   249     if (!strcmp(cp, "env"))
   250       bank->tone[i].strip_envelope=0;
   251     else if (!strcmp(cp, "loop"))
   252       bank->tone[i].strip_loop=0;
   253     else
   254       {
   255         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
   256           "%s: line %d: keep must be env or loop\n", name, line);
   257        return -2;
   258       }
   259       }
   260      else if (!strcmp(w[j], "strip"))
   261       {
   262     if (!strcmp(cp, "env"))
   263       bank->tone[i].strip_envelope=1;
   264     else if (!strcmp(cp, "loop"))
   265       bank->tone[i].strip_loop=1;
   266     else if (!strcmp(cp, "tail"))
   267       bank->tone[i].strip_tail=1;
   268     else
   269       {
   270        ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
   271          "%s: line %d: strip must be env, loop, or tail\n",
   272          name, line);
   273        return -2;
   274       }
   275       }
   276      else
   277       {
   278     ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: line %d: bad patch option %s\n",
   279       name, line, w[j]);
   280     return -2;
   281       }
   282     }
   283     }
   284    }
   285   if (ferror(fp))
   286    {
   287     ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Can't read from %s\n", name);
   288     close_file(fp);
   289     return -2;
   290    }
   291   close_file(fp);
   292   return 0;
   293 }
   294 
   295 int Timidity_Init(int rate, int format, int channels, int samples)
   296 {
   297   if (read_config_file(CONFIG_FILE)<0) {
   298     return(-1);
   299   }
   300 
   301   if (channels < 1 || channels == 3 || channels == 5 || channels > 6) return(-1);
   302 
   303   num_ochannels = channels;
   304 
   305   /* Set play mode parameters */
   306   play_mode->rate = rate;
   307   play_mode->encoding = 0;
   308   if ( (format&0xFF) == 16 ) {
   309     play_mode->encoding |= PE_16BIT;
   310   }
   311   if ( (format&0x8000) ) {
   312     play_mode->encoding |= PE_SIGNED;
   313   }
   314   if ( channels == 1 ) {
   315     play_mode->encoding |= PE_MONO;
   316   } 
   317   switch (format) {
   318     case AUDIO_S8:
   319       s32tobuf = s32tos8;
   320       break;
   321     case AUDIO_U8:
   322       s32tobuf = s32tou8;
   323       break;
   324     case AUDIO_S16LSB:
   325       s32tobuf = s32tos16l;
   326       break;
   327     case AUDIO_S16MSB:
   328       s32tobuf = s32tos16b;
   329       break;
   330     case AUDIO_U16LSB:
   331       s32tobuf = s32tou16l;
   332       break;
   333     case AUDIO_U16MSB:
   334       s32tobuf = s32tou16b;
   335       break;
   336     default:
   337       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Unsupported audio format");
   338       return(-1);
   339   }
   340   AUDIO_BUFFER_SIZE = samples;
   341 
   342   /* Allocate memory for mixing (WARNING:  Memory leak!) */
   343   resample_buffer = safe_malloc(AUDIO_BUFFER_SIZE*sizeof(resample_t)+100);
   344   common_buffer = safe_malloc(AUDIO_BUFFER_SIZE*num_ochannels*sizeof(int32));
   345 
   346   init_tables();
   347 
   348   if (ctl->open(0, 0)) {
   349     ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Couldn't open %s\n", ctl->id_name);
   350     return(-1);
   351   }
   352 
   353   if (!control_ratio) {
   354     control_ratio = play_mode->rate / CONTROLS_PER_SECOND;
   355     if(control_ratio<1)
   356       control_ratio=1;
   357     else if (control_ratio > MAX_CONTROL_RATIO)
   358       control_ratio=MAX_CONTROL_RATIO;
   359   }
   360   if (*def_instr_name)
   361     set_default_instrument(def_instr_name);
   362   return(0);
   363 }
   364 
   365 char timidity_error[1024] = "";
   366 char *Timidity_Error(void)
   367 {
   368   return(timidity_error);
   369 }