timidity/instrum.c
author Ozkan Sezer <sezeroz@gmail.com>
Sat, 13 Oct 2018 23:02:04 +0300
branchSDL-1.2
changeset 908 6b860486ce24
parent 518 8bc9b5fd2aae
child 642 dae7bb0a66b1
permissions -rw-r--r--
Mix_InitMP3: unload dll if mpg123_init() fails.
     1 /*
     2     TiMidity -- Experimental MIDI to WAVE converter
     3     Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
     4 
     5     This program is free software; you can redistribute it and/or modify
     6     it under the terms of the Perl Artistic License, available in COPYING.
     7  */
     8 
     9 #include <stdio.h>
    10 #include <string.h>
    11 #include <stdlib.h>
    12 
    13 #include "config.h"
    14 #include "common.h"
    15 #include "instrum.h"
    16 #include "playmidi.h"
    17 #include "output.h"
    18 #include "ctrlmode.h"
    19 #include "resample.h"
    20 #include "tables.h"
    21 #include "filter.h"
    22 
    23 /* Some functions get aggravated if not even the standard banks are 
    24    available. */
    25 static ToneBank standard_tonebank, standard_drumset;
    26 ToneBank 
    27   *tonebank[MAXBANK]={&standard_tonebank},
    28   *drumset[MAXBANK]={&standard_drumset};
    29 
    30 /* This is a special instrument, used for all melodic programs */
    31 InstrumentLayer *default_instrument=0;
    32 
    33 /* This is only used for tracks that don't specify a program */
    34 int default_program=DEFAULT_PROGRAM;
    35 
    36 int antialiasing_allowed=0;
    37 #ifdef FAST_DECAY
    38 int fast_decay=1;
    39 #else
    40 int fast_decay=0;
    41 #endif
    42 
    43 
    44 int current_tune_number = 0;
    45 int last_tune_purged = 0;
    46 int current_patch_memory = 0;
    47 int max_patch_memory = 60000000;
    48 
    49 static void purge_as_required(void);
    50 
    51 static void free_instrument(Instrument *ip)
    52 {
    53   Sample *sp;
    54   int i;
    55   if (!ip) return;
    56 
    57   if (!ip->contents)
    58   for (i=0; i<ip->samples; i++)
    59     {
    60       sp=&(ip->sample[i]);
    61       if (sp->data) free(sp->data);
    62     }
    63   free(ip->sample);
    64 
    65   if (!ip->contents)
    66   for (i=0; i<ip->right_samples; i++)
    67     {
    68       sp=&(ip->right_sample[i]);
    69       if (sp->data) free(sp->data);
    70     }
    71   if (ip->right_sample)
    72     free(ip->right_sample);
    73   free(ip);
    74 }
    75 
    76 
    77 static void free_layer(InstrumentLayer *lp)
    78 {
    79   InstrumentLayer *next;
    80 
    81   current_patch_memory -= lp->size;
    82 
    83   for (; lp; lp = next)
    84    {
    85      next = lp->next;
    86      free_instrument(lp->instrument);
    87      free(lp);
    88    }
    89 }
    90 
    91 static void free_bank(int dr, int b)
    92 {
    93   int i;
    94   ToneBank *bank=((dr) ? drumset[b] : tonebank[b]);
    95   for (i=0; i<MAXPROG; i++)
    96   {
    97     if (bank->tone[i].layer)
    98     {
    99 	  /* Not that this could ever happen, of course */
   100 	  if (bank->tone[i].layer != MAGIC_LOAD_INSTRUMENT)
   101 	  {
   102 	    free_layer(bank->tone[i].layer);
   103 	    bank->tone[i].layer=NULL;
   104 	    bank->tone[i].last_used=-1;
   105 	  }
   106     }
   107     if (bank->tone[i].name)
   108     {
   109       free(bank->tone[i].name);
   110       bank->tone[i].name = NULL;
   111     }
   112   }
   113 }
   114 
   115 
   116 static void free_old_bank(int dr, int b, int how_old)
   117 {
   118   int i;
   119   ToneBank *bank=((dr) ? drumset[b] : tonebank[b]);
   120   for (i=0; i<MAXPROG; i++)
   121     if (bank->tone[i].layer && bank->tone[i].last_used < how_old)
   122       {
   123 	if (bank->tone[i].layer != MAGIC_LOAD_INSTRUMENT)
   124 	  {
   125 	    ctl->cmsg(CMSG_INFO, VERB_DEBUG,
   126 		"Unloading %s %s[%d,%d] - last used %d.",
   127 		(dr)? "drum" : "inst", bank->tone[i].name,
   128 		i, b, bank->tone[i].last_used);
   129 	    free_layer(bank->tone[i].layer);
   130 	    bank->tone[i].layer=NULL;
   131 	    bank->tone[i].last_used=-1;
   132 	  }
   133       }
   134 }
   135 
   136 
   137 int32 convert_envelope_rate_attack(uint8 rate, uint8 fastness)
   138 {
   139   int32 r;
   140 
   141   r=3-((rate>>6) & 0x3);
   142   r*=3;
   143   r = (int32)(rate & 0x3f) << r; /* 6.9 fixed point */
   144 
   145   /* 15.15 fixed point. */
   146   return (((r * 44100) / play_mode->rate) * control_ratio) 
   147     << 10;
   148 }
   149 
   150 int32 convert_envelope_rate(uint8 rate)
   151 {
   152   int32 r;
   153 
   154   r=3-((rate>>6) & 0x3);
   155   r*=3;
   156   r = (int32)(rate & 0x3f) << r; /* 6.9 fixed point */
   157 
   158   /* 15.15 fixed point. */
   159   return (((r * 44100) / play_mode->rate) * control_ratio) 
   160     << ((fast_decay) ? 10 : 9);
   161 }
   162 
   163 int32 convert_envelope_offset(uint8 offset)
   164 {
   165   /* This is not too good... Can anyone tell me what these values mean?
   166      Are they GUS-style "exponential" volumes? And what does that mean? */
   167 
   168   /* 15.15 fixed point */
   169   return offset << (7+15);
   170 }
   171 
   172 int32 convert_tremolo_sweep(uint8 sweep)
   173 {
   174   if (!sweep)
   175     return 0;
   176 
   177   return
   178     ((control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
   179       (play_mode->rate * sweep);
   180 }
   181 
   182 int32 convert_vibrato_sweep(uint8 sweep, int32 vib_control_ratio)
   183 {
   184   if (!sweep)
   185     return 0;
   186 
   187   return
   188     (int32) (FSCALE((double) (vib_control_ratio) * SWEEP_TUNING, SWEEP_SHIFT)
   189 	     / (double)(play_mode->rate * sweep));
   190 
   191   /* this was overflowing with seashore.pat
   192 
   193       ((vib_control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
   194       (play_mode->rate * sweep); */
   195 }
   196 
   197 int32 convert_tremolo_rate(uint8 rate)
   198 {
   199   return
   200     ((SINE_CYCLE_LENGTH * control_ratio * rate) << RATE_SHIFT) /
   201       (TREMOLO_RATE_TUNING * play_mode->rate);
   202 }
   203 
   204 int32 convert_vibrato_rate(uint8 rate)
   205 {
   206   /* Return a suitable vibrato_control_ratio value */
   207   return
   208     (VIBRATO_RATE_TUNING * play_mode->rate) / 
   209       (rate * 2 * VIBRATO_SAMPLE_INCREMENTS);
   210 }
   211 
   212 static void reverse_data(int16 *sp, int32 ls, int32 le)
   213 {
   214   int16 s, *ep=sp+le;
   215   sp+=ls;
   216   le-=ls;
   217   le/=2;
   218   while (le--)
   219     {
   220       s=*sp;
   221       *sp++=*ep;
   222       *ep--=s;
   223     }
   224 }
   225 
   226 /* 
   227    If panning or note_to_use != -1, it will be used for all samples,
   228    instead of the sample-specific values in the instrument file. 
   229 
   230    For note_to_use, any value <0 or >127 will be forced to 0.
   231  
   232    For other parameters, 1 means yes, 0 means no, other values are
   233    undefined.
   234 
   235    TODO: do reverse loops right */
   236 static InstrumentLayer *load_instrument(const char *name, int font_type, int percussion,
   237 				   int panning, int amp, int cfg_tuning, int note_to_use,
   238 				   int strip_loop, int strip_envelope,
   239 				   int strip_tail, int bank, int gm_num, int sf_ix)
   240 {
   241   InstrumentLayer *lp, *lastlp, *headlp = 0;
   242   Instrument *ip;
   243   FILE *fp;
   244   uint8 tmp[1024];
   245   int i,j,noluck=0;
   246 #ifdef PATCH_EXT_LIST
   247   static char *patch_ext[] = PATCH_EXT_LIST;
   248 #endif
   249   int sf2flag = 0;
   250   int right_samples = 0;
   251   int stereo_channels = 1, stereo_layer;
   252   int vlayer_list[19][4], vlayer, vlayer_count = 0;
   253 
   254   if (!name) return 0;
   255   
   256   /* Open patch file */
   257   if ((fp=open_file(name, 1, OF_NORMAL)) == NULL)
   258     {
   259       noluck=1;
   260 #ifdef PATCH_EXT_LIST
   261       /* Try with various extensions */
   262       for (i=0; patch_ext[i]; i++)
   263 	{
   264 	  if (strlen(name)+strlen(patch_ext[i])<PATH_MAX)
   265 	    {
   266               char path[PATH_MAX];
   267 	      strcpy(path, name);
   268 	      strcat(path, patch_ext[i]);
   269 	      if ((fp=open_file(path, 1, OF_NORMAL)) != NULL)
   270 		{
   271 		  noluck=0;
   272 		  break;
   273 		}
   274 	    }
   275 	}
   276 #endif
   277     }
   278   
   279   if (noluck)
   280     {
   281       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   282 		"Instrument `%s' can't be found.", name);
   283       return 0;
   284     }
   285       
   286   /*ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s", current_filename);*/
   287   
   288   /* Read some headers and do cursory sanity checks. There are loads
   289      of magic offsets. This could be rewritten... */
   290 
   291   if ((239 != fread(tmp, 1, 239, fp)) ||
   292       (memcmp(tmp, "GF1PATCH110\0ID#000002", 22) &&
   293        memcmp(tmp, "GF1PATCH100\0ID#000002", 22))) /* don't know what the
   294 						      differences are */
   295     {
   296       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: not an instrument", name);
   297       return 0;
   298     }
   299 
   300 /* patch layout:
   301  * bytes:  info:		starts at offset:
   302  * 22	id (see above)		0
   303  * 60	copyright		22
   304  *  1	instruments		82
   305  *  1	voices			83
   306  *  1	channels		84
   307  *  2	number of waveforms	85
   308  *  2	master volume		87
   309  *  4	datasize		89
   310  * 36   reserved, but now:	93
   311  * 	7 "SF2EXT\0" id			93
   312  * 	1 right samples		       100
   313  *     28 reserved		       101
   314  *  2	instrument number	129
   315  * 16	instrument name		131
   316  *  4	instrument size		147
   317  *  1	number of layers	151
   318  * 40	reserved		152
   319  *  1	layer duplicate		192
   320  *  1	layer number		193
   321  *  4	layer size		194
   322  *  1	number of samples	198
   323  * 40	reserved		199
   324  * 				239
   325  * THEN, for each sample, see below
   326  */
   327 
   328   if (!memcmp(tmp + 93, "SF2EXT", 6))
   329     {
   330 	    sf2flag = 1;
   331 	    vlayer_count = tmp[152];
   332     }
   333 
   334   if (tmp[82] != 1 && tmp[82] != 0) /* instruments. To some patch makers, 
   335 				       0 means 1 */
   336     {
   337       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   338 	   "Can't handle patches with %d instruments", tmp[82]);
   339       return 0;
   340     }
   341 
   342   if (tmp[151] != 1 && tmp[151] != 0) /* layers. What's a layer? */
   343     {
   344       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   345 	   "Can't handle instruments with %d layers", tmp[151]);
   346       return 0;
   347     }
   348   
   349 
   350   if (sf2flag && vlayer_count > 0) {
   351 	for (i = 0; i < 9; i++)
   352 	  for (j = 0; j < 4; j++)
   353 	    vlayer_list[i][j] = tmp[153+i*4+j];
   354 	for (i = 9; i < 19; i++)
   355 	  for (j = 0; j < 4; j++)
   356 	    vlayer_list[i][j] = tmp[199+(i-9)*4+j];
   357   }
   358   else {
   359 	for (i = 0; i < 19; i++)
   360 	  for (j = 0; j < 4; j++)
   361 	    vlayer_list[i][j] = 0;
   362 	vlayer_list[0][0] = 0;
   363 	vlayer_list[0][1] = 127;
   364 	vlayer_list[0][2] = tmp[198];
   365 	vlayer_list[0][3] = 0;
   366 	vlayer_count = 1;
   367   }
   368 
   369   lastlp = 0;
   370 
   371   for (vlayer = 0; vlayer < vlayer_count; vlayer++) {
   372 
   373   lp=(InstrumentLayer *)safe_malloc(sizeof(InstrumentLayer));
   374   lp->size = sizeof(InstrumentLayer);
   375   lp->lo = vlayer_list[vlayer][0];
   376   lp->hi = vlayer_list[vlayer][1];
   377   ip=(Instrument *)safe_malloc(sizeof(Instrument));
   378   lp->size += sizeof(Instrument);
   379   lp->instrument = ip;
   380   lp->next = 0;
   381 
   382   if (lastlp) lastlp->next = lp;
   383   else headlp = lp;
   384 
   385   lastlp = lp;
   386 
   387   if (sf2flag) ip->type = INST_SF2;
   388   else ip->type = INST_GUS;
   389   ip->samples = vlayer_list[vlayer][2];
   390   ip->sample = (Sample *)safe_malloc(sizeof(Sample) * ip->samples);
   391   lp->size += sizeof(Sample) * ip->samples;
   392   ip->left_samples = ip->samples;
   393   ip->left_sample = ip->sample;
   394   right_samples = vlayer_list[vlayer][3];
   395   ip->right_samples = right_samples;
   396   if (right_samples)
   397     {
   398       ip->right_sample = (Sample *)safe_malloc(sizeof(Sample) * right_samples);
   399       lp->size += sizeof(Sample) * right_samples;
   400       stereo_channels = 2;
   401     }
   402   else ip->right_sample = 0;
   403   ip->contents = 0;
   404 
   405   ctl->cmsg(CMSG_INFO, VERB_NOISY, "%s%s[%d,%d] %s(%d-%d layer %d of %d)",
   406 	(percussion)? "   ":"", name,
   407 	(percussion)? note_to_use : gm_num, bank,
   408 	(right_samples)? "(2) " : "",
   409 	lp->lo, lp->hi, vlayer+1, vlayer_count);
   410 
   411  for (stereo_layer = 0; stereo_layer < stereo_channels; stereo_layer++)
   412  {
   413   int sample_count = 0;
   414 
   415   if (stereo_layer == 0) sample_count = ip->left_samples;
   416   else if (stereo_layer == 1) sample_count = ip->right_samples;
   417 
   418   for (i=0; i < sample_count; i++)
   419     {
   420       uint8 fractions;
   421       int32 tmplong;
   422       uint16 tmpshort;
   423       uint16 sample_volume = 0;
   424       uint8 tmpchar;
   425       Sample *sp = 0;
   426       uint8 sf2delay = 0;
   427 
   428 #define READ_CHAR(thing) \
   429       if (1 != fread(&tmpchar, 1, 1, fp)) goto fail; \
   430       thing = tmpchar;
   431 #define READ_SHORT(thing) \
   432       if (1 != fread(&tmpshort, 2, 1, fp)) goto fail; \
   433       thing = LE_SHORT(tmpshort);
   434 #define READ_LONG(thing) \
   435       if (1 != fread(&tmplong, 4, 1, fp)) goto fail; \
   436       thing = LE_LONG(tmplong);
   437 
   438 /*
   439  *  7	sample name
   440  *  1	fractions
   441  *  4	length
   442  *  4	loop start
   443  *  4	loop end
   444  *  2	sample rate
   445  *  4	low frequency
   446  *  4	high frequency
   447  *  2	finetune
   448  *  1	panning
   449  *  6	envelope rates			|
   450  *  6	envelope offsets		|  18 bytes
   451  *  3	tremolo sweep, rate, depth	|
   452  *  3	vibrato sweep, rate, depth	|
   453  *  1	sample mode
   454  *  2	scale frequency
   455  *  2	scale factor
   456  *  2	sample volume (??)
   457  * 34	reserved
   458  * Now: 1	delay
   459  * 	33	reserved
   460  */
   461       skip(fp, 7); /* Skip the wave name */
   462 
   463       if (1 != fread(&fractions, 1, 1, fp))
   464 	{
   465 	fail:
   466 	  ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d", i);
   467 	  if (stereo_layer == 1)
   468 	     {
   469 	       for (j=0; j<i; j++)
   470 	         free(ip->right_sample[j].data);
   471 	       free(ip->right_sample);
   472 	       i = ip->left_samples;
   473 	     }
   474 	  for (j=0; j<i; j++)
   475 	    free(ip->left_sample[j].data);
   476 	  free(ip->left_sample);
   477 	  free(ip);
   478 	  free(lp);
   479 	  return 0;
   480 	}
   481 
   482       if (stereo_layer == 0) sp=&(ip->left_sample[i]);
   483       else if (stereo_layer == 1) sp=&(ip->right_sample[i]);
   484 
   485       READ_LONG(sp->data_length);
   486       READ_LONG(sp->loop_start);
   487       READ_LONG(sp->loop_end);
   488       READ_SHORT(sp->sample_rate);
   489       READ_LONG(sp->low_freq);
   490       READ_LONG(sp->high_freq);
   491       READ_LONG(sp->root_freq);
   492       skip(fp, 2); /* Why have a "root frequency" and then "tuning"?? */
   493       
   494       READ_CHAR(tmp[0]);
   495 
   496       if (panning==-1)
   497 	sp->panning = (tmp[0] * 8 + 4) & 0x7f;
   498       else
   499 	sp->panning=(uint8)(panning & 0x7F);
   500 
   501       sp->resonance=0;
   502       sp->cutoff_freq=0;
   503       sp->reverberation=0;
   504       sp->chorusdepth=0;
   505       sp->exclusiveClass=0;
   506       sp->keyToModEnvHold=0;
   507       sp->keyToModEnvDecay=0;
   508       sp->keyToVolEnvHold=0;
   509       sp->keyToVolEnvDecay=0;
   510 
   511       if (cfg_tuning)
   512 	{
   513 	  double tune_factor = (double)(cfg_tuning)/1200.0;
   514 	  tune_factor = pow(2.0, tune_factor);
   515 	  sp->root_freq = (uint32)( tune_factor * (double)sp->root_freq );
   516 	}
   517 
   518       /* envelope, tremolo, and vibrato */
   519       if (18 != fread(tmp, 1, 18, fp)) goto fail; 
   520 
   521       if (!tmp[13] || !tmp[14])
   522 	{
   523 	  sp->tremolo_sweep_increment=
   524 	    sp->tremolo_phase_increment=sp->tremolo_depth=0;
   525 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo");
   526 	}
   527       else
   528 	{
   529 	  sp->tremolo_sweep_increment=convert_tremolo_sweep(tmp[12]);
   530 	  sp->tremolo_phase_increment=convert_tremolo_rate(tmp[13]);
   531 	  sp->tremolo_depth=tmp[14];
   532 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
   533 	       " * tremolo: sweep %d, phase %d, depth %d",
   534 	       sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
   535 	       sp->tremolo_depth);
   536 	}
   537 
   538       if (!tmp[16] || !tmp[17])
   539 	{
   540 	  sp->vibrato_sweep_increment=
   541 	    sp->vibrato_control_ratio=sp->vibrato_depth=0;
   542 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato");
   543 	}
   544       else
   545 	{
   546 	  sp->vibrato_control_ratio=convert_vibrato_rate(tmp[16]);
   547 	  sp->vibrato_sweep_increment=
   548 	    convert_vibrato_sweep(tmp[15], sp->vibrato_control_ratio);
   549 	  sp->vibrato_depth=tmp[17];
   550 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
   551 	       " * vibrato: sweep %d, ctl %d, depth %d",
   552 	       sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
   553 	       sp->vibrato_depth);
   554 
   555 	}
   556 
   557       READ_CHAR(sp->modes);
   558       READ_SHORT(sp->freq_center);
   559       READ_SHORT(sp->freq_scale);
   560 
   561       if (sf2flag)
   562         {
   563           READ_SHORT(sample_volume);
   564 	  READ_CHAR(sf2delay);
   565           READ_CHAR(sp->exclusiveClass);
   566           skip(fp, 32);
   567 	}
   568       else
   569         {
   570           skip(fp, 36);
   571         }
   572 
   573       /* Mark this as a fixed-pitch instrument if such a deed is desired. */
   574       if (note_to_use!=-1)
   575 	sp->note_to_use=(uint8)(note_to_use);
   576       else
   577 	sp->note_to_use=0;
   578       
   579       /* seashore.pat in the Midia patch set has no Sustain. I don't
   580          understand why, and fixing it by adding the Sustain flag to
   581          all looped patches probably breaks something else. We do it
   582          anyway. */
   583 	 
   584       if (sp->modes & MODES_LOOPING) 
   585 	sp->modes |= MODES_SUSTAIN;
   586 
   587       /* Strip any loops and envelopes we're permitted to */
   588       if ((strip_loop==1) && 
   589 	  (sp->modes & (MODES_SUSTAIN | MODES_LOOPING | 
   590 			MODES_PINGPONG | MODES_REVERSE)))
   591 	{
   592 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain");
   593 	  sp->modes &=~(MODES_SUSTAIN | MODES_LOOPING | 
   594 			MODES_PINGPONG | MODES_REVERSE);
   595 	}
   596 
   597       if (strip_envelope==1)
   598 	{
   599 	  if (sp->modes & MODES_ENVELOPE)
   600 	    ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
   601 	  sp->modes &= ~MODES_ENVELOPE;
   602 	}
   603       else if (strip_envelope != 0)
   604 	{
   605 	  /* Have to make a guess. */
   606 	  if (!(sp->modes & (MODES_LOOPING | MODES_PINGPONG | MODES_REVERSE)))
   607 	    {
   608 	      /* No loop? Then what's there to sustain? No envelope needed
   609 		 either... */
   610 	      sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
   611 	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
   612 			" - No loop, removing sustain and envelope");
   613 	    }
   614 	  else if (!memcmp(tmp, "??????", 6) || tmp[11] >= 100) 
   615 	    {
   616 	      /* Envelope rates all maxed out? Envelope end at a high "offset"?
   617 		 That's a weird envelope. Take it out. */
   618 	      sp->modes &= ~MODES_ENVELOPE;
   619 	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
   620 			" - Weirdness, removing envelope");
   621 	    }
   622 	  else if (!(sp->modes & MODES_SUSTAIN))
   623 	    {
   624 	      /* No sustain? Then no envelope.  I don't know if this is
   625 		 justified, but patches without sustain usually don't need the
   626 		 envelope either... at least the Gravis ones. They're mostly
   627 		 drums.  I think. */
   628 	      sp->modes &= ~MODES_ENVELOPE;
   629 	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
   630 			" - No sustain, removing envelope");
   631 	    }
   632 	}
   633 
   634       sp->attenuation = 0;
   635 
   636       for (j=ATTACK; j<DELAY; j++)
   637 	{
   638 	  sp->envelope_rate[j]=
   639 	    (j<3)? convert_envelope_rate_attack(tmp[j], 11) : convert_envelope_rate(tmp[j]);
   640 	  sp->envelope_offset[j]= 
   641 	    convert_envelope_offset(tmp[6+j]);
   642 	}
   643       if (sf2flag)
   644 	{
   645 	  if (sf2delay > 5) sf2delay = 5;
   646 	  sp->envelope_rate[DELAY] = (int32)( (sf2delay*play_mode->rate) / 1000 );
   647 	}
   648       else
   649 	{
   650           sp->envelope_rate[DELAY]=0;
   651 	}
   652       sp->envelope_offset[DELAY]=0;
   653 
   654       for (j=ATTACK; j<DELAY; j++)
   655 	{
   656 	  sp->modulation_rate[j]=sp->envelope_rate[j];
   657 	  sp->modulation_offset[j]=sp->envelope_offset[j];
   658 	}
   659       sp->modulation_rate[DELAY] = sp->modulation_offset[DELAY] = 0;
   660       sp->modEnvToFilterFc=0;
   661       sp->modEnvToPitch=0;
   662       sp->lfo_sweep_increment = 0;
   663       sp->lfo_phase_increment = 0;
   664       sp->modLfoToFilterFc = 0;
   665       sp->vibrato_delay = 0;
   666 
   667       /* Then read the sample data */
   668       if (sp->data_length/2 > MAX_SAMPLE_SIZE)
   669         {
   670 	  goto fail;
   671 	}
   672       sp->data = safe_malloc(sp->data_length + 1);
   673       lp->size += sp->data_length + 1;
   674 
   675       if (1 != fread(sp->data, sp->data_length, 1, fp))
   676 	goto fail;
   677       
   678       if (!(sp->modes & MODES_16BIT)) /* convert to 16-bit data */
   679 	{
   680 	  int32 i=sp->data_length;
   681 	  uint8 *cp=(uint8 *)(sp->data);
   682 	  uint16 *tmp,*newdta;
   683 	  tmp=newdta=safe_malloc(sp->data_length*2 + 2);
   684 	  while (i--)
   685 	    *tmp++ = (uint16)(*cp++) << 8;
   686 	  cp=(uint8 *)(sp->data);
   687 	  sp->data = (sample_t *)newdta;
   688 	  free(cp);
   689 	  sp->data_length *= 2;
   690 	  sp->loop_start *= 2;
   691 	  sp->loop_end *= 2;
   692 	}
   693 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
   694       else
   695 	/* convert to machine byte order */
   696 	{
   697 	  int32 i=sp->data_length/2;
   698 	  int16 *tmp=(int16 *)sp->data,s;
   699 	  while (i--)
   700 	    { 
   701 	      s=LE_SHORT(*tmp);
   702 	      *tmp++=s;
   703 	    }
   704 	}
   705 #endif
   706       
   707       if (sp->modes & MODES_UNSIGNED) /* convert to signed data */
   708 	{
   709 	  int32 i=sp->data_length/2;
   710 	  int16 *tmp=(int16 *)sp->data;
   711 	  while (i--)
   712 	    *tmp++ ^= 0x8000;
   713 	}
   714 
   715       /* Reverse reverse loops and pass them off as normal loops */
   716       if (sp->modes & MODES_REVERSE)
   717 	{
   718 	  int32 t;
   719 	  /* The GUS apparently plays reverse loops by reversing the
   720 	     whole sample. We do the same because the GUS does not SUCK. */
   721 
   722 	  ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "Reverse loop in %s", name);
   723 	  reverse_data((int16 *)sp->data, 0, sp->data_length/2);
   724 
   725 	  t=sp->loop_start;
   726 	  sp->loop_start=sp->data_length - sp->loop_end;
   727 	  sp->loop_end=sp->data_length - t;
   728 
   729 	  sp->modes &= ~MODES_REVERSE;
   730 	  sp->modes |= MODES_LOOPING; /* just in case */
   731 	}
   732 
   733       /* If necessary do some anti-aliasing filtering  */
   734 
   735       if (antialiasing_allowed)
   736 	  antialiasing(sp,play_mode->rate);
   737 
   738 #ifdef ADJUST_SAMPLE_VOLUMES
   739       if (amp!=-1)
   740 	sp->volume=(FLOAT_T)((amp) / 100.0);
   741       else if (sf2flag)
   742 	sp->volume=(FLOAT_T)((sample_volume) / 255.0);
   743       else
   744 	{
   745 	  /* Try to determine a volume scaling factor for the sample.
   746 	     This is a very crude adjustment, but things sound more
   747 	     balanced with it. Still, this should be a runtime option. */
   748 	  uint32 i, numsamps=sp->data_length/2;
   749 	  uint32 higher=0, highcount=0;
   750 	  int16 maxamp=0,a;
   751 	  int16 *tmp=(int16 *)sp->data;
   752 	  i = numsamps;
   753 	  while (i--)
   754 	    {
   755 	      a=*tmp++;
   756 	      if (a<0) a=-a;
   757 	      if (a>maxamp)
   758 		maxamp=a;
   759 	    }
   760 	  tmp=(int16 *)sp->data;
   761 	  i = numsamps;
   762 	  while (i--)
   763 	    {
   764 	      a=*tmp++;
   765 	      if (a<0) a=-a;
   766 	      if (a > 3*maxamp/4)
   767 		{
   768 		   higher += a;
   769 		   highcount++;
   770 		}
   771 	    }
   772 	  if (highcount) higher /= highcount;
   773 	  else higher = 10000;
   774 	  sp->volume = (32768.0 * 0.875) /  (double)higher ;
   775 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * volume comp: %f", sp->volume);
   776 	}
   777 #else
   778       if (amp!=-1)
   779 	sp->volume=(double)(amp) / 100.0;
   780       else
   781 	sp->volume=1.0;
   782 #endif
   783 
   784       sp->data_length /= 2; /* These are in bytes. Convert into samples. */
   785 
   786       sp->loop_start /= 2;
   787       sp->loop_end /= 2;
   788       sp->data[sp->data_length] = sp->data[sp->data_length-1];
   789 
   790       /* Then fractional samples */
   791       sp->data_length <<= FRACTION_BITS;
   792       sp->loop_start <<= FRACTION_BITS;
   793       sp->loop_end <<= FRACTION_BITS;
   794 
   795     /* trim off zero data at end */
   796     {
   797 	int ls = sp->loop_start>>FRACTION_BITS;
   798 	int le = sp->loop_end>>FRACTION_BITS;
   799 	int se = sp->data_length>>FRACTION_BITS;
   800 	while (se > 1 && !sp->data[se-1]) se--;
   801 	if (le > se) le = se;
   802 	if (ls >= le) sp->modes &= ~MODES_LOOPING;
   803 	sp->loop_end = le<<FRACTION_BITS;
   804 	sp->data_length = se<<FRACTION_BITS;
   805     }
   806 
   807       /* Adjust for fractional loop points. This is a guess. Does anyone
   808 	 know what "fractions" really stands for? */
   809       sp->loop_start |=
   810 	(fractions & 0x0F) << (FRACTION_BITS-4);
   811       sp->loop_end |=
   812 	((fractions>>4) & 0x0F) << (FRACTION_BITS-4);
   813 
   814       /* If this instrument will always be played on the same note,
   815 	 and it's not looped, we can resample it now. */
   816       if (sp->note_to_use && !(sp->modes & MODES_LOOPING))
   817 	pre_resample(sp);
   818 
   819 #ifdef LOOKUP_HACK
   820       /* Squash the 16-bit data into 8 bits. */
   821       {
   822 	uint8 *gulp,*ulp;
   823 	int16 *swp;
   824 	int l=sp->data_length >> FRACTION_BITS;
   825 	gulp=ulp=safe_malloc(l+1);
   826 	swp=(int16 *)sp->data;
   827 	while(l--)
   828 	  *ulp++ = (*swp++ >> 8) & 0xFF;
   829 	free(sp->data);
   830 	sp->data=(sample_t *)gulp;
   831       }
   832 #endif
   833       
   834       if (strip_tail==1)
   835 	{
   836 	  /* Let's not really, just say we did. */
   837 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Stripping tail");
   838 	  sp->data_length = sp->loop_end;
   839 	}
   840     } /* end of sample loop */
   841  } /* end of stereo layer loop */
   842  } /* end of vlayer loop */
   843 
   844 
   845   close_file(fp);
   846   return headlp;
   847 }
   848 
   849 static int fill_bank(int dr, int b)
   850 {
   851   int i, errors=0;
   852   ToneBank *bank=((dr) ? drumset[b] : tonebank[b]);
   853   if (!bank)
   854     {
   855       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   856 	   "Huh. Tried to load instruments in non-existent %s %d",
   857 	   (dr) ? "drumset" : "tone bank", b);
   858       return 0;
   859     }
   860   for (i=0; i<MAXPROG; i++)
   861     {
   862       if (bank->tone[i].layer==MAGIC_LOAD_INSTRUMENT)
   863 	{
   864 	  if (!(bank->tone[i].name))
   865 	    {
   866 	      ctl->cmsg(CMSG_WARNING, (b!=0) ? VERB_VERBOSE : VERB_NORMAL,
   867 		   "No instrument mapped to %s %d, program %d%s",
   868 		   (dr)? "drum set" : "tone bank", b, i, 
   869 		   (b!=0) ? "" : " - this instrument will not be heard");
   870 	      if (b!=0)
   871 		{
   872 		  /* Mark the corresponding instrument in the default
   873 		     bank / drumset for loading (if it isn't already) */
   874 		  if (!dr)
   875 		    {
   876 		      if (!(standard_tonebank.tone[i].layer))
   877 			standard_tonebank.tone[i].layer=
   878 			  MAGIC_LOAD_INSTRUMENT;
   879 		    }
   880 		  else
   881 		    {
   882 		      if (!(standard_drumset.tone[i].layer))
   883 			standard_drumset.tone[i].layer=
   884 			  MAGIC_LOAD_INSTRUMENT;
   885 		    }
   886 		}
   887 	      bank->tone[i].layer=0;
   888 	      errors++;
   889 	    }
   890 	  else if (!(bank->tone[i].layer=
   891 		     load_instrument(bank->tone[i].name, 
   892 			     	     bank->tone[i].font_type,
   893 				     (dr) ? 1 : 0,
   894 				     bank->tone[i].pan,
   895 				     bank->tone[i].amp,
   896 				     bank->tone[i].tuning,
   897 				     (bank->tone[i].note!=-1) ? 
   898 				       bank->tone[i].note :
   899 				       ((dr) ? i : -1),
   900 				     (bank->tone[i].strip_loop!=-1) ?
   901 				     bank->tone[i].strip_loop :
   902 				     ((dr) ? 1 : -1),
   903 				     (bank->tone[i].strip_envelope != -1) ? 
   904 				     bank->tone[i].strip_envelope :
   905 				     ((dr) ? 1 : -1),
   906 				     bank->tone[i].strip_tail,
   907 				     b,
   908 				     ((dr) ? i + 128 : i),
   909 				     bank->tone[i].sf_ix
   910 			    			 )))
   911 	    {
   912 	      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   913 		   "Couldn't load instrument %s (%s %d, program %d)",
   914 		   bank->tone[i].name,
   915 		   (dr)? "drum set" : "tone bank", b, i);
   916 	      errors++;
   917 	    }
   918 	  else
   919 	    { /* it's loaded now */
   920 		bank->tone[i].last_used = current_tune_number;
   921 		current_patch_memory += bank->tone[i].layer->size;
   922 		purge_as_required();
   923 		if (current_patch_memory > max_patch_memory) {
   924 	      		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
   925 		   		"Not enough memory to load instrument %s (%s %d, program %d)",
   926 		   		bank->tone[i].name,
   927 		   		(dr)? "drum set" : "tone bank", b, i);
   928 	      		errors++;
   929 	    		free_layer(bank->tone[i].layer);
   930 	    		bank->tone[i].layer=0;
   931 	    		bank->tone[i].last_used=-1;
   932 		}
   933 #if 0
   934   	        if (check_for_rc()) {
   935 	    		free_layer(bank->tone[i].layer);
   936 	    		bank->tone[i].layer=0;
   937 	    		bank->tone[i].last_used=-1;
   938 			return 0;
   939 		}
   940 #endif
   941 	    }
   942 	}
   943     }
   944   return errors;
   945 }
   946 
   947 static void free_old_instruments(int how_old)
   948 {
   949   int i=MAXBANK;
   950   while(i--)
   951     {
   952       if (tonebank[i])
   953 	free_old_bank(0, i, how_old);
   954       if (drumset[i])
   955 	free_old_bank(1, i, how_old);
   956     }
   957 }
   958 
   959 static void purge_as_required(void)
   960 {
   961   if (!max_patch_memory) return;
   962 
   963   while (last_tune_purged < current_tune_number
   964 	&& current_patch_memory > max_patch_memory)
   965     {
   966 	last_tune_purged++;
   967 	free_old_instruments(last_tune_purged);
   968     }
   969 }
   970 
   971 
   972 int load_missing_instruments(void)
   973 {
   974   int i=MAXBANK,errors=0;
   975   while (i--)
   976     {
   977       if (tonebank[i])
   978 	errors+=fill_bank(0,i);
   979       if (drumset[i])
   980 	errors+=fill_bank(1,i);
   981     }
   982   current_tune_number++;
   983   return errors;
   984 }
   985 
   986 void free_instruments(void)
   987 {
   988   int i=128;
   989   while(i--)
   990     {
   991       if (tonebank[i])
   992 	free_bank(0,i);
   993       if (drumset[i])
   994 	free_bank(1,i);
   995     }
   996 }
   997 
   998 int set_default_instrument(const char *name)
   999 {
  1000   InstrumentLayer *lp;
  1001 /*  if (!(lp=load_instrument(name, 0, -1, -1, -1, 0, 0, 0))) */
  1002   if (!(lp=load_instrument(name, FONT_NORMAL, 0, -1, -1, 0, -1, -1, -1, -1, 0, -1, -1)))
  1003     return -1;
  1004   if (default_instrument)
  1005     free_layer(default_instrument);
  1006   default_instrument=lp;
  1007   default_program=SPECIAL_PROGRAM;
  1008   return 0;
  1009 }