DOOM-3-BFG

DOOM 3 BFG Edition
Log | Files | Refs

readmidi.cpp (18410B)


      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 #include "../../neo/idlib/precompiled.h"
     23 
     24 #include <stdio.h>
     25 #include <stdlib.h>
     26 #include <errno.h>
     27 #include <string.h>
     28 
     29 #include "config.h"
     30 #include "common.h"
     31 #include "instrum.h"
     32 #include "playmidi.h"
     33 #include "readmidi.h"
     34 #include "output.h"
     35 #include "controls.h"
     36 
     37 
     38 void Real_Tim_Free( void *pt );
     39 
     40  int32_t quietchannels=0;
     41 
     42 /* to avoid some unnecessary parameter passing */
     43 static MidiEventList *evlist;
     44 static  int32_t event_count;
     45 static idFile * fp = NULL;
     46 static  int32_t at;
     47 static unsigned char* local_buffer = 0;
     48 static size_t local_buffer_length = 0;
     49 static size_t local_buffer_cur = 0;
     50 
     51 /* These would both fit into 32 bits, but they are often added in
     52 large multiples, so it's simpler to have two roomy ints */
     53 static  int32_t sample_increment, sample_correction; /*samples per MIDI delta-t*/
     54 
     55 static  int32_t read_local(void* buffer, size_t len, size_t count)
     56 {
     57 	if (fp && len > 0) {
     58 		return (int32_t)fp->Read(buffer, len * count ) / len;
     59 	} else if( local_buffer != NULL ) {
     60 		if (len * count + local_buffer_cur > local_buffer_length) {
     61 			memcpy(buffer, &local_buffer[local_buffer_cur], local_buffer_length - local_buffer_cur);
     62 			return(int32_t)(local_buffer_length - local_buffer_cur)/len;
     63 		} else {
     64 			memcpy(buffer, &local_buffer[local_buffer_cur], len * count);
     65 			local_buffer_cur += len * count;
     66 			return(count);
     67 		}
     68 	}
     69 
     70 	return 0;
     71 }
     72 
     73 static void skip_local(size_t len)
     74 {
     75 	if (fp) {
     76 		skip(fp, len);
     77 	} else {
     78 		if (len + local_buffer_cur > local_buffer_length) {
     79 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "skip_local failed on memory buffer");
     80 		} else {
     81 			local_buffer_cur += len;
     82 		}
     83 	}
     84 }
     85 
     86 /* Computes how many (fractional) samples one MIDI delta-time unit contains */
     87 static void compute_sample_increment( int32_t tempo,  int32_t divisions)
     88 {
     89 	double a;
     90 	a = (double) (tempo) * (double) (play_mode->rate) * (65536.0/1000000.0) /
     91 		(double)(divisions);
     92 
     93 	sample_correction = (int32_t)(a) & 0xFFFF;
     94 	sample_increment = (int32_t)(a) >> 16;
     95 
     96 	ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Samples per delta-t: %d (correction %d)",
     97 		sample_increment, sample_correction);
     98 }
     99 
    100 /* Read variable-length number (7 bits per byte, MSB first) */
    101 static  int32_t getvl(void)
    102 {
    103 	 int32_t l=0;
    104 	uint8_t c;
    105 	for (;;)
    106 	{
    107 		read_local(&c,1,1);
    108 		l += (c & 0x7f);
    109 		if (!(c & 0x80)) return l;
    110 		l<<=7;
    111 	}
    112 }
    113 
    114 /* Print a string from the file, followed by a newline. Any non-ASCII
    115 or unprintable characters will be converted to periods. */
    116 static int dumpstring( int32_t len, char *label)
    117 {
    118 	signed char *s=(signed char *)safe_malloc(len+1);
    119 	if (len != (int32_t)read_local(s, 1, len))
    120 	{
    121 		Real_Tim_Free(s);
    122 		return -1;
    123 	}
    124 	s[len]='\0';
    125 	while (len--)
    126 	{
    127 		if (s[len]<32)
    128 			s[len]='.';
    129 	}
    130 	ctl->cmsg(CMSG_TEXT, VERB_VERBOSE, "%s%s", label, s);
    131 	Real_Tim_Free(s);
    132 	return 0;
    133 }
    134 
    135 #define MIDIEVENT(at,t,ch,pa,pb) \
    136 	newEventList=(MidiEventList*)safe_malloc(sizeof(MidiEventList)); \
    137 	newEventList->event.time=at; newEventList->event.type=t; newEventList->event.channel=ch; \
    138 	newEventList->event.a=pa; newEventList->event.b=pb; newEventList->next=0;\
    139 	return newEventList;
    140 
    141 #define MAGIC_EOT ((MidiEventList *)(-1))
    142 
    143 /* Read a MIDI event, returning a freshly allocated element that can
    144 be linked to the event list */
    145 static MidiEventList *read_midi_event(void)
    146 {
    147 	static uint8_t laststatus, lastchan;
    148 	static uint8_t nrpn=0, rpn_msb[16], rpn_lsb[16]; /* one per channel */
    149 	uint8_t me, type, a,b,c;
    150 	 int32_t len;
    151 	MidiEventList *newEventList;
    152 
    153 	for (;;)
    154 	{
    155 		at+=getvl();
    156 		if (read_local(&me,1,1)!=1)
    157 		{
    158 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: read_midi_event: %s", 
    159 				current_filename, strerror(errno));
    160 			return 0;
    161 		}
    162 
    163 		if(me==0xF0 || me == 0xF7) /* SysEx event */
    164 		{
    165 			len=getvl();
    166 			skip_local(len);
    167 		}
    168 		else if(me==0xFF) /* Meta event */
    169 		{
    170 			read_local(&type,1,1);
    171 			len=getvl();
    172 			if (type>0 && type<16)
    173 			{
    174 				static char *label[]={
    175 					"Text event: ", "Text: ", "Copyright: ", "Track name: ",
    176 						"Instrument: ", "Lyric: ", "Marker: ", "Cue point: "};
    177 					dumpstring(len, label[(type>7) ? 0 : type]);
    178 			}
    179 			else
    180 				switch(type)
    181 			{
    182 				case 0x2F: /* End of Track */
    183 					return MAGIC_EOT;
    184 
    185 				case 0x51: /* Tempo */
    186 					read_local(&a,1,1); read_local(&b,1,1); read_local(&c,1,1);
    187 					MIDIEVENT(at, ME_TEMPO, c, a, b);
    188 
    189 				default:
    190 					ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
    191 						"(Meta event type 0x%02x, length %ld)", type, len);
    192 					skip_local(len);
    193 					break;
    194 			}
    195 		}
    196 		else
    197 		{
    198 			a=me;
    199 			if (a & 0x80) /* status byte */
    200 			{
    201 				lastchan=a & 0x0F;
    202 				laststatus=(a>>4) & 0x07;
    203 				read_local(&a, 1,1);
    204 				a &= 0x7F;
    205 			}
    206 			switch(laststatus)
    207 			{
    208 			case 0: /* Note off */
    209 				read_local(&b, 1,1);
    210 				b &= 0x7F;
    211 				MIDIEVENT(at, ME_NOTEOFF, lastchan, a,b);
    212 
    213 			case 1: /* Note on */
    214 				read_local(&b, 1,1);
    215 				b &= 0x7F;
    216 				MIDIEVENT(at, ME_NOTEON, lastchan, a,b);
    217 
    218 			case 2: /* Key Pressure */
    219 				read_local(&b, 1,1);
    220 				b &= 0x7F;
    221 				MIDIEVENT(at, ME_KEYPRESSURE, lastchan, a, b);
    222 
    223 			case 3: /* Control change */
    224 				read_local(&b, 1,1);
    225 				b &= 0x7F;
    226 				{
    227 					int control=255;
    228 					switch(a)
    229 					{
    230 					case 7: control=ME_MAINVOLUME; break;
    231 					case 10: control=ME_PAN; break;
    232 					case 11: control=ME_EXPRESSION; break;
    233 					case 64: control=ME_SUSTAIN; break;
    234 					case 120: control=ME_ALL_SOUNDS_OFF; break;
    235 					case 121: control=ME_RESET_CONTROLLERS; break;
    236 					case 123: control=ME_ALL_NOTES_OFF; break;
    237 
    238 						/* These should be the SCC-1 tone bank switch
    239 						commands. I don't know why there are two, or
    240 						why the latter only allows switching to bank 0.
    241 						Also, some MIDI files use 0 as some sort of
    242 						continuous controller. This will cause lots of
    243 						warnings about undefined tone banks. */
    244 					case 0: control=ME_TONE_BANK; break;
    245 					case 32: 
    246 						if (b!=0)
    247 							ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
    248 							"(Strange: tone bank change 0x20%02x)", b);
    249 						else
    250 							control=ME_TONE_BANK;
    251 						break;
    252 
    253 					case 100: nrpn=0; rpn_msb[lastchan]=b; break;
    254 					case 101: nrpn=0; rpn_lsb[lastchan]=b; break;
    255 					case 99: nrpn=1; rpn_msb[lastchan]=b; break;
    256 					case 98: nrpn=1; rpn_lsb[lastchan]=b; break;
    257 
    258 					case 6:
    259 						if (nrpn)
    260 						{
    261 							ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
    262 								"(Data entry (MSB) for NRPN %02x,%02x: %ld)",
    263 								rpn_msb[lastchan], rpn_lsb[lastchan],
    264 								b);
    265 							break;
    266 						}
    267 
    268 						switch((rpn_msb[lastchan]<<8) | rpn_lsb[lastchan])
    269 						{
    270 						case 0x0000: /* Pitch bend sensitivity */
    271 							control=ME_PITCH_SENS;
    272 							break;
    273 
    274 						case 0x7F7F: /* RPN reset */
    275 							/* reset pitch bend sensitivity to 2 */
    276 							MIDIEVENT(at, ME_PITCH_SENS, lastchan, 2, 0);
    277 
    278 						default:
    279 							ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
    280 								"(Data entry (MSB) for RPN %02x,%02x: %ld)",
    281 								rpn_msb[lastchan], rpn_lsb[lastchan],
    282 								b);
    283 							break;
    284 						}
    285 						break;
    286 
    287 					default:
    288 						ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
    289 							"(Control %d: %d)", a, b);
    290 						break;
    291 					}
    292 					if (control != 255)
    293 					{ 
    294 						MIDIEVENT(at, control, lastchan, b, 0); 
    295 					}
    296 				}
    297 				break;
    298 
    299 			case 4: /* Program change */
    300 				a &= 0x7f;
    301 				MIDIEVENT(at, ME_PROGRAM, lastchan, a, 0);
    302 
    303 			case 5: /* Channel pressure - NOT IMPLEMENTED */
    304 				break;
    305 
    306 			case 6: /* Pitch wheel */
    307 				read_local(&b, 1,1);
    308 				b &= 0x7F;
    309 				MIDIEVENT(at, ME_PITCHWHEEL, lastchan, a, b);
    310 
    311 			default: 
    312 				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
    313 					"*** Can't happen: status 0x%02X, channel 0x%02X",
    314 					laststatus, lastchan);
    315 				break;
    316 			}
    317 		}
    318 	}
    319 
    320 	return newEventList;
    321 }
    322 
    323 #undef MIDIEVENT
    324 
    325 /* Read a midi track into the linked list, either merging with any previous
    326 tracks or appending to them. */
    327 static int read_track(int append)
    328 {
    329 	MidiEventList *meep;
    330 	MidiEventList *next, *newEventList;
    331 	 int32_t len;
    332 	char tmp[4];
    333 
    334 	meep=evlist;
    335 	if (append && meep)
    336 	{
    337 		/* find the last event in the list */
    338 		for (; meep->next; meep=(MidiEventList *)meep->next)
    339 			;
    340 		at=meep->event.time;
    341 	}
    342 	else
    343 		at=0;
    344 
    345 	/* Check the formalities */
    346 
    347 	if ((read_local(tmp,1,4) != 4) || (read_local(&len,4,1) != 1))
    348 	{
    349 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
    350 			"%s: Can't read track header.", current_filename);
    351 		return -1;
    352 	}
    353 	len=BE_LONG(len);
    354 	if (memcmp(tmp, "MTrk", 4))
    355 	{
    356 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
    357 			"%s: Corrupt MIDI file.", current_filename);
    358 		return -2;
    359 	}
    360 
    361 	for (;;)
    362 	{
    363 		if (!(newEventList=read_midi_event())) /* Some kind of error  */
    364 			return -2;
    365 
    366 		if (newEventList==MAGIC_EOT) /* End-of-track Hack. */
    367 		{
    368 			return 0;
    369 		}
    370 
    371 		next=(MidiEventList *)meep->next;
    372 		while (next && (next->event.time < newEventList->event.time))
    373 		{
    374 			meep=next;
    375 			next=(MidiEventList *)meep->next;
    376 		}
    377 
    378 		newEventList->next=next;
    379 		meep->next=newEventList;
    380 
    381 		event_count++; /* Count the event. (About one?) */
    382 		meep=newEventList;
    383 	}
    384 }
    385 
    386 /* Free the linked event list from memory. */
    387 static void free_midi_list(void)
    388 {
    389 	MidiEventList *meep, *next;
    390 	if (!(meep=evlist)) return;
    391 	while (meep)
    392 	{
    393 		next=(MidiEventList *)meep->next;
    394 		Real_Tim_Free(meep);
    395 		meep=next;
    396 	}
    397 	evlist=0;
    398 }
    399 
    400 /* Allocate an array of MidiEvents and fill it from the linked list of
    401 events, marking used instruments for loading. Convert event times to
    402 samples: handle tempo changes. Strip unnecessary events from the list.
    403 Free the linked list. */
    404 static MidiEvent *groom_list( int32_t divisions, int32_t *eventsp, int32_t *samplesp)
    405 {
    406 	MidiEvent *groomed_list, *lp;
    407 	MidiEventList *meep;
    408 	 int32_t i, our_event_count, tempo, skip_local_this_event, new_value;
    409 	 int32_t sample_cum, samples_to_do, at, st, dt, counting_time;
    410 
    411 	int current_bank[16], current_set[16], current_program[16]; 
    412 	/* Or should each bank have its own current program? */
    413 
    414 	for (i=0; i<16; i++)
    415 	{
    416 		current_bank[i]=0;
    417 		current_set[i]=0;
    418 		current_program[i]=default_program;
    419 	}
    420 
    421 	tempo=500000;
    422 	compute_sample_increment(tempo, divisions);
    423 
    424 	/* This may allocate a bit more than we need */
    425 	groomed_list=lp=(MidiEvent*)safe_malloc(sizeof(MidiEvent) * (event_count+1));
    426 	meep=evlist;
    427 
    428 	our_event_count=0;
    429 	st=at=sample_cum=0;
    430 	counting_time=2; /* We strip any silence before the first NOTE ON. */
    431 
    432 	for (i=0; i<event_count; i++)
    433 	{
    434 		skip_local_this_event=0;
    435 		ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
    436 			"%6d: ch %2d: event %d (%d,%d)",
    437 			meep->event.time, meep->event.channel + 1,
    438 			meep->event.type, meep->event.a, meep->event.b);
    439 
    440 		if (meep->event.type==ME_TEMPO)
    441 		{
    442 			tempo=
    443 				meep->event.channel + meep->event.b * 256 + meep->event.a * 65536;
    444 			compute_sample_increment(tempo, divisions);
    445 			skip_local_this_event=1;
    446 		}
    447 		else if ((quietchannels & (1<<meep->event.channel)))
    448 			skip_local_this_event=1;
    449 		else switch (meep->event.type)
    450 		{
    451 	case ME_PROGRAM:
    452 		if (ISDRUMCHANNEL(meep->event.channel))
    453 		{
    454 			if (drumset[meep->event.a]) /* Is this a defined drumset? */
    455 				new_value=meep->event.a;
    456 			else
    457 			{
    458 				ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
    459 					"Drum set %d is undefined", meep->event.a);
    460 				new_value=meep->event.a=0;
    461 			}
    462 			if (current_set[meep->event.channel] != new_value)
    463 				current_set[meep->event.channel]=new_value;
    464 			else 
    465 				skip_local_this_event=1;
    466 		}
    467 		else
    468 		{
    469 			new_value=meep->event.a;
    470 			if ((current_program[meep->event.channel] != SPECIAL_PROGRAM)
    471 				&& (current_program[meep->event.channel] != new_value))
    472 				current_program[meep->event.channel] = new_value;
    473 			else
    474 				skip_local_this_event=1;
    475 		}
    476 		break;
    477 
    478 	case ME_NOTEON:
    479 		if (counting_time)
    480 			counting_time=1;
    481 		if (ISDRUMCHANNEL(meep->event.channel))
    482 		{
    483 			/* Mark this instrument to be loaded */
    484 			if (!(drumset[current_set[meep->event.channel]]
    485 			->tone[meep->event.a].instrument))
    486 				drumset[current_set[meep->event.channel]]
    487 				->tone[meep->event.a].instrument=
    488 					MAGIC_LOAD_INSTRUMENT;
    489 		}
    490 		else
    491 		{
    492 			if (current_program[meep->event.channel]==SPECIAL_PROGRAM)
    493 				break;
    494 			/* Mark this instrument to be loaded */
    495 			if (!(tonebank[current_bank[meep->event.channel]]
    496 			->tone[current_program[meep->event.channel]].instrument))
    497 				tonebank[current_bank[meep->event.channel]]
    498 				->tone[current_program[meep->event.channel]].instrument=
    499 					MAGIC_LOAD_INSTRUMENT;
    500 		}
    501 		break;
    502 
    503 	case ME_TONE_BANK:
    504 		if (ISDRUMCHANNEL(meep->event.channel))
    505 		{
    506 			skip_local_this_event=1;
    507 			break;
    508 		}
    509 		if (tonebank[meep->event.a]) /* Is this a defined tone bank? */
    510 			new_value=meep->event.a;
    511 		else 
    512 		{
    513 			ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
    514 				"Tone bank %d is undefined", meep->event.a);
    515 			new_value=meep->event.a=0;
    516 		}
    517 		if (current_bank[meep->event.channel]!=new_value)
    518 			current_bank[meep->event.channel]=new_value;
    519 		else
    520 			skip_local_this_event=1;
    521 		break;
    522 		}
    523 
    524 		/* Recompute time in samples*/
    525 		if ((dt=meep->event.time - at) && !counting_time)
    526 		{
    527 			samples_to_do=sample_increment * dt;
    528 			sample_cum += sample_correction * dt;
    529 			if (sample_cum & 0xFFFF0000)
    530 			{
    531 				samples_to_do += ((sample_cum >> 16) & 0xFFFF);
    532 				sample_cum &= 0x0000FFFF;
    533 			}
    534 			st += samples_to_do;
    535 		}
    536 		else if (counting_time==1) counting_time=0;
    537 		if (!skip_local_this_event)
    538 		{
    539 			/* Add the event to the list */
    540 			*lp=meep->event;
    541 			lp->time=st;
    542 			lp++;
    543 			our_event_count++;
    544 		}
    545 		at=meep->event.time;
    546 		meep=(MidiEventList *)meep->next;
    547 	}
    548 	/* Add an End-of-Track event */
    549 	lp->time=st;
    550 	lp->type=ME_EOT;
    551 	our_event_count++;
    552 	free_midi_list();
    553 
    554 	*eventsp=our_event_count;
    555 	*samplesp=st;
    556 	return groomed_list;
    557 }
    558 
    559 MidiEvent *read_midi_file(idFile * mfp,  int32_t *count,  int32_t *sp)
    560 {
    561 	 int32_t len, divisions;
    562 	int16_t format, tracks, divisions_tmp;
    563 	int i;
    564 	char tmp[4];
    565 
    566 	fp = mfp;
    567 	local_buffer = 0;
    568 	local_buffer_length = 0;
    569 	local_buffer_cur = 0;
    570 
    571 	event_count=0;
    572 	at=0;
    573 	evlist=0;
    574 	int first = (read_local(tmp,1,4));
    575 	int second = (read_local(&len,4,1));
    576 	if ( first != 4 || second != 1)
    577 	{
    578 		if (0)
    579 		{
    580 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: %s", current_filename, 
    581 				strerror(errno));
    582 		}
    583 		else
    584 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
    585 			"%s: Not a MIDI file!", current_filename);
    586 		return 0;
    587 	}
    588 	len=BE_LONG(len);
    589 	if (memcmp(tmp, "MThd", 4) || len < 6)
    590 	{
    591 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
    592 			"%s: Not a MIDI file!", current_filename);
    593 		return 0;
    594 	}
    595 
    596 	read_local(&format, 2, 1);
    597 	read_local(&tracks, 2, 1);
    598 	read_local(&divisions_tmp, 2, 1);
    599 	format=BE_SHORT(format);
    600 	tracks=BE_SHORT(tracks);
    601 	divisions_tmp=BE_SHORT(divisions_tmp);
    602 
    603 	if (divisions_tmp<0)
    604 	{
    605 		/* SMPTE time -- totally untested. Got a MIDI file that uses this? */
    606 		divisions=
    607 			(int32_t)(-(divisions_tmp/256)) * (int32_t)(divisions_tmp & 0xFF);
    608 	}
    609 	else divisions=(int32_t)(divisions_tmp);
    610 
    611 	if (len > 6)
    612 	{
    613 		ctl->cmsg(CMSG_WARNING, VERB_NORMAL, 
    614 			"%s: MIDI file header size %ld bytes", 
    615 			current_filename, len);
    616 		skip_local(len-6); /* skip_local the excess */
    617 	}
    618 	if (format<0 || format >2)
    619 	{
    620 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
    621 			"%s: Unknown MIDI file format %d", current_filename, format);
    622 		return 0;
    623 	}
    624 	//ctl->cmsg(CMSG_INFO, VERB_VERBOSE, 
    625 	//	"Format: %d  Tracks: %d  Divisions: %d", format, tracks, divisions);
    626 
    627 	/* Put a do-nothing event first in the list for easier processing */
    628 	evlist=(MidiEventList *)safe_malloc(sizeof(MidiEventList));
    629 	evlist->event.time=0;
    630 	evlist->event.type=ME_NONE;
    631 	evlist->next=0;
    632 	event_count++;
    633 
    634 	switch(format)
    635 	{
    636 	case 0:
    637 		if (read_track(0))
    638 		{
    639 			free_midi_list();
    640 			return 0;
    641 		}
    642 		break;
    643 
    644 	case 1:
    645 		for (i=0; i<tracks; i++)
    646 			if (read_track(0))
    647 			{
    648 				free_midi_list();
    649 				return 0;
    650 			}
    651 			break;
    652 
    653 	case 2: /* We simply play the tracks sequentially */
    654 		for (i=0; i<tracks; i++)
    655 			if (read_track(1))
    656 			{
    657 				free_midi_list();
    658 				return 0;
    659 			}
    660 			break;
    661 	}
    662 	return groom_list(divisions, count, sp);
    663 }
    664 
    665 MidiEvent *read_midi_buffer(unsigned char* buffer, size_t length,  int32_t *count,  int32_t *sp)
    666 {
    667 	 int32_t len, divisions;
    668 	int16_t format, tracks, divisions_tmp;
    669 	int i;
    670 	char tmp[4];
    671 
    672 	fp = 0;
    673 	local_buffer = buffer;
    674 	local_buffer_length = length;
    675 	local_buffer_cur = 0;
    676 
    677 	event_count=0;
    678 	at=0;
    679 	evlist=0;
    680 
    681 	if ((read_local(tmp,1,4) != 4) || (read_local(&len,4,1) != 1))
    682 	{
    683 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,  "Not a MIDI file!");
    684 		return 0;
    685 	}
    686 	len=BE_LONG(len);
    687 	if (memcmp(tmp, "MThd", 4) || len < 6)
    688 	{
    689 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: Not a MIDI file!", current_filename);
    690 		return 0;
    691 	}
    692 
    693 	read_local(&format, 2, 1);
    694 	read_local(&tracks, 2, 1);
    695 	read_local(&divisions_tmp, 2, 1);
    696 	format=BE_SHORT(format);
    697 	tracks=BE_SHORT(tracks);
    698 	divisions_tmp=BE_SHORT(divisions_tmp);
    699 
    700 	if (divisions_tmp<0) {
    701 		/* SMPTE time -- totally untested. Got a MIDI file that uses this? */
    702 		divisions= (int32_t)(-(divisions_tmp/256)) * (int32_t)(divisions_tmp & 0xFF);
    703 	}
    704 	else divisions=(int32_t)(divisions_tmp);
    705 
    706 	if (len > 6)
    707 	{
    708 		ctl->cmsg(CMSG_WARNING, VERB_NORMAL, 
    709 			"%s: MIDI file header size %ld bytes", 
    710 			current_filename, len);
    711 		skip_local(len-6); /* skip_local the excess */
    712 	}
    713 	if (format<0 || format >2)
    714 	{
    715 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
    716 			"%s: Unknown MIDI file format %d", current_filename, format);
    717 		return 0;
    718 	}
    719 	//ctl->cmsg(CMSG_INFO, VERB_VERBOSE, 
    720 	//	"Format: %d  Tracks: %d  Divisions: %d", format, tracks, divisions);
    721 
    722 	/* Put a do-nothing event first in the list for easier processing */
    723 	evlist=(MidiEventList *)safe_malloc(sizeof(MidiEventList));
    724 	evlist->event.time=0;
    725 	evlist->event.type=ME_NONE;
    726 	evlist->next=0;
    727 	event_count++;
    728 
    729 	switch(format)
    730 	{
    731 	case 0:
    732 		if (read_track(0))
    733 		{
    734 			free_midi_list();
    735 			return 0;
    736 		}
    737 		break;
    738 
    739 	case 1:
    740 		for (i=0; i<tracks; i++)
    741 			if (read_track(0))
    742 			{
    743 				free_midi_list();
    744 				return 0;
    745 			}
    746 			break;
    747 
    748 	case 2: /* We simply play the tracks sequentially */
    749 		for (i=0; i<tracks; i++)
    750 			if (read_track(1))
    751 			{
    752 				free_midi_list();
    753 				return 0;
    754 			}
    755 			break;
    756 	}
    757 	return groom_list(divisions, count, sp);
    758 }