src/codecs/timidity/readmidi.c
author Ozkan Sezer
Mon, 16 Dec 2019 10:33:55 +0300
changeset 1083 7a3b49dbf90f
parent 1069 8d8ebc200fd4
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 
    10 #if HAVE_CONFIG_H
    11 #  include <config.h>
    12 #endif
    13 
    14 #include <stdio.h>
    15 #include <stdlib.h>
    16 #include <string.h>
    17 
    18 #include "SDL.h"
    19 
    20 #include "options.h"
    21 #include "timidity.h"
    22 #include "common.h"
    23 #include "instrum.h"
    24 #include "playmidi.h"
    25 
    26 /* Computes how many (fractional) samples one MIDI delta-time unit contains */
    27 static void compute_sample_increment(MidiSong *song, Sint32 tempo,
    28 				     Sint32 divisions)
    29 {
    30   double a;
    31   a = (double) (tempo) * (double) (song->rate) * (65536.0/1000000.0) /
    32     (double)(divisions);
    33 
    34   song->sample_correction = (Sint32)(a) & 0xFFFF;
    35   song->sample_increment = (Sint32)(a) >> 16;
    36 
    37   SNDDBG(("Samples per delta-t: %d (correction %d)",
    38 	  song->sample_increment, song->sample_correction));
    39 }
    40 
    41 /* Read variable-length number (7 bits per byte, MSB first) */
    42 static Sint32 getvl(SDL_RWops *rw)
    43 {
    44   Sint32 l=0;
    45   Uint8 c;
    46   for (;;)
    47     {
    48       if (!SDL_RWread(rw, &c, 1, 1)) return l;
    49       l += (c & 0x7f);
    50       if (!(c & 0x80)) return l;
    51       l<<=7;
    52     }
    53 }
    54 
    55 #if 0 /* SNDDBG() is just an empty macro */
    56 /* Print a string from the file, followed by a newline. Any non-ASCII
    57    or unprintable characters will be converted to periods. */
    58 static int dumpstring(SDL_RWops *rw, Sint32 len, Uint8 type)
    59 {
    60   static char *label[]={
    61     "Text event: ", "Text: ", "Copyright: ", "Track name: ",
    62     "Instrument: ", "Lyric: ", "Marker: ", "Cue point: "};
    63   signed char *s=safe_malloc(len+1);
    64   if (len != (Sint32) SDL_RWread(rw, s, 1, len))
    65     {
    66       free(s);
    67       return -1;
    68     }
    69   s[len]='\0';
    70   while (len--)
    71     {
    72       if (s[len]<32)
    73 	s[len]='.';
    74     }
    75   SNDDBG(("%s%s", label[(type>7) ? 0 : type], s));
    76   free(s);
    77   return 0;
    78 }
    79 #else
    80 static SDL_INLINE int dumpstring(SDL_RWops *rw, Sint32 len, Uint8 type) {
    81   return SDL_RWseek(rw, len, RW_SEEK_CUR);
    82 }
    83 #endif
    84 
    85 #define MIDIEVENT(at,t,ch,pa,pb) \
    86   new=safe_malloc(sizeof(MidiEventList)); \
    87   new->event.time=at; new->event.type=t; new->event.channel=ch; \
    88   new->event.a=pa; new->event.b=pb; new->next=0;\
    89   return new;
    90 
    91 #define MAGIC_EOT ((MidiEventList *)(-1))
    92 
    93 /* Read a MIDI event, returning a freshly allocated element that can
    94    be linked to the event list */
    95 static MidiEventList *read_midi_event(MidiSong *song)
    96 {
    97   static Uint8 laststatus, lastchan;
    98   static Uint8 nrpn=0, rpn_msb[16], rpn_lsb[16]; /* one per channel */
    99   Uint8 me, type, a,b,c;
   100   Sint32 len;
   101   MidiEventList *new;
   102 
   103   for (;;)
   104     {
   105       song->at += getvl(song->rw);
   106       if (SDL_RWread(song->rw, &me, 1, 1) != 1)
   107 	{
   108 	  SNDDBG(("read_midi_event: SDL_RWread() failure\n"));
   109 	  return NULL;
   110 	}
   111       
   112       if(me==0xF0 || me == 0xF7) /* SysEx event */
   113 	{
   114 	  len=getvl(song->rw);
   115 	  SDL_RWseek(song->rw, len, RW_SEEK_CUR);
   116 	}
   117       else if(me==0xFF) /* Meta event */
   118 	{
   119 	  SDL_RWread(song->rw, &type, 1, 1);
   120 	  len=getvl(song->rw);
   121 	  if (type>0 && type<16)
   122 	    {
   123 	      dumpstring(song->rw, len, type);
   124 	    }
   125 	  else
   126 	    switch(type)
   127 	      {
   128 	      case 0x2F: /* End of Track */
   129 		return MAGIC_EOT;
   130 
   131 	      case 0x51: /* Tempo */
   132 		SDL_RWread(song->rw, &a, 1, 1);
   133 		SDL_RWread(song->rw, &b, 1, 1);
   134 		SDL_RWread(song->rw, &c, 1, 1);
   135 		MIDIEVENT(song->at, ME_TEMPO, c, a, b);
   136 		
   137 	      default:
   138 		SNDDBG(("(Meta event type 0x%02x, length %d)\n", type, len));
   139 		SDL_RWseek(song->rw, len, RW_SEEK_CUR);
   140 		break;
   141 	      }
   142 	}
   143       else
   144 	{
   145 	  a=me;
   146 	  if (a & 0x80) /* status byte */
   147 	    {
   148 	      lastchan=a & 0x0F;
   149 	      laststatus=(a>>4) & 0x07;
   150 	      SDL_RWread(song->rw, &a, 1, 1);
   151 	      a &= 0x7F;
   152 	    }
   153 	  switch(laststatus)
   154 	    {
   155 	    case 0: /* Note off */
   156 	      SDL_RWread(song->rw, &b, 1, 1);
   157 	      b &= 0x7F;
   158 	      MIDIEVENT(song->at, ME_NOTEOFF, lastchan, a,b);
   159 
   160 	    case 1: /* Note on */
   161 	      SDL_RWread(song->rw, &b, 1, 1);
   162 	      b &= 0x7F;
   163 	      MIDIEVENT(song->at, ME_NOTEON, lastchan, a,b);
   164 
   165 	    case 2: /* Key Pressure */
   166 	      SDL_RWread(song->rw, &b, 1, 1);
   167 	      b &= 0x7F;
   168 	      MIDIEVENT(song->at, ME_KEYPRESSURE, lastchan, a, b);
   169 
   170 	    case 3: /* Control change */
   171 	      SDL_RWread(song->rw, &b, 1, 1);
   172 	      b &= 0x7F;
   173 	      {
   174 		int control=255;
   175 		switch(a)
   176 		  {
   177 		  case 7: control=ME_MAINVOLUME; break;
   178 		  case 10: control=ME_PAN; break;
   179 		  case 11: control=ME_EXPRESSION; break;
   180 		  case 64: control=ME_SUSTAIN; b = (b >= 64); break;
   181 		  case 120: control=ME_ALL_SOUNDS_OFF; break;
   182 		  case 121: control=ME_RESET_CONTROLLERS; break;
   183 		  case 123: control=ME_ALL_NOTES_OFF; break;
   184 
   185 		    /* These should be the SCC-1 tone bank switch
   186 		       commands. I don't know why there are two, or
   187 		       why the latter only allows switching to bank 0.
   188 		       Also, some MIDI files use 0 as some sort of
   189 		       continuous controller. This will cause lots of
   190 		       warnings about undefined tone banks. */
   191 		  case 0: control=ME_TONE_BANK; break;
   192 		  case 32:
   193 		    if (b!=0) {
   194 		      SNDDBG(("(Strange: tone bank change 0x%02x)\n", b));
   195 		    }
   196 #if 0	/* `Bank Select LSB' is not worked at GS. Please ignore it. */
   197 		    else
   198 		      control=ME_TONE_BANK;
   199 #endif
   200 		    break;
   201 
   202 		  case 100: nrpn=0; rpn_msb[lastchan]=b; break;
   203 		  case 101: nrpn=0; rpn_lsb[lastchan]=b; break;
   204 		  case 99: nrpn=1; rpn_msb[lastchan]=b; break;
   205 		  case 98: nrpn=1; rpn_lsb[lastchan]=b; break;
   206 		    
   207 		  case 6:
   208 		    if (nrpn)
   209 		      {
   210 			SNDDBG(("(Data entry (MSB) for NRPN %02x,%02x: %d)\n",
   211 				rpn_msb[lastchan], rpn_lsb[lastchan], b));
   212 			break;
   213 		      }
   214 		    
   215 		    switch((rpn_msb[lastchan]<<8) | rpn_lsb[lastchan])
   216 		      {
   217 		      case 0x0000: /* Pitch bend sensitivity */
   218 			control=ME_PITCH_SENS;
   219 			break;
   220 
   221 		      case 0x7F7F: /* RPN reset */
   222 			/* reset pitch bend sensitivity to 2 */
   223 			MIDIEVENT(song->at, ME_PITCH_SENS, lastchan, 2, 0);
   224 
   225 		      default:
   226 			SNDDBG(("(Data entry (MSB) for RPN %02x,%02x: %d)\n",
   227 				rpn_msb[lastchan], rpn_lsb[lastchan], b));
   228 			break;
   229 		      }
   230 		    break;
   231 		    
   232 		  default:
   233 		    SNDDBG(("(Control %d: %d)\n", a, b));
   234 		    break;
   235 		  }
   236 		if (control != 255)
   237 		  { 
   238 		    MIDIEVENT(song->at, control, lastchan, b, 0); 
   239 		  }
   240 	      }
   241 	      break;
   242 
   243 	    case 4: /* Program change */
   244 	      a &= 0x7f;
   245 	      MIDIEVENT(song->at, ME_PROGRAM, lastchan, a, 0);
   246 
   247 	    case 5: /* Channel pressure - NOT IMPLEMENTED */
   248 	      break;
   249 
   250 	    case 6: /* Pitch wheel */
   251 	      SDL_RWread(song->rw, &b, 1, 1);
   252 	      b &= 0x7F;
   253 	      MIDIEVENT(song->at, ME_PITCHWHEEL, lastchan, a, b);
   254 
   255 	    default: 
   256 	      SNDDBG(("*** Can't happen: status 0x%02X, channel 0x%02X\n",
   257 		      laststatus, lastchan));
   258 	      break;
   259 	    }
   260 	}
   261     }
   262   
   263   return new;
   264 }
   265 
   266 #undef MIDIEVENT
   267 
   268 /* Read a midi track into the linked list, either merging with any previous
   269    tracks or appending to them. */
   270 static int read_track(MidiSong *song, int append)
   271 {
   272   MidiEventList *meep;
   273   MidiEventList *next, *new;
   274   Sint32 len;
   275   Sint64 next_pos, pos;
   276   char tmp[4];
   277 
   278   meep = song->evlist;
   279   if (append && meep)
   280     {
   281       /* find the last event in the list */
   282       for (; meep->next; meep=meep->next)
   283 	;
   284       song->at = meep->event.time;
   285     }
   286   else
   287     song->at=0;
   288 
   289   /* Check the formalities */
   290   
   291   if (SDL_RWread(song->rw, tmp, 1, 4) != 4 || SDL_RWread(song->rw, &len, 4, 1) != 1)
   292     {
   293       SNDDBG(("Can't read track header.\n"));
   294       return -1;
   295     }
   296   len=SDL_SwapBE32(len);
   297   next_pos = SDL_RWtell(song->rw) + len;
   298   if (memcmp(tmp, "MTrk", 4))
   299     {
   300       SNDDBG(("Corrupt MIDI file.\n"));
   301       return -2;
   302     }
   303 
   304   for (;;)
   305     {
   306       if (!(new=read_midi_event(song))) /* Some kind of error  */
   307 	return -2;
   308 
   309       if (new==MAGIC_EOT) /* End-of-track Hack. */
   310 	{
   311           pos = SDL_RWtell(song->rw);
   312           if (pos < next_pos)
   313             SDL_RWseek(song->rw, next_pos - pos, RW_SEEK_CUR);
   314 	  return 0;
   315 	}
   316 
   317       next=meep->next;
   318       while (next && (next->event.time < new->event.time))
   319 	{
   320 	  meep=next;
   321 	  next=meep->next;
   322 	}
   323 	  
   324       new->next=next;
   325       meep->next=new;
   326 
   327       song->event_count++; /* Count the event. (About one?) */
   328       meep=new;
   329     }
   330 }
   331 
   332 /* Free the linked event list from memory. */
   333 static void free_midi_list(MidiSong *song)
   334 {
   335   MidiEventList *meep, *next;
   336   if (!(meep = song->evlist)) return;
   337   while (meep)
   338     {
   339       next=meep->next;
   340       free(meep);
   341       meep=next;
   342     }
   343   song->evlist=NULL;
   344 }
   345 
   346 /* Allocate an array of MidiEvents and fill it from the linked list of
   347    events, marking used instruments for loading. Convert event times to
   348    samples: handle tempo changes. Strip unnecessary events from the list.
   349    Free the linked list. */
   350 static MidiEvent *groom_list(MidiSong *song, Sint32 divisions,Sint32 *eventsp,
   351 			     Sint32 *samplesp)
   352 {
   353   MidiEvent *groomed_list, *lp;
   354   MidiEventList *meep;
   355   Sint32 i, our_event_count, tempo, skip_this_event, new_value;
   356   Sint32 sample_cum, samples_to_do, at, st, dt, counting_time;
   357 
   358   int current_bank[MAXCHAN], current_set[MAXCHAN], current_program[MAXCHAN]; 
   359   /* Or should each bank have its own current program? */
   360 
   361   for (i=0; i<MAXCHAN; i++)
   362     {
   363       current_bank[i]=0;
   364       current_set[i]=0;
   365       current_program[i]=song->default_program;
   366     }
   367 
   368   tempo=500000;
   369   compute_sample_increment(song, tempo, divisions);
   370 
   371   /* This may allocate a bit more than we need */
   372   groomed_list=lp=safe_malloc(sizeof(MidiEvent) * (song->event_count+1));
   373   meep=song->evlist;
   374 
   375   our_event_count=0;
   376   st=at=sample_cum=0;
   377   counting_time=2; /* We strip any silence before the first NOTE ON. */
   378 
   379   for (i = 0; i < song->event_count; i++)
   380     {
   381       skip_this_event=0;
   382 
   383       if (meep->event.type==ME_TEMPO)
   384 	{
   385 	  skip_this_event=1;
   386 	}
   387       else if (meep->event.channel >= MAXCHAN)
   388         skip_this_event=1;
   389       else switch (meep->event.type)
   390 	{
   391 	case ME_PROGRAM:
   392 	  if (ISDRUMCHANNEL(song, meep->event.channel))
   393 	    {
   394 	      if (song->drumset[meep->event.a]) /* Is this a defined drumset? */
   395 		new_value=meep->event.a;
   396 	      else
   397 		{
   398 		  SNDDBG(("Drum set %d is undefined\n", meep->event.a));
   399 		  new_value=meep->event.a=0;
   400 		}
   401 	      if (current_set[meep->event.channel] != new_value)
   402 		current_set[meep->event.channel]=new_value;
   403 	      else 
   404 		skip_this_event=1;
   405 	    }
   406 	  else
   407 	    {
   408 	      new_value=meep->event.a;
   409 	      if ((current_program[meep->event.channel] != SPECIAL_PROGRAM)
   410 		  && (current_program[meep->event.channel] != new_value))
   411 		current_program[meep->event.channel] = new_value;
   412 	      else
   413 		skip_this_event=1;
   414 	    }
   415 	  break;
   416 
   417 	case ME_NOTEON:
   418 	  if (counting_time)
   419 	    counting_time=1;
   420 	  if (ISDRUMCHANNEL(song, meep->event.channel))
   421 	    {
   422 	      /* Mark this instrument to be loaded */
   423 	      if (!(song->drumset[current_set[meep->event.channel]]
   424 		    ->instrument[meep->event.a]))
   425 		song->drumset[current_set[meep->event.channel]]
   426 		  ->instrument[meep->event.a] = MAGIC_LOAD_INSTRUMENT;
   427 	    }
   428 	  else
   429 	    {
   430 	      if (current_program[meep->event.channel]==SPECIAL_PROGRAM)
   431 		break;
   432 	      /* Mark this instrument to be loaded */
   433 	      if (!(song->tonebank[current_bank[meep->event.channel]]
   434 		    ->instrument[current_program[meep->event.channel]]))
   435 		song->tonebank[current_bank[meep->event.channel]]
   436 		  ->instrument[current_program[meep->event.channel]] =
   437 		    MAGIC_LOAD_INSTRUMENT;
   438 	    }
   439 	  break;
   440 
   441 	case ME_TONE_BANK:
   442 	  if (ISDRUMCHANNEL(song, meep->event.channel))
   443 	    {
   444 	      skip_this_event=1;
   445 	      break;
   446 	    }
   447 	  if (song->tonebank[meep->event.a]) /* Is this a defined tone bank? */
   448 	    new_value=meep->event.a;
   449 	  else 
   450 	    {
   451 	      SNDDBG(("Tone bank %d is undefined\n", meep->event.a));
   452 	      new_value=meep->event.a=0;
   453 	    }
   454 	  if (current_bank[meep->event.channel]!=new_value)
   455 	    current_bank[meep->event.channel]=new_value;
   456 	  else
   457 	    skip_this_event=1;
   458 	  break;
   459 	}
   460 
   461       /* Recompute time in samples*/
   462       if ((dt=meep->event.time - at) && !counting_time)
   463 	{
   464 	  if (song->sample_increment  > 2147483647/dt ||
   465 	      song->sample_correction > 2147483647/dt) {
   466 	      goto _overflow;
   467 	    }
   468 	  samples_to_do = song->sample_increment * dt;
   469 	  sample_cum += song->sample_correction * dt;
   470 	  if (sample_cum & 0xFFFF0000)
   471 	    {
   472 	      samples_to_do += ((sample_cum >> 16) & 0xFFFF);
   473 	      sample_cum &= 0x0000FFFF;
   474 	    }
   475 	  if (st >= 2147483647 - samples_to_do) {
   476 	  _overflow:
   477 	      SNDDBG(("Overflow in sample counter\n"));
   478 	      free_midi_list(song);
   479 	      free(groomed_list);
   480 	      return NULL;
   481 	    }
   482 	  st += samples_to_do;
   483 	}
   484       else if (counting_time==1) counting_time=0;
   485       if (meep->event.type==ME_TEMPO)
   486 	{
   487 	  tempo=
   488 	    meep->event.channel + meep->event.b * 256 + meep->event.a * 65536;
   489 	  compute_sample_increment(song, tempo, divisions);
   490 	}
   491       if (!skip_this_event)
   492 	{
   493 	  /* Add the event to the list */
   494 	  *lp=meep->event;
   495 	  lp->time=st;
   496 	  lp++;
   497 	  our_event_count++;
   498 	}
   499       at=meep->event.time;
   500       meep=meep->next;
   501     }
   502   /* Add an End-of-Track event */
   503   lp->time=st;
   504   lp->type=ME_EOT;
   505   our_event_count++;
   506   free_midi_list(song);
   507 
   508   *eventsp=our_event_count;
   509   *samplesp=st;
   510   return groomed_list;
   511 }
   512 
   513 MidiEvent *read_midi_file(MidiSong *song, Sint32 *count, Sint32 *sp)
   514 {
   515   Sint32 len, divisions;
   516   Sint16 format, tracks, divisions_tmp;
   517   int i;
   518   char tmp[4];
   519 
   520   song->event_count=0;
   521   song->at=0;
   522   song->evlist = NULL;
   523 
   524   if (SDL_RWread(song->rw, tmp, 1, 4) != 4 || SDL_RWread(song->rw, &len, 4, 1) != 1)
   525     {
   526       SNDDBG(("Not a MIDI file!\n"));
   527       return NULL;
   528     }
   529   if (memcmp(tmp, "RIFF", 4) == 0) { /* RMID ?? */
   530     if (SDL_RWread(song->rw, tmp, 1, 4) != 4 || memcmp(tmp, "RMID", 4) != 0 ||
   531 	SDL_RWread(song->rw, tmp, 1, 4) != 4 || memcmp(tmp, "data", 4) != 0 ||
   532 	SDL_RWread(song->rw, tmp, 1, 4) != 4 ||
   533 	/* SMF must begin from here onwards: */
   534 	SDL_RWread(song->rw, tmp, 1, 4) != 4 || SDL_RWread(song->rw, &len, 4, 1) != 1)
   535       {
   536 	SNDDBG(("Not an RMID file!\n"));
   537 	return NULL;
   538       }
   539   }
   540   len=(Sint32)SDL_SwapBE32((Uint32)len);
   541   if (memcmp(tmp, "MThd", 4) || len < 6)
   542     {
   543       SNDDBG(("Not a MIDI file!\n"));
   544       return NULL;
   545     }
   546 
   547   SDL_RWread(song->rw, &format, 2, 1);
   548   SDL_RWread(song->rw, &tracks, 2, 1);
   549   SDL_RWread(song->rw, &divisions_tmp, 2, 1);
   550   format=SDL_SwapBE16(format);
   551   tracks=SDL_SwapBE16(tracks);
   552   divisions_tmp=SDL_SwapBE16(divisions_tmp);
   553 
   554   if (divisions_tmp<0)
   555     {
   556       /* SMPTE time -- totally untested. Got a MIDI file that uses this? */
   557       divisions=
   558 	(Sint32)(-(divisions_tmp/256)) * (Sint32)(divisions_tmp & 0xFF);
   559     }
   560   else divisions=(Sint32)(divisions_tmp);
   561 
   562   if (len > 6)
   563     {
   564       SNDDBG(("MIDI file header size %u bytes", len));
   565       SDL_RWseek(song->rw, len-6, RW_SEEK_CUR); /* skip the excess */
   566     }
   567   if (format<0 || format >2)
   568     {
   569       SNDDBG(("Unknown MIDI file format %d\n", format));
   570       return NULL;
   571     }
   572   if (tracks<1)
   573     {
   574       SNDDBG(("Bad number of tracks %d\n", tracks));
   575       return NULL;
   576     }
   577   if (format==0 && tracks!=1)
   578     {
   579       SNDDBG(("%d tracks with Type-0 MIDI (must be 1.)\n", tracks));
   580       return NULL;
   581     }
   582   SNDDBG(("Format: %d  Tracks: %d  Divisions: %d\n",
   583 	  format, tracks, divisions));
   584 
   585   /* Put a do-nothing event first in the list for easier processing */
   586   song->evlist=safe_malloc(sizeof(MidiEventList));
   587   memset(song->evlist, 0, sizeof(MidiEventList));
   588   song->event_count++;
   589 
   590   switch(format)
   591     {
   592     case 0:
   593       if (read_track(song, 0))
   594 	{
   595 	  free_midi_list(song);
   596 	  return NULL;
   597 	}
   598       break;
   599 
   600     case 1:
   601       for (i=0; i<tracks; i++)
   602 	if (read_track(song, 0))
   603 	  {
   604 	    free_midi_list(song);
   605 	    return NULL;
   606 	  }
   607       break;
   608 
   609     case 2: /* We simply play the tracks sequentially */
   610       for (i=0; i<tracks; i++)
   611 	if (read_track(song, 1))
   612 	  {
   613 	    free_midi_list(song);
   614 	    return NULL;
   615 	  }
   616       break;
   617     }
   618 
   619   return groom_list(song, divisions, count, sp);
   620 }