src/codecs/timidity/instrum.c
author Ozkan Sezer
Mon, 16 Dec 2019 10:33:55 +0300
changeset 1083 7a3b49dbf90f
parent 999 1a87fe70802d
child 1084 c7cedfb5f65f
permissions -rw-r--r--
timidity: minor warning fixes

based on a patch by Wohlstand
     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 Perl Artistic License, available in COPYING.
     8 
     9    instrum.c 
    10    
    11    Code to load and unload GUS-compatible instrument patches.
    12 
    13 */
    14 
    15 #if HAVE_CONFIG_H
    16 #  include <config.h>
    17 #endif
    18 
    19 #include <stdio.h>
    20 #include <string.h>
    21 #include <stdlib.h>
    22 
    23 #include "SDL.h"
    24 
    25 #include "timidity.h"
    26 #include "options.h"
    27 #include "common.h"
    28 #include "instrum.h"
    29 #include "resample.h"
    30 #include "tables.h"
    31 
    32 static void free_instrument(Instrument *ip)
    33 {
    34   Sample *sp;
    35   int i;
    36   if (!ip) return;
    37   for (i=0; i<ip->samples; i++)
    38     {
    39       sp=&(ip->sample[i]);
    40       free(sp->data);
    41     }
    42   free(ip->sample);
    43   free(ip);
    44 }
    45 
    46 static void free_bank(MidiSong *song, int dr, int b)
    47 {
    48   int i;
    49   ToneBank *bank=((dr) ? song->drumset[b] : song->tonebank[b]);
    50   for (i=0; i<MAXBANK; i++)
    51     if (bank->instrument[i])
    52       {
    53 	/* Not that this could ever happen, of course */
    54 	if (bank->instrument[i] != MAGIC_LOAD_INSTRUMENT)
    55 	  free_instrument(bank->instrument[i]);
    56 	bank->instrument[i]=0;
    57       }
    58 }
    59 
    60 static Sint32 convert_envelope_rate(MidiSong *song, Uint8 rate)
    61 {
    62   Sint32 r;
    63   
    64   r = 3 - ((rate >> 6) & 0x3);
    65   r *= 3;
    66   r = (Sint32) (rate & 0x3f) << r; /* 6.9 fixed point */
    67 
    68   /* 15.15 fixed point. */
    69   r = ((r * 44100) / song->rate) * song->control_ratio;
    70 
    71 #ifdef FAST_DECAY
    72   return r << 10;
    73 #else
    74   return r << 9;
    75 #endif
    76 }
    77 
    78 static Sint32 convert_envelope_offset(Uint8 offset)
    79 {
    80   /* This is not too good... Can anyone tell me what these values mean?
    81      Are they GUS-style "exponential" volumes? And what does that mean? */
    82 
    83   /* 15.15 fixed point */
    84   return offset << (7+15);
    85 }
    86 
    87 static Sint32 convert_tremolo_sweep(MidiSong *song, Uint8 sweep)
    88 {
    89   if (!sweep)
    90     return 0;
    91 
    92   return
    93     ((song->control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
    94       (song->rate * sweep);
    95 }
    96 
    97 static Sint32 convert_vibrato_sweep(MidiSong *song, Uint8 sweep,
    98 				    Sint32 vib_control_ratio)
    99 {
   100   if (!sweep)
   101     return 0;
   102 
   103   return
   104     (Sint32) (FSCALE((double) (vib_control_ratio) * SWEEP_TUNING, SWEEP_SHIFT)
   105 	     / (double)(song->rate * sweep));
   106 
   107   /* this was overflowing with seashore.pat
   108 
   109       ((vib_control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
   110       (song->rate * sweep); */
   111 }
   112 
   113 static Sint32 convert_tremolo_rate(MidiSong *song, Uint8 rate)
   114 {
   115   return
   116     ((SINE_CYCLE_LENGTH * song->control_ratio * rate) << RATE_SHIFT) /
   117       (TREMOLO_RATE_TUNING * song->rate);
   118 }
   119 
   120 static Sint32 convert_vibrato_rate(MidiSong *song, Uint8 rate)
   121 {
   122   /* Return a suitable vibrato_control_ratio value */
   123   return
   124     (VIBRATO_RATE_TUNING * song->rate) / 
   125       (rate * 2 * VIBRATO_SAMPLE_INCREMENTS);
   126 }
   127 
   128 static void reverse_data(Sint16 *sp, Sint32 ls, Sint32 le)
   129 {
   130   Sint16 s, *ep=sp+le;
   131   sp+=ls;
   132   le-=ls;
   133   le/=2;
   134   while (le--)
   135     {
   136       s=*sp;
   137       *sp++=*ep;
   138       *ep--=s;
   139     }
   140 }
   141 
   142 /* 
   143    If panning or note_to_use != -1, it will be used for all samples,
   144    instead of the sample-specific values in the instrument file. 
   145 
   146    For note_to_use, any value <0 or >127 will be forced to 0.
   147  
   148    For other parameters, 1 means yes, 0 means no, other values are
   149    undefined.
   150 
   151    TODO: do reverse loops right */
   152 static Instrument *load_instrument(MidiSong *song, char *name, int percussion,
   153 				   int panning, int amp, int note_to_use,
   154 				   int strip_loop, int strip_envelope,
   155 				   int strip_tail)
   156 {
   157   Instrument *ip;
   158   Sample *sp;
   159   SDL_RWops *rw;
   160   char tmp[1024];
   161   int i,j,noluck=0;
   162   static char *patch_ext[] = PATCH_EXT_LIST;
   163   (void)percussion; /* unused */
   164 
   165   if (!name) return 0;
   166   
   167   /* Open patch file */
   168   if ((rw=open_file(name)) == NULL)
   169     {
   170       noluck=1;
   171       /* Try with various extensions */
   172       for (i=0; patch_ext[i]; i++)
   173 	{
   174 	  if (strlen(name)+strlen(patch_ext[i])<1024)
   175 	    {
   176 	      strcpy(tmp, name);
   177 	      strcat(tmp, patch_ext[i]);
   178 	      if ((rw=open_file(tmp)) != NULL)
   179 		{
   180 		  noluck=0;
   181 		  break;
   182 		}
   183 	    }
   184 	}
   185     }
   186   
   187   if (noluck)
   188     {
   189       SNDDBG(("Instrument `%s' can't be found.\n", name));
   190       return 0;
   191     }
   192       
   193   SNDDBG(("Loading instrument %s\n", tmp));
   194   
   195   /* Read some headers and do cursory sanity checks. There are loads
   196      of magic offsets. This could be rewritten... */
   197 
   198   if ((239 != SDL_RWread(rw, tmp, 1, 239)) ||
   199       (memcmp(tmp, "GF1PATCH110\0ID#000002", 22) &&
   200        memcmp(tmp, "GF1PATCH100\0ID#000002", 22))) /* don't know what the
   201 						      differences are */
   202     {
   203       SNDDBG(("%s: not an instrument\n", name));
   204       SDL_RWclose(rw);
   205       return 0;
   206     }
   207   
   208   if (tmp[82] != 1 && tmp[82] != 0) /* instruments. To some patch makers, 
   209 				       0 means 1 */
   210     {
   211       SNDDBG(("Can't handle patches with %d instruments\n", tmp[82]));
   212       SDL_RWclose(rw);
   213       return 0;
   214     }
   215 
   216   if (tmp[151] != 1 && tmp[151] != 0) /* layers. What's a layer? */
   217     {
   218       SNDDBG(("Can't handle instruments with %d layers\n", tmp[151]));
   219       SDL_RWclose(rw);
   220       return 0;
   221     }
   222   
   223   ip=safe_malloc(sizeof(Instrument));
   224   ip->samples = tmp[198];
   225   ip->sample = safe_malloc(sizeof(Sample) * ip->samples);
   226   for (i=0; i<ip->samples; i++)
   227     {
   228 
   229       Uint8 fractions;
   230       Sint32 tmplong;
   231       Uint16 tmpshort;
   232       Uint8 tmpchar;
   233 
   234 #define READ_CHAR(thing) \
   235       if (1 != SDL_RWread(rw, &tmpchar, 1, 1)) goto fail; \
   236       thing = tmpchar;
   237 #define READ_SHORT(thing) \
   238       if (1 != SDL_RWread(rw, &tmpshort, 2, 1)) goto fail; \
   239       thing = SDL_SwapLE16(tmpshort);
   240 #define READ_LONG(thing) \
   241       if (1 != SDL_RWread(rw, &tmplong, 4, 1)) goto fail; \
   242       thing = SDL_SwapLE32(tmplong);
   243 
   244       SDL_RWseek(rw, 7, RW_SEEK_CUR); /* Skip the wave name */
   245 
   246       if (1 != SDL_RWread(rw, &fractions, 1, 1))
   247 	{
   248 	fail:
   249 	  SNDDBG(("Error reading sample %d\n", i));
   250 	  for (j=0; j<i; j++)
   251 	    free(ip->sample[j].data);
   252 	  free(ip->sample);
   253 	  free(ip);
   254 	  SDL_RWclose(rw);
   255 	  return 0;
   256 	}
   257 
   258       sp=&(ip->sample[i]);
   259       
   260       READ_LONG(sp->data_length);
   261       READ_LONG(sp->loop_start);
   262       READ_LONG(sp->loop_end);
   263       READ_SHORT(sp->sample_rate);
   264       READ_LONG(sp->low_freq);
   265       READ_LONG(sp->high_freq);
   266       READ_LONG(sp->root_freq);
   267       SDL_RWseek(rw, 2, RW_SEEK_CUR); /* Why have a "root frequency" and then
   268 				    * "tuning"?? */
   269       
   270       READ_CHAR(tmp[0]);
   271 
   272       if (panning==-1)
   273 	sp->panning = (tmp[0] * 8 + 4) & 0x7f;
   274       else
   275 	sp->panning=(Uint8)(panning & 0x7F);
   276 
   277       /* envelope, tremolo, and vibrato */
   278       if (18 != SDL_RWread(rw, tmp, 1, 18)) goto fail; 
   279 
   280       if (!tmp[13] || !tmp[14])
   281 	{
   282 	  sp->tremolo_sweep_increment=
   283 	    sp->tremolo_phase_increment=sp->tremolo_depth=0;
   284 	  SNDDBG((" * no tremolo\n"));
   285 	}
   286       else
   287 	{
   288 	  sp->tremolo_sweep_increment=convert_tremolo_sweep(song, tmp[12]);
   289 	  sp->tremolo_phase_increment=convert_tremolo_rate(song, tmp[13]);
   290 	  sp->tremolo_depth=tmp[14];
   291 	  SNDDBG((" * tremolo: sweep %d, phase %d, depth %d\n",
   292 	       sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
   293 	       sp->tremolo_depth));
   294 	}
   295 
   296       if (!tmp[16] || !tmp[17])
   297 	{
   298 	  sp->vibrato_sweep_increment=
   299 	    sp->vibrato_control_ratio=sp->vibrato_depth=0;
   300 	  SNDDBG((" * no vibrato\n"));
   301 	}
   302       else
   303 	{
   304 	  sp->vibrato_control_ratio=convert_vibrato_rate(song, tmp[16]);
   305 	  sp->vibrato_sweep_increment=
   306 	    convert_vibrato_sweep(song, tmp[15], sp->vibrato_control_ratio);
   307 	  sp->vibrato_depth=tmp[17];
   308 	  SNDDBG((" * vibrato: sweep %d, ctl %d, depth %d\n",
   309 	       sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
   310 	       sp->vibrato_depth));
   311 
   312 	}
   313 
   314       READ_CHAR(sp->modes);
   315 
   316       SDL_RWseek(rw, 40, RW_SEEK_CUR); /* skip the useless scale frequency, scale
   317 				       factor (what's it mean?), and reserved
   318 				       space */
   319 
   320       /* Mark this as a fixed-pitch instrument if such a deed is desired. */
   321       if (note_to_use!=-1)
   322 	sp->note_to_use=(Uint8)(note_to_use);
   323       else
   324 	sp->note_to_use=0;
   325       
   326       /* seashore.pat in the Midia patch set has no Sustain. I don't
   327          understand why, and fixing it by adding the Sustain flag to
   328          all looped patches probably breaks something else. We do it
   329          anyway. */
   330 	 
   331       if (sp->modes & MODES_LOOPING) 
   332 	sp->modes |= MODES_SUSTAIN;
   333 
   334       /* Strip any loops and envelopes we're permitted to */
   335       if ((strip_loop==1) && 
   336 	  (sp->modes & (MODES_SUSTAIN | MODES_LOOPING | 
   337 			MODES_PINGPONG | MODES_REVERSE)))
   338 	{
   339 	  SNDDBG((" - Removing loop and/or sustain\n"));
   340 	  sp->modes &=~(MODES_SUSTAIN | MODES_LOOPING | 
   341 			MODES_PINGPONG | MODES_REVERSE);
   342 	}
   343 
   344       if (strip_envelope==1)
   345 	{
   346 	  if (sp->modes & MODES_ENVELOPE) {
   347 	    SNDDBG((" - Removing envelope\n"));
   348 	  }
   349 	  sp->modes &= ~MODES_ENVELOPE;
   350 	}
   351       else if (strip_envelope != 0)
   352 	{
   353 	  /* Have to make a guess. */
   354 	  if (!(sp->modes & (MODES_LOOPING | MODES_PINGPONG | MODES_REVERSE)))
   355 	    {
   356 	      /* No loop? Then what's there to sustain? No envelope needed
   357 		 either... */
   358 	      sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
   359 	      SNDDBG((" - No loop, removing sustain and envelope\n"));
   360 	    }
   361 	  else if (!memcmp(tmp, "??????", 6) || tmp[11] >= 100) 
   362 	    {
   363 	      /* Envelope rates all maxed out? Envelope end at a high "offset"?
   364 		 That's a weird envelope. Take it out. */
   365 	      sp->modes &= ~MODES_ENVELOPE;
   366 	      SNDDBG((" - Weirdness, removing envelope\n"));
   367 	    }
   368 	  else if (!(sp->modes & MODES_SUSTAIN))
   369 	    {
   370 	      /* No sustain? Then no envelope.  I don't know if this is
   371 		 justified, but patches without sustain usually don't need the
   372 		 envelope either... at least the Gravis ones. They're mostly
   373 		 drums.  I think. */
   374 	      sp->modes &= ~MODES_ENVELOPE;
   375 	      SNDDBG((" - No sustain, removing envelope\n"));
   376 	    }
   377 	}
   378 
   379       for (j=0; j<6; j++)
   380 	{
   381 	  sp->envelope_rate[j]=
   382 	    convert_envelope_rate(song, tmp[j]);
   383 	  sp->envelope_offset[j]= 
   384 	    convert_envelope_offset(tmp[6+j]);
   385 	}
   386 
   387       /* Then read the sample data */
   388       sp->data = (sample_t *) safe_malloc(sp->data_length+4);
   389       if (1 != SDL_RWread(rw, sp->data, sp->data_length, 1))
   390 	goto fail;
   391       
   392       if (!(sp->modes & MODES_16BIT)) /* convert to 16-bit data */
   393 	{
   394 	  Sint32 k=sp->data_length;
   395 	  Uint8 *cp=(Uint8 *)(sp->data);
   396 	  Uint16 *tmp16,*new16;
   397 	  sp->data_length *= 2;
   398 	  sp->loop_start *= 2;
   399 	  sp->loop_end *= 2;
   400 	  tmp16 = new16 = (Uint16 *) safe_malloc(sp->data_length+4);
   401 	  while (k--)
   402 	    *tmp16++ = (Uint16)(*cp++) << 8;
   403 	  free(sp->data);
   404 	  sp->data = (sample_t *)new16;
   405 	}
   406 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
   407       else
   408 	/* convert to machine byte order */
   409 	{
   410 	  Sint32 k=sp->data_length/2;
   411 	  Sint16 *tmp16=(Sint16 *)sp->data,s;
   412 	  while (k--)
   413 	    {
   414 	      s=SDL_SwapLE16(*tmp16);
   415 	      *tmp16++=s;
   416 	    }
   417 	}
   418 #endif
   419       
   420       if (sp->modes & MODES_UNSIGNED) /* convert to signed data */
   421 	{
   422 	  Sint32 k=sp->data_length/2;
   423 	  Sint16 *tmp16=(Sint16 *)sp->data;
   424 	  while (k--)
   425 	    *tmp16++ ^= 0x8000;
   426 	}
   427 
   428       /* Reverse reverse loops and pass them off as normal loops */
   429       if (sp->modes & MODES_REVERSE)
   430 	{
   431 	  Sint32 t;
   432 	  /* The GUS apparently plays reverse loops by reversing the
   433 	     whole sample. We do the same because the GUS does not SUCK. */
   434 
   435 	  SNDDBG(("Reverse loop in %s\n", name));
   436 	  reverse_data((Sint16 *)sp->data, 0, sp->data_length/2);
   437 
   438 	  t=sp->loop_start;
   439 	  sp->loop_start=sp->data_length - sp->loop_end;
   440 	  sp->loop_end=sp->data_length - t;
   441 
   442 	  sp->modes &= ~MODES_REVERSE;
   443 	  sp->modes |= MODES_LOOPING; /* just in case */
   444 	}
   445 
   446 #ifdef ADJUST_SAMPLE_VOLUMES
   447       if (amp!=-1)
   448 	sp->volume=(float)((amp) / 100.0);
   449       else
   450 	{
   451 	  /* Try to determine a volume scaling factor for the sample.
   452 	     This is a very crude adjustment, but things sound more
   453 	     balanced with it. Still, this should be a runtime option. */
   454 	  Sint32 k=sp->data_length/2;
   455 	  Sint16 maxamp=0,a;
   456 	  Sint16 *tmp16=(Sint16 *)sp->data;
   457 	  while (k--)
   458 	    {
   459 	      a=*tmp16++;
   460 	      if (a<0) a=-a;
   461 	      if (a>maxamp)
   462 		maxamp=a;
   463 	    }
   464 	  sp->volume=(float)(32768.0 / maxamp);
   465 	  SNDDBG((" * volume comp: %f\n", sp->volume));
   466 	}
   467 #else
   468       if (amp!=-1)
   469 	sp->volume=(double)(amp) / 100.0;
   470       else
   471 	sp->volume=1.0;
   472 #endif
   473 
   474       sp->data_length /= 2; /* These are in bytes. Convert into samples. */
   475       sp->loop_start /= 2;
   476       sp->loop_end /= 2;
   477 
   478       /* initialize the added extra sample space (see the +4 bytes in
   479 	 allocation) using the last actual sample:  */
   480       sp->data[sp->data_length] = sp->data[sp->data_length+1] = 0;
   481 
   482       /* Then fractional samples */
   483       sp->data_length <<= FRACTION_BITS;
   484       sp->loop_start <<= FRACTION_BITS;
   485       sp->loop_end <<= FRACTION_BITS;
   486 
   487       /* Adjust for fractional loop points. This is a guess. Does anyone
   488 	 know what "fractions" really stands for? */
   489       sp->loop_start |=
   490 	(fractions & 0x0F) << (FRACTION_BITS-4);
   491       sp->loop_end |=
   492 	((fractions>>4) & 0x0F) << (FRACTION_BITS-4);
   493 
   494       /* If this instrument will always be played on the same note,
   495 	 and it's not looped, we can resample it now. */
   496       if (sp->note_to_use && !(sp->modes & MODES_LOOPING))
   497 	pre_resample(song, sp);
   498 
   499       if (strip_tail==1)
   500 	{
   501 	  /* Let's not really, just say we did. */
   502 	  SNDDBG((" - Stripping tail\n"));
   503 	  sp->data_length = sp->loop_end;
   504 	}
   505     }
   506 
   507   SDL_RWclose(rw);
   508   return ip;
   509 }
   510 
   511 static int fill_bank(MidiSong *song, int dr, int b)
   512 {
   513   int i, errors=0;
   514   ToneBank *bank=((dr) ? song->drumset[b] : song->tonebank[b]);
   515   if (!bank)
   516     {
   517       SNDDBG(("Huh. Tried to load instruments in non-existent %s %d\n",
   518 	   (dr) ? "drumset" : "tone bank", b));
   519       return 0;
   520     }
   521   for (i=0; i<MAXBANK; i++)
   522     {
   523       if (bank->instrument[i]==MAGIC_LOAD_INSTRUMENT)
   524 	{
   525 	  if (!(bank->tone[i].name))
   526 	    {
   527 	      SNDDBG(("No instrument mapped to %s %d, program %d%s\n",
   528 		   (dr)? "drum set" : "tone bank", b, i, 
   529 		   (b!=0) ? "" : " - this instrument will not be heard"));
   530 	      if (b!=0)
   531 		{
   532 		  /* Mark the corresponding instrument in the default
   533 		     bank / drumset for loading (if it isn't already) */
   534 		  if (!dr)
   535 		    {
   536 		      if (!(song->tonebank[0]->instrument[i]))
   537 			song->tonebank[0]->instrument[i] =
   538 			  MAGIC_LOAD_INSTRUMENT;
   539 		    }
   540 		  else
   541 		    {
   542 		      if (!(song->drumset[0]->instrument[i]))
   543 			song->drumset[0]->instrument[i] =
   544 			  MAGIC_LOAD_INSTRUMENT;
   545 		    }
   546 		}
   547 	      bank->instrument[i] = 0;
   548 	      errors++;
   549 	    }
   550 	  else if (!(bank->instrument[i] =
   551 		     load_instrument(song,
   552 				     bank->tone[i].name, 
   553 				     (dr) ? 1 : 0,
   554 				     bank->tone[i].pan,
   555 				     bank->tone[i].amp,
   556 				     (bank->tone[i].note!=-1) ? 
   557 				     bank->tone[i].note :
   558 				     ((dr) ? i : -1),
   559 				     (bank->tone[i].strip_loop!=-1) ?
   560 				     bank->tone[i].strip_loop :
   561 				     ((dr) ? 1 : -1),
   562 				     (bank->tone[i].strip_envelope != -1) ? 
   563 				     bank->tone[i].strip_envelope :
   564 				     ((dr) ? 1 : -1),
   565 				     bank->tone[i].strip_tail )))
   566 	    {
   567 	      SNDDBG(("Couldn't load instrument %s (%s %d, program %d)\n",
   568 		   bank->tone[i].name,
   569 		   (dr)? "drum set" : "tone bank", b, i));
   570 	      errors++;
   571 	    }
   572 	}
   573     }
   574   return errors;
   575 }
   576 
   577 int load_missing_instruments(MidiSong *song)
   578 {
   579   int i=MAXBANK,errors=0;
   580   while (i--)
   581     {
   582       if (song->tonebank[i])
   583 	errors+=fill_bank(song,0,i);
   584       if (song->drumset[i])
   585 	errors+=fill_bank(song,1,i);
   586     }
   587   return errors;
   588 }
   589 
   590 void free_instruments(MidiSong *song)
   591 {
   592   int i=MAXBANK;
   593   while(i--)
   594     {
   595       if (song->tonebank[i])
   596 	free_bank(song, 0, i);
   597       if (song->drumset[i])
   598 	free_bank(song, 1, i);
   599     }
   600 }
   601 
   602 int set_default_instrument(MidiSong *song, char *name)
   603 {
   604   Instrument *ip;
   605   if (!(ip=load_instrument(song, name, 0, -1, -1, -1, 0, 0, 0)))
   606     return -1;
   607   song->default_instrument = ip;
   608   song->default_program = SPECIAL_PROGRAM;
   609   return 0;
   610 }