PageRenderTime 76ms CodeModel.GetById 10ms app.highlight 60ms RepoModel.GetById 1ms app.codeStats 1ms

/project/jni/sdl_sound/decoders/timidity/timidity.c

https://github.com/aichunyu/FFPlayer
C | 602 lines | 447 code | 58 blank | 97 comment | 144 complexity | ea8c0855df231dd7b2bb16343793a757 MD5 | raw file
  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
 22#if HAVE_CONFIG_H
 23#  include <config.h>
 24#endif
 25
 26#include <stdio.h>
 27#include <stdlib.h>
 28#include <string.h>
 29
 30#include "SDL_sound.h"
 31
 32#define __SDL_SOUND_INTERNAL__
 33#include "SDL_sound_internal.h"
 34
 35#include "timidity.h"
 36
 37#include "options.h"
 38#include "common.h"
 39#include "instrum.h"
 40#include "playmidi.h"
 41#include "readmidi.h"
 42#include "output.h"
 43
 44#include "tables.h"
 45
 46ToneBank *master_tonebank[128], *master_drumset[128];
 47
 48static char def_instr_name[256] = "";
 49
 50#define MAXWORDS 10
 51
 52/* Quick-and-dirty fgets() replacement. */
 53
 54static char *RWgets(SDL_RWops *rw, char *s, int size)
 55{
 56    int num_read = 0;
 57    int newline = 0;
 58
 59    while (num_read < size && !newline)
 60    {
 61	if (SDL_RWread(rw, &s[num_read], 1, 1) != 1)
 62	    break;
 63
 64	/* Unlike fgets(), don't store newline. Under Windows/DOS we'll
 65	 * probably get an extra blank line for every line that's being
 66	 * read, but that should be ok.
 67	 */
 68	if (s[num_read] == '\n' || s[num_read] == '\r')
 69	{
 70	    s[num_read] = '\0';
 71	    newline = 1;
 72	}
 73	
 74	num_read++;
 75    }
 76
 77    s[num_read] = '\0';
 78    
 79    return (num_read != 0) ? s : NULL;
 80}
 81
 82static int read_config_file(char *name)
 83{
 84  SDL_RWops *rw;
 85  char tmp[1024], *w[MAXWORDS], *cp;
 86  ToneBank *bank=0;
 87  int i, j, k, line=0, words;
 88  static int rcf_count=0;
 89
 90  if (rcf_count>50)
 91  {
 92    SNDDBG(("Probable source loop in configuration files\n"));
 93    return (-1);
 94  }
 95
 96  if (!(rw=open_file(name)))
 97   return -1;
 98
 99  while (RWgets(rw, tmp, sizeof(tmp)))
100  {
101    line++;
102    w[words=0]=strtok(tmp, " \t\240");
103    if (!w[0]) continue;
104
105        /* Originally the TiMidity++ extensions were prefixed like this */
106    if (strcmp(w[0], "#extension") == 0)
107        words = -1;
108    else if (*w[0] == '#')
109        continue;
110
111    while (w[words] && *w[words] != '#' && (words < MAXWORDS))
112      w[++words]=strtok(0," \t\240");
113
114        /*
115         * TiMidity++ adds a number of extensions to the config file format.
116         * Many of them are completely irrelevant to SDL_sound, but at least
117         * we shouldn't choke on them.
118         *
119         * Unfortunately the documentation for these extensions is often quite
120         * vague, gramatically strange or completely absent.
121         */
122    if (
123           !strcmp(w[0], "comm")      /* "comm" program second        */
124        || !strcmp(w[0], "HTTPproxy") /* "HTTPproxy" hostname:port    */
125        || !strcmp(w[0], "FTPproxy")  /* "FTPproxy" hostname:port     */
126        || !strcmp(w[0], "mailaddr")  /* "mailaddr" your-mail-address */
127        || !strcmp(w[0], "opt")       /* "opt" timidity-options       */
128       )
129    {
130            /*
131             * + "comm" sets some kind of comment -- the documentation is too
132             *   vague for me to understand at this time.
133             * + "HTTPproxy", "FTPproxy" and "mailaddr" are for reading data
134             *   over a network, rather than from the file system.
135             * + "opt" specifies default options for TiMidity++.
136             *
137             * These are all quite useless for our version of TiMidity, so
138             * they can safely remain no-ops.
139             */
140    } else if (!strcmp(w[0], "timeout")) /* "timeout" program second */
141    {
142            /*
143             * Specifies a timeout value of the program. A number of seconds
144             * before TiMidity kills the note. This may be useful to implement
145             * later, but I don't see any urgent need for it.
146             */
147        SNDDBG(("FIXME: Implement \"timeout\" in TiMidity config.\n"));
148    } else if (!strcmp(w[0], "copydrumset")  /* "copydrumset" drumset */
149               || !strcmp(w[0], "copybank")) /* "copybank" bank       */
150    {
151            /*
152             * Copies all the settings of the specified drumset or bank to
153             * the current drumset or bank. May be useful later, but not a
154             * high priority.
155             */
156        SNDDBG(("FIXME: Implement \"%s\" in TiMidity config.\n", w[0]));
157    } else if (!strcmp(w[0], "undef")) /* "undef" progno */
158    {
159            /*
160             * Undefines the tone "progno" of the current tone bank (or
161             * drum set?). Not a high priority.
162             */
163        SNDDBG(("FIXME: Implement \"undef\" in TiMidity config.\n"));
164    } else if (!strcmp(w[0], "altassign")) /* "altassign" prog1 prog2 ... */
165    {
166            /*
167             * Sets the alternate assign for drum set. Whatever that's
168             * supposed to mean.
169             */
170        SNDDBG(("FIXME: Implement \"altassign\" in TiMidity config.\n"));
171    } else if (!strcmp(w[0], "soundfont")
172               || !strcmp(w[0], "font"))
173    {
174            /*
175             * I can't find any documentation for these, but I guess they're
176             * an alternative way of loading/unloading instruments.
177             * 
178             * "soundfont" sf_file "remove"
179             * "soundfont" sf_file ["order=" order] ["cutoff=" cutoff]
180             *                     ["reso=" reso] ["amp=" amp]
181             * "font" "exclude" bank preset keynote
182             * "font" "order" order bank preset keynote
183             */
184        SNDDBG(("FIXME: Implmement \"%s\" in TiMidity config.\n", w[0]));
185    } else if (!strcmp(w[0], "progbase"))
186    {
187            /*
188             * The documentation for this makes absolutely no sense to me, but
189             * apparently it sets some sort of base offset for tone numbers.
190             * Why anyone would want to do this is beyond me.
191             */
192        SNDDBG(("FIXME: Implement \"progbase\" in TiMidity config.\n"));
193    } else if (!strcmp(w[0], "map")) /* "map" name set1 elem1 set2 elem2 */
194    {
195            /*
196             * This extension is the one we will need to implement, as it is
197             * used by the "eawpats". Unfortunately I cannot find any
198             * documentation whatsoever for it, but it looks like it's used
199             * for remapping one instrument to another somehow.
200             */
201        SNDDBG(("FIXME: Implement \"map\" in TiMidity config.\n"));
202    }
203
204        /* Standard TiMidity config */
205    
206    else if (!strcmp(w[0], "dir"))
207    {
208      if (words < 2)
209      {
210	SNDDBG(("%s: line %d: No directory given\n", name, line));
211	return -2;
212      }
213      for (i=1; i<words; i++)
214	add_to_pathlist(w[i]);
215    }
216    else if (!strcmp(w[0], "source"))
217    {
218      if (words < 2)
219      {
220	SNDDBG(("%s: line %d: No file name given\n", name, line));
221	return -2;
222      }
223      for (i=1; i<words; i++)
224      {
225	rcf_count++;
226	read_config_file(w[i]);
227	rcf_count--;
228      }
229    }
230    else if (!strcmp(w[0], "default"))
231    {
232      if (words != 2)
233      {
234	SNDDBG(("%s: line %d: Must specify exactly one patch name\n",
235		name, line));
236	return -2;
237      }
238      strncpy(def_instr_name, w[1], 255);
239      def_instr_name[255]='\0';
240    }
241    else if (!strcmp(w[0], "drumset"))
242    {
243      if (words < 2)
244      {
245	SNDDBG(("%s: line %d: No drum set number given\n", name, line));
246	return -2;
247      }
248      i=atoi(w[1]);
249      if (i<0 || i>127)
250      {
251	SNDDBG(("%s: line %d: Drum set must be between 0 and 127\n",
252		name, line));
253	return -2;
254      }
255      if (!master_drumset[i])
256      {
257	master_drumset[i] = safe_malloc(sizeof(ToneBank));
258	memset(master_drumset[i], 0, sizeof(ToneBank));
259	master_drumset[i]->tone = safe_malloc(128 * sizeof(ToneBankElement));
260	memset(master_drumset[i]->tone, 0, 128 * sizeof(ToneBankElement));
261      }
262      bank=master_drumset[i];
263    }
264    else if (!strcmp(w[0], "bank"))
265    {
266      if (words < 2)
267      {
268	SNDDBG(("%s: line %d: No bank number given\n", name, line));
269	return -2;
270      }
271      i=atoi(w[1]);
272      if (i<0 || i>127)
273      {
274	SNDDBG(("%s: line %d: Tone bank must be between 0 and 127\n",
275		name, line));
276	return -2;
277      }
278      if (!master_tonebank[i])
279      {
280	master_tonebank[i] = safe_malloc(sizeof(ToneBank));
281	memset(master_tonebank[i], 0, sizeof(ToneBank));
282	master_tonebank[i]->tone = safe_malloc(128 * sizeof(ToneBankElement));
283	memset(master_tonebank[i]->tone, 0, 128 * sizeof(ToneBankElement));
284      }
285      bank=master_tonebank[i];
286    }
287    else
288    {
289      if ((words < 2) || (*w[0] < '0' || *w[0] > '9'))
290      {
291	SNDDBG(("%s: line %d: syntax error\n", name, line));
292	return -2;
293      }
294      i=atoi(w[0]);
295      if (i<0 || i>127)
296      {
297	SNDDBG(("%s: line %d: Program must be between 0 and 127\n",
298		name, line));
299	return -2;
300      }
301      if (!bank)
302      {
303	SNDDBG(("%s: line %d: Must specify tone bank or drum set before assignment\n",
304		name, line));
305	return -2;
306      }
307      if (bank->tone[i].name)
308	free(bank->tone[i].name);
309      strcpy((bank->tone[i].name=safe_malloc(strlen(w[1])+1)),w[1]);
310      bank->tone[i].note=bank->tone[i].amp=bank->tone[i].pan=
311      bank->tone[i].strip_loop=bank->tone[i].strip_envelope=
312      bank->tone[i].strip_tail=-1;
313
314      for (j=2; j<words; j++)
315      {
316	if (!(cp=strchr(w[j], '=')))
317	{
318	  SNDDBG(("%s: line %d: bad patch option %s\n", name, line, w[j]));
319	  return -2;
320	}
321	*cp++=0;
322	if (!strcmp(w[j], "amp"))
323	{
324	  k=atoi(cp);
325	  if ((k<0 || k>MAX_AMPLIFICATION) || (*cp < '0' || *cp > '9'))
326	  {
327	    SNDDBG(("%s: line %d: amplification must be between 0 and %d\n",
328		    name, line, MAX_AMPLIFICATION));
329	    return -2;
330	  }
331	  bank->tone[i].amp=k;
332	}
333	else if (!strcmp(w[j], "note"))
334	{
335	  k=atoi(cp);
336	  if ((k<0 || k>127) || (*cp < '0' || *cp > '9'))
337	  {
338	    SNDDBG(("%s: line %d: note must be between 0 and 127\n",
339		    name, line));
340	    return -2;
341	  }
342	  bank->tone[i].note=k;
343	}
344	else if (!strcmp(w[j], "pan"))
345	{
346	  if (!strcmp(cp, "center"))
347	    k=64;
348	  else if (!strcmp(cp, "left"))
349	    k=0;
350	  else if (!strcmp(cp, "right"))
351	    k=127;
352	  else
353	    k=((atoi(cp)+100) * 100) / 157;
354	  if ((k<0 || k>127) || (k==0 && *cp!='-' && (*cp < '0' || *cp > '9')))
355	  {
356	    SNDDBG(("%s: line %d: panning must be left, right, center, or between -100 and 100\n",
357		    name, line));
358	    return -2;
359	  }
360	  bank->tone[i].pan=k;
361	}
362	else if (!strcmp(w[j], "keep"))
363	{
364	  if (!strcmp(cp, "env"))
365	    bank->tone[i].strip_envelope=0;
366	  else if (!strcmp(cp, "loop"))
367	    bank->tone[i].strip_loop=0;
368	  else
369	  {
370	    SNDDBG(("%s: line %d: keep must be env or loop\n", name, line));
371	    return -2;
372	  }
373	}
374	else if (!strcmp(w[j], "strip"))
375	{
376	  if (!strcmp(cp, "env"))
377	    bank->tone[i].strip_envelope=1;
378	  else if (!strcmp(cp, "loop"))
379	    bank->tone[i].strip_loop=1;
380	  else if (!strcmp(cp, "tail"))
381	    bank->tone[i].strip_tail=1;
382	  else
383	  {
384	    SNDDBG(("%s: line %d: strip must be env, loop, or tail\n",
385		    name, line));
386	    return -2;
387	  }
388	}
389	else
390	{
391	  SNDDBG(("%s: line %d: bad patch option %s\n", name, line, w[j]));
392	  return -2;
393	}
394      }
395    }
396  }
397  SDL_RWclose(rw);
398  return 0;
399}
400
401int Timidity_Init_NoConfig()
402{
403  /* Allocate memory for the standard tonebank and drumset */
404  master_tonebank[0] = safe_malloc(sizeof(ToneBank));
405  memset(master_tonebank[0], 0, sizeof(ToneBank));
406  master_tonebank[0]->tone = safe_malloc(128 * sizeof(ToneBankElement));
407  memset(master_tonebank[0]->tone, 0, 128 * sizeof(ToneBankElement));
408
409  master_drumset[0] = safe_malloc(sizeof(ToneBank));
410  memset(master_drumset[0], 0, sizeof(ToneBank));
411  master_drumset[0]->tone = safe_malloc(128 * sizeof(ToneBankElement));
412  memset(master_drumset[0]->tone, 0, 128 * sizeof(ToneBankElement));
413
414  return 0;
415}
416
417int Timidity_Init()
418{
419  /* !!! FIXME: This may be ugly, but slightly less so than requiring the
420   *            default search path to have only one element. I think.
421   *
422   *            We only need to include the likely locations for the config
423   *            file itself since that file should contain any other directory
424   *            that needs to be added to the search path.
425   */
426#ifdef WIN32
427  add_to_pathlist("\\TIMIDITY");
428#else
429  add_to_pathlist("/usr/local/lib/timidity");
430  add_to_pathlist("/etc");
431#endif
432
433  Timidity_Init_NoConfig();
434
435  return read_config_file(CONFIG_FILE);
436}
437
438MidiSong *Timidity_LoadDLSSong(SDL_RWops *rw, DLS_Patches *patches, SDL_AudioSpec *audio)
439{
440  MidiSong *song;
441  Sint32 events;
442  int i;
443
444  if (rw == NULL)
445      return NULL;
446  
447  /* Allocate memory for the song */
448  song = (MidiSong *)safe_malloc(sizeof(*song));
449  memset(song, 0, sizeof(*song));
450  song->patches = patches;
451
452  for (i = 0; i < 128; i++)
453  {
454    if (master_tonebank[i])
455    {
456      song->tonebank[i] = safe_malloc(sizeof(ToneBank));
457      memset(song->tonebank[i], 0, sizeof(ToneBank));
458      song->tonebank[i]->tone = master_tonebank[i]->tone;
459    }
460    if (master_drumset[i])
461    {
462      song->drumset[i] = safe_malloc(sizeof(ToneBank));
463      memset(song->drumset[i], 0, sizeof(ToneBank));
464      song->drumset[i]->tone = master_drumset[i]->tone;
465    }
466  }
467
468  song->amplification = DEFAULT_AMPLIFICATION;
469  song->voices = DEFAULT_VOICES;
470  song->drumchannels = DEFAULT_DRUMCHANNELS;
471
472  song->rw = rw;
473
474  song->rate = audio->freq;
475  song->encoding = 0;
476  if ((audio->format & 0xFF) == 16)
477      song->encoding |= PE_16BIT;
478  if (audio->format & 0x8000)
479      song->encoding |= PE_SIGNED;
480  if (audio->channels == 1)
481      song->encoding |= PE_MONO;
482  switch (audio->format) {
483      case AUDIO_S8:
484	  song->write = s32tos8;
485	  break;
486      case AUDIO_U8:
487	  song->write = s32tou8;
488	  break;
489      case AUDIO_S16LSB:
490	  song->write = s32tos16l;
491	  break;
492      case AUDIO_S16MSB:
493	  song->write = s32tos16b;
494	  break;
495      case AUDIO_U16LSB:
496	  song->write = s32tou16l;
497	  break;
498      default:
499	  SNDDBG(("Unsupported audio format"));
500	  song->write = s32tou16l;
501	  break;
502  }
503
504  song->buffer_size = audio->samples;
505  song->resample_buffer = safe_malloc(audio->samples * sizeof(sample_t));
506  song->common_buffer = safe_malloc(audio->samples * 2 * sizeof(Sint32));
507  
508  song->control_ratio = audio->freq / CONTROLS_PER_SECOND;
509  if (song->control_ratio < 1)
510      song->control_ratio = 1;
511  else if (song->control_ratio > MAX_CONTROL_RATIO)
512      song->control_ratio = MAX_CONTROL_RATIO;
513
514  song->lost_notes = 0;
515  song->cut_notes = 0;
516
517  song->events = read_midi_file(song, &events, &song->samples);
518
519  /* The RWops can safely be closed at this point, but let's make that the
520   * responsibility of the caller.
521   */
522  
523  /* Make sure everything is okay */
524  if (!song->events) {
525    free(song);
526    return(NULL);
527  }
528
529  song->default_instrument = 0;
530  song->default_program = DEFAULT_PROGRAM;
531
532  if (*def_instr_name)
533    set_default_instrument(song, def_instr_name);
534
535  load_missing_instruments(song);
536
537  return(song);
538}
539
540MidiSong *Timidity_LoadSong(SDL_RWops *rw, SDL_AudioSpec *audio)
541{
542  return Timidity_LoadDLSSong(rw, NULL, audio);
543}
544
545void Timidity_FreeSong(MidiSong *song)
546{
547  int i;
548
549  free_instruments(song);
550
551  for (i = 0; i < 128; i++)
552  {
553    if (song->tonebank[i])
554      free(song->tonebank[i]);
555    if (song->drumset[i])
556      free(song->drumset[i]);
557  }
558  
559  free(song->common_buffer);
560  free(song->resample_buffer);
561  free(song->events);
562  free(song);
563}
564
565void Timidity_Exit(void)
566{
567  int i, j;
568
569  for (i = 0; i < 128; i++)
570  {
571    if (master_tonebank[i])
572    {
573      ToneBankElement *e = master_tonebank[i]->tone;
574      if (e != NULL)
575      {
576        for (j = 0; j < 128; j++)
577        {
578          if (e[j].name != NULL)
579            free(e[j].name);
580        }
581        free(e);
582      }
583      free(master_tonebank[i]);
584    }
585    if (master_drumset[i])
586    {
587      ToneBankElement *e = master_drumset[i]->tone;
588      if (e != NULL)
589      {
590        for (j = 0; j < 128; j++)
591        {
592          if (e[j].name != NULL)
593            free(e[j].name);
594        }
595        free(e);
596      }
597      free(master_drumset[i]);
598    }
599  }
600
601  free_pathlist();
602}