home *** CD-ROM | disk | FTP | other *** search
/ PC Musician 2000 / PC_Musician_2000.iso / PCMUSIC / MISC / MTM05SRC / MIDIFILE.C < prev    next >
Encoding:
C/C++ Source or Header  |  1996-01-09  |  19.7 KB  |  887 lines

  1. /*
  2.  * midifile 1.11
  3.  * 
  4.  * Read and write a MIDI file.  Externally-assigned function pointers are 
  5.  * called upon recognizing things in the file.
  6.  *
  7.  * Original release ?
  8.  * June 1989 - Added writing capability, M. Czeiszperger.
  9.  *
  10.  *          The file format implemented here is called
  11.  *          Standard MIDI Files, and is part of the Musical
  12.  *          instrument Digital Interface specification.
  13.  *          The spec is avaiable from:
  14.  *
  15.  *               International MIDI Association
  16.  *               5316 West 57th Street
  17.  *               Los Angeles, CA 90056
  18.  *
  19.  *          An in-depth description of the spec can also be found
  20.  *          in the article "Introducing Standard MIDI Files", published
  21.  *          in Electronic Musician magazine, April, 1989.
  22.  * 
  23.  */
  24. #include "midifile.h"
  25. #define NULLFUNC 0
  26. #define NULL 0
  27.  
  28. #define THINK
  29.  
  30. #ifdef THINK
  31. #include <stdlib.h>
  32. #endif
  33.  
  34. #include <stdio.h>
  35.  
  36. char *strcpy(), *strcat();
  37. #ifdef __STDC__
  38. void exit(), free();
  39. #endif
  40. static readheader();
  41. static readtrack();
  42. static badbyte();
  43. static metaevent();
  44. static sysex();
  45. static chanmessage();
  46. static msginit();
  47. static msgleng();
  48. static msgadd();
  49. static biggermsg();
  50. void WriteVarLen();
  51.  
  52. /* public stuff */
  53.  
  54. /* Functions to be called while processing the MIDI file. */
  55. int (*Mf_getc)() = NULLFUNC;
  56. int (*Mf_error)() = NULLFUNC;
  57. int (*Mf_header)() = NULLFUNC;
  58. int (*Mf_trackstart)() = NULLFUNC;
  59. int (*Mf_trackend)() = NULLFUNC;
  60. int (*Mf_noteon)() = NULLFUNC;
  61. int (*Mf_noteoff)() = NULLFUNC;
  62. int (*Mf_pressure)() = NULLFUNC;
  63. int (*Mf_parameter)() = NULLFUNC;
  64. int (*Mf_pitchbend)() = NULLFUNC;
  65. int (*Mf_program)() = NULLFUNC;
  66. int (*Mf_chanpressure)() = NULLFUNC;
  67. int (*Mf_sysex)() = NULLFUNC;
  68. int (*Mf_arbitrary)() = NULLFUNC;
  69. int (*Mf_metamisc)() = NULLFUNC;
  70. int (*Mf_seqnum)() = NULLFUNC;
  71. int (*Mf_eot)() = NULLFUNC;
  72. int (*Mf_smpte)() = NULLFUNC;
  73. int (*Mf_tempo)() = NULLFUNC;
  74. int (*Mf_timesig)() = NULLFUNC;
  75. int (*Mf_keysig)() = NULLFUNC;
  76. int (*Mf_seqspecific)() = NULLFUNC;
  77. int (*Mf_text)() = NULLFUNC;
  78.  
  79. /* Functions to implement in order to write a MIDI file */
  80. int (*Mf_putc)() = NULLFUNC;
  81. int (*Mf_writetrack)() = NULLFUNC;
  82. int (*Mf_writetempotrack)() = NULLFUNC;
  83.  
  84. int Mf_nomerge = 0;        /* 1 => continue'ed system exclusives are */
  85.                             /* not collapsed. */
  86. long Mf_currtime = 0L;        /* current time in delta-time units */
  87.  
  88. /* private stuff */
  89. static long Mf_toberead = 0L;
  90. static long Mf_numbyteswritten = 0L;
  91.  
  92. static long readvarinum();
  93. static long read32bit();
  94. static long to32bit();
  95. static int read16bit();
  96. static int to16bit();
  97. static char *msg();
  98.  
  99. mfread()         /* The only non-static function in this file. */
  100. {
  101.     if ( Mf_getc == NULLFUNC )
  102.         mferror("mfread() called without setting Mf_getc"); 
  103.  
  104.     readheader();
  105.     while ( readtrack() )
  106.         ;
  107. }
  108.  
  109. /* for backward compatibility with the original lib */
  110. midifile()
  111. {
  112.     mfread();
  113. }
  114.  
  115. static
  116. readmt(s)        /* read through the "MThd" or "MTrk" header string */
  117. char *s;
  118. {
  119.     int n = 0;
  120.     char *p = s;
  121.     int c;
  122.  
  123.     while ( n++<4 && (c=(*Mf_getc)()) != EOF ) {
  124.         if ( c != *p++ ) {
  125.             char buff[32];
  126.             (void) strcpy(buff,"expecting ");
  127.             (void) strcat(buff,s);
  128.             mferror(buff);
  129.         }
  130.     }
  131.     return(c);
  132. }
  133.  
  134. static
  135. egetc()            /* read a single character and abort on EOF */
  136. {
  137.     int c = (*Mf_getc)();
  138.  
  139.     if ( c == EOF )
  140.         mferror("premature EOF");
  141.     Mf_toberead--;
  142.     return(c);
  143. }
  144.  
  145. static
  146. readheader()        /* read a header chunk */
  147. {
  148.     int format, ntrks, division;
  149.  
  150.     if ( readmt("MThd") == EOF )
  151.         return;
  152.  
  153.     Mf_toberead = read32bit();
  154.     format = read16bit();
  155.     ntrks = read16bit();
  156.     division = read16bit();
  157.  
  158.     if ( Mf_header )
  159.         (*Mf_header)(format,ntrks,division);
  160.  
  161.     /* flush any extra stuff, in case the length of header is not 6 */
  162.     while ( Mf_toberead > 0 )
  163.         (void) egetc();
  164. }
  165.  
  166. static
  167. readtrack()         /* read a track chunk */
  168. {
  169.     /* This array is indexed by the high half of a status byte.  It's */
  170.     /* value is either the number of bytes needed (1 or 2) for a channel */
  171.     /* message, or 0 (meaning it's not  a channel message). */
  172.     static int chantype[] = {
  173.         0, 0, 0, 0, 0, 0, 0, 0,        /* 0x00 through 0x70 */
  174.         2, 2, 2, 2, 1, 1, 2, 0        /* 0x80 through 0xf0 */
  175.     };
  176.     long lookfor;
  177.     int c, c1, type;
  178.     int sysexcontinue = 0;    /* 1 if last message was an unfinished sysex */
  179.     int running = 0;    /* 1 when running status used */
  180.     int status = 0;        /* status value (e.g. 0x90==note-on) */
  181.     int needed;
  182.  
  183.     if ( readmt("MTrk") == EOF )
  184.         return(0);
  185.  
  186.     Mf_toberead = read32bit();
  187.     Mf_currtime = 0;
  188.  
  189.     if ( Mf_trackstart )
  190.         (*Mf_trackstart)();
  191.  
  192.     while ( Mf_toberead > 0 ) {
  193.  
  194.         Mf_currtime += readvarinum();    /* delta time */
  195.  
  196.         c = egetc();
  197.  
  198.         if ( sysexcontinue && c != 0xf7 )
  199.             mferror("didn't find expected continuation of a sysex");
  200.  
  201.         if ( (c & 0x80) == 0 ) {     /* running status? */
  202.             if ( status == 0 )
  203.                 mferror("unexpected running status");
  204.             running = 1;
  205.         }
  206.         else {
  207.             status = c;
  208.             running = 0;
  209.         }
  210.  
  211.         needed = chantype[ (status>>4) & 0xf ];
  212.  
  213.         if ( needed ) {        /* ie. is it a channel message? */
  214.  
  215.             if ( running )
  216.                 c1 = c;
  217.             else
  218.                 c1 = egetc();
  219.             chanmessage( status, c1, (needed>1) ? egetc() : 0 );
  220.             continue;;
  221.         }
  222.  
  223.         switch ( c ) {
  224.  
  225.         case 0xff:            /* meta event */
  226.  
  227.             type = egetc();
  228.             lookfor = Mf_toberead - readvarinum();
  229.             msginit();
  230.  
  231.             while ( Mf_toberead > lookfor )
  232.                 msgadd(egetc());
  233.  
  234.             metaevent(type);
  235.             break;
  236.  
  237.         case 0xf0:        /* start of system exclusive */
  238.  
  239.             lookfor = Mf_toberead - readvarinum();
  240.             msginit();
  241.             msgadd(0xf0);
  242.  
  243.             while ( Mf_toberead > lookfor )
  244.                 msgadd(c=egetc());
  245.  
  246.             if ( c==0xf7 || Mf_nomerge==0 )
  247.                 sysex();
  248.             else
  249.                 sysexcontinue = 1;  /* merge into next msg */
  250.             break;
  251.  
  252.         case 0xf7:    /* sysex continuation or arbitrary stuff */
  253.  
  254.             lookfor = Mf_toberead - readvarinum();
  255.  
  256.             if ( ! sysexcontinue )
  257.                 msginit();
  258.  
  259.             while ( Mf_toberead > lookfor )
  260.                 msgadd(c=egetc());
  261.  
  262.             if ( ! sysexcontinue ) {
  263.                 if ( Mf_arbitrary )
  264.                     (*Mf_arbitrary)(msgleng(),msg());
  265.             }
  266.             else if ( c == 0xf7 ) {
  267.                 sysex();
  268.                 sysexcontinue = 0;
  269.             }
  270.             break;
  271.         default:
  272.             badbyte(c);
  273.             break;
  274.         }
  275.     }
  276.     if ( Mf_trackend )
  277.         (*Mf_trackend)();
  278.     return(1);
  279. }
  280.  
  281. static
  282. badbyte(c)
  283. int c;
  284. {
  285.     char buff[32];
  286.  
  287.     (void) sprintf(buff,"unexpected byte: 0x%02x",c);
  288.     mferror(buff);
  289. }
  290.  
  291. static
  292. metaevent(type)
  293. {
  294.     int leng = msgleng();
  295.     char *m = msg();
  296.  
  297.     switch  ( type ) {
  298.     case 0x00:
  299.         if ( Mf_seqnum )
  300.             (*Mf_seqnum)(to16bit(m[0],m[1]));
  301.         break;
  302.     case 0x01:    /* Text event */
  303.     case 0x02:    /* Copyright notice */
  304.     case 0x03:    /* Sequence/Track name */
  305.     case 0x04:    /* Instrument name */
  306.     case 0x05:    /* Lyric */
  307.     case 0x06:    /* Marker */
  308.     case 0x07:    /* Cue point */
  309.     case 0x08:
  310.     case 0x09:
  311.     case 0x0a:
  312.     case 0x0b:
  313.     case 0x0c:
  314.     case 0x0d:
  315.     case 0x0e:
  316.     case 0x0f:
  317.         /* These are all text events */
  318.         if ( Mf_text )
  319.             (*Mf_text)(type,leng,m);
  320.         break;
  321.     case 0x2f:    /* End of Track */
  322.         if ( Mf_eot )
  323.             (*Mf_eot)();
  324.         break;
  325.     case 0x51:    /* Set tempo */
  326.         if ( Mf_tempo )
  327.             (*Mf_tempo)(to32bit(0,m[0],m[1],m[2]));
  328.         break;
  329.     case 0x54:
  330.         if ( Mf_smpte )
  331.             (*Mf_smpte)(m[0],m[1],m[2],m[3],m[4]);
  332.         break;
  333.     case 0x58:
  334.         if ( Mf_timesig )
  335.             (*Mf_timesig)(m[0],m[1],m[2],m[3]);
  336.         break;
  337.     case 0x59:
  338.         if ( Mf_keysig )
  339.             (*Mf_keysig)(m[0],m[1]);
  340.         break;
  341.     case 0x7f:
  342.         if ( Mf_seqspecific )
  343.             (*Mf_seqspecific)(leng,m);
  344.         break;
  345.     default:
  346.         if ( Mf_metamisc )
  347.             (*Mf_metamisc)(type,leng,m);
  348.     }
  349. }
  350.  
  351. static
  352. sysex()
  353. {
  354.     if ( Mf_sysex )
  355.         (*Mf_sysex)(msgleng(),msg());
  356. }
  357.  
  358. static
  359. chanmessage(status,c1,c2)
  360. int status;
  361. int c1, c2;
  362. {
  363.     int chan = status & 0xf;
  364.  
  365.     switch ( status & 0xf0 ) {
  366.     case 0x80:
  367.         if ( Mf_noteoff )
  368.             (*Mf_noteoff)(chan,c1,c2);
  369.         break;
  370.     case 0x90:
  371.         if ( Mf_noteon )
  372.             (*Mf_noteon)(chan,c1,c2);
  373.         break;
  374.     case 0xa0:
  375.         if ( Mf_pressure )
  376.             (*Mf_pressure)(chan,c1,c2);
  377.         break;
  378.     case 0xb0:
  379.         if ( Mf_parameter )
  380.             (*Mf_parameter)(chan,c1,c2);
  381.         break;
  382.     case 0xe0:
  383.         if ( Mf_pitchbend )
  384.             (*Mf_pitchbend)(chan,c1,c2);
  385.         break;
  386.     case 0xc0:
  387.         if ( Mf_program )
  388.             (*Mf_program)(chan,c1);
  389.         break;
  390.     case 0xd0:
  391.         if ( Mf_chanpressure )
  392.             (*Mf_chanpressure)(chan,c1);
  393.         break;
  394.     }
  395. }
  396.  
  397. /* readvarinum - read a varying-length number, and return the */
  398. /* number of characters it took. */
  399.  
  400. static long
  401. readvarinum()
  402. {
  403.     long value;
  404.     int c;
  405.  
  406.     c = egetc();
  407.     value = c;
  408.     if ( c & 0x80 ) {
  409.         value &= 0x7f;
  410.         do {
  411.             c = egetc();
  412.             value = (value << 7) + (c & 0x7f);
  413.         } while (c & 0x80);
  414.     }
  415.     return (value);
  416. }
  417.  
  418. static long
  419. to32bit(c1,c2,c3,c4)
  420. {
  421.     long value = 0L;
  422.  
  423.     value = (c1 & 0xff);
  424.     value = (value<<8) + (c2 & 0xff);
  425.     value = (value<<8) + (c3 & 0xff);
  426.     value = (value<<8) + (c4 & 0xff);
  427.     return (value);
  428. }
  429.  
  430. static
  431. to16bit(c1,c2)
  432. int c1, c2;
  433. {
  434.     return ((c1 & 0xff ) << 8) + (c2 & 0xff);
  435. }
  436.  
  437. static long
  438. read32bit()
  439. {
  440.     int c1, c2, c3, c4;
  441.  
  442.     c1 = egetc();
  443.     c2 = egetc();
  444.     c3 = egetc();
  445.     c4 = egetc();
  446.     return to32bit(c1,c2,c3,c4);
  447. }
  448.  
  449. static
  450. read16bit()
  451. {
  452.     int c1, c2;
  453.     c1 = egetc();
  454.     c2 = egetc();
  455.     return to16bit(c1,c2);
  456. }
  457.  
  458. /* static */
  459. mferror(s)
  460. char *s;
  461. {
  462.     if ( Mf_error )
  463.         (*Mf_error)(s);
  464.     exit(1);
  465. }
  466.  
  467. /* The code below allows collection of a system exclusive message of */
  468. /* arbitrary length.  The Msgbuff is expanded as necessary.  The only */
  469. /* visible data/routines are msginit(), msgadd(), msg(), msgleng(). */
  470.  
  471. #define MSGINCREMENT 128
  472. static char *Msgbuff = NULL;    /* message buffer */
  473. static int Msgsize = 0;        /* Size of currently allocated Msg */
  474. static int Msgindex = 0;    /* index of next available location in Msg */
  475.  
  476. static
  477. msginit()
  478. {
  479.     Msgindex = 0;
  480. }
  481.  
  482. static char *
  483. msg()
  484. {
  485.     return(Msgbuff);
  486. }
  487.  
  488. static
  489. msgleng()
  490. {
  491.     return(Msgindex);
  492. }
  493.  
  494. static
  495. msgadd(c)
  496. int c;
  497. {
  498.     /* If necessary, allocate larger message buffer. */
  499.     if ( Msgindex >= Msgsize )
  500.         biggermsg();
  501.     Msgbuff[Msgindex++] = c;
  502. }
  503.  
  504. static
  505. biggermsg()
  506. {
  507. /*     char *malloc(); */
  508.     char *newmess;
  509.     char *oldmess = Msgbuff;
  510.     int oldleng = Msgsize;
  511.  
  512.     Msgsize += MSGINCREMENT;
  513.     newmess = (char *) malloc( (unsigned)(sizeof(char)*Msgsize) );
  514.  
  515.     if(newmess == NULL)
  516.         mferror("malloc error!");
  517.         
  518.     /* copy old message into larger new one */
  519.     if ( oldmess != NULL ) {
  520.         register char *p = newmess;
  521.         register char *q = oldmess;
  522.         register char *endq = &oldmess[oldleng];
  523.  
  524.         for ( ; q!=endq ; p++,q++ )
  525.             *p = *q;
  526.         free(oldmess);
  527.     }
  528.     Msgbuff = newmess;
  529. }
  530.  
  531. /*
  532.  * mfwrite() - The only fuction you'll need to call to write out
  533.  *             a midi file.
  534.  *
  535.  * format      0 - Single multi-channel track
  536.  *             1 - Multiple simultaneous tracks
  537.  *             2 - One or more sequentially independent
  538.  *                 single track patterns                
  539.  * ntracks     The number of tracks in the file.
  540.  * division    This is kind of tricky, it can represent two
  541.  *             things, depending on whether it is positive or negative
  542.  *             (bit 15 set or not).  If  bit  15  of division  is zero,
  543.  *             bits 14 through 0 represent the number of delta-time
  544.  *             "ticks" which make up a quarter note.  If bit  15 of
  545.  *             division  is  a one, delta-times in a file correspond to
  546.  *             subdivisions of a second similiar to  SMPTE  and  MIDI
  547.  *             time code.  In  this format bits 14 through 8 contain
  548.  *             one of four values - 24, -25, -29, or -30,
  549.  *             corresponding  to  the  four standard  SMPTE and MIDI
  550.  *             time code frame per second formats, where  -29
  551.  *             represents  30  drop  frame.   The  second  byte
  552.  *             consisting  of  bits 7 through 0 corresponds the the
  553.  *             resolution within a frame.  Refer the Standard MIDI
  554.  *             Files 1.0 spec for more details.
  555.  * fp          This should be the open file pointer to the file you
  556.  *             want to write.  It will have be a global in order
  557.  *             to work with Mf_putc.  
  558.  */ 
  559. void 
  560. mfwrite(format,ntracks,division,fp) 
  561. int format,ntracks,division; 
  562. FILE *fp; 
  563. {
  564.     int i; void mf_write_track_chunk(), mf_write_header_chunk();
  565.  
  566.     if ( Mf_putc == NULLFUNC )
  567.         mferror("mfmf_write() called without setting Mf_putc");
  568.  
  569.     if ( Mf_writetrack == NULLFUNC )
  570.         mferror("mfmf_write() called without setting Mf_mf_writetrack"); 
  571.  
  572.     /* every MIDI file starts with a header */
  573.     mf_write_header_chunk(format,ntracks,division);
  574.  
  575.     /* In format 1 files, the first track is a tempo map */
  576.     if(format == 1 && ( Mf_writetempotrack ))
  577.     {
  578.     (*Mf_writetempotrack)();
  579.     }
  580.  
  581.     /* The rest of the file is a series of tracks */
  582.     for(i = 0; i < ntracks; i++)
  583.         mf_write_track_chunk(i,fp);
  584. }
  585.  
  586. void 
  587. mf_write_track_chunk(which_track,fp)
  588. int which_track;
  589. FILE *fp;
  590. {
  591.     unsigned long trkhdr,trklength;
  592.     long offset, place_marker;
  593.     void write16bit(),write32bit();
  594.     
  595.     
  596.     trkhdr = MTrk;
  597.     trklength = 0;
  598.  
  599.     /* Remember where the length was written, because we don't
  600.        know how long it will be until we've finished writing */
  601.     offset = ftell(fp); 
  602.  
  603. #ifdef DEBUG
  604.         printf("offset = %d\n",(int) offset);
  605. #endif
  606.  
  607.     /* Write the track chunk header */
  608.     write32bit(trkhdr);
  609.     write32bit(trklength);
  610.  
  611.     Mf_numbyteswritten = 0L; /* the header's length doesn't count */
  612.  
  613.     if( Mf_writetrack )
  614.     {
  615.         (*Mf_writetrack)(which_track);
  616.     }
  617.  
  618.     /* mf_write End of track meta event */
  619.     eputc(0);
  620.     eputc(meta_event);
  621.     eputc(end_of_track);
  622.  
  623.      eputc(0);
  624.      
  625.     /* It's impossible to know how long the track chunk will be beforehand,
  626.            so the position of the track length data is kept so that it can
  627.            be written after the chunk has been generated */
  628.     place_marker = ftell(fp);
  629.     
  630.     /* This method turned out not to be portable because the
  631.            parameter returned from ftell is not guaranteed to be
  632.            in bytes on every machine */
  633.      /* track.length = place_marker - offset - (long) sizeof(track); */
  634.  
  635. #ifdef DEBUG
  636. printf("length = %d\n",(int) trklength);
  637. #endif
  638.  
  639.      if(fseek(fp,offset,0) < 0)
  640.         mferror("error seeking during final stage of write");
  641.  
  642.     trklength = Mf_numbyteswritten;
  643.  
  644.     /* Re-mf_write the track chunk header with right length */
  645.     write32bit(trkhdr);
  646.     write32bit(trklength);
  647.  
  648.     fseek(fp,place_marker,0);
  649. } /* End gen_track_chunk() */
  650.  
  651.  
  652. void 
  653. mf_write_header_chunk(format,ntracks,division)
  654. int format,ntracks,division;
  655. {
  656.     unsigned long ident,length;
  657.     void write16bit(),write32bit();
  658.     
  659.     ident = MThd;           /* Head chunk identifier                    */
  660.     length = 6;             /* Chunk length                             */
  661.  
  662.     /* individual bytes of the header must be written separately
  663.        to preserve byte order across cpu types :-( */
  664.     write32bit(ident);
  665.     write32bit(length);
  666.     write16bit(format);
  667.     write16bit(ntracks);
  668.     write16bit(division);
  669. } /* end gen_header_chunk() */
  670.  
  671.  
  672. /*
  673.  * mf_write_midi_event()
  674.  * 
  675.  * Library routine to mf_write a single MIDI track event in the standard MIDI
  676.  * file format. The format is:
  677.  *
  678.  *                    <delta-time><event>
  679.  *
  680.  * In this case, event can be any multi-byte midi message, such as
  681.  * "note on", "note off", etc.      
  682.  *
  683.  * delta_time - the time in ticks since the last event.
  684.  * type - the type of meta event.
  685.  * chan - The midi channel.
  686.  * data - A pointer to a block of chars containing the META EVENT,
  687.  *        data.
  688.  * size - The length of the meta-event data.
  689.  */
  690. int 
  691. mf_write_midi_event(delta_time, type, chan, data, size)
  692. unsigned long delta_time;
  693. unsigned int chan,type;
  694. unsigned long size;
  695. unsigned char *data;
  696. {
  697.     int i;
  698.     void WriteVarLen();
  699.     unsigned char c;
  700.  
  701.     WriteVarLen(delta_time);
  702.  
  703.     /* all MIDI events start with the type in the first four bits,
  704.        and the channel in the lower four bits */
  705.     c = type | chan;
  706.  
  707.     if(chan > 15)
  708.         perror("error: MIDI channel greater than 16\n");
  709.  
  710.     eputc(c);
  711.  
  712.     /* write out the data bytes */
  713.     for(i = 0; i < size; i++)
  714.     eputc(data[i]);
  715.  
  716.     return(size);
  717. } /* end mf_write MIDI event */
  718.  
  719. /*
  720.  * mf_write_meta_event()
  721.  *
  722.  * Library routine to mf_write a single meta event in the standard MIDI
  723.  * file format. The format of a meta event is:
  724.  *
  725.  *          <delta-time><FF><type><length><bytes>
  726.  *
  727.  * delta_time - the time in ticks since the last event.
  728.  * type - the type of meta event.
  729.  * data - A pointer to a block of chars containing the META EVENT,
  730.  *        data.
  731.  * size - The length of the meta-event data.
  732.  */
  733. int
  734. mf_write_meta_event(delta_time, type, data, size)
  735. unsigned long delta_time;
  736. unsigned char *data,type;
  737. unsigned long size;
  738. {
  739.     int i;
  740.  
  741.     WriteVarLen(delta_time);
  742.     
  743.     /* This marks the fact we're writing a meta-event */
  744.     eputc(meta_event);
  745.  
  746.     /* The type of meta event */
  747.     eputc(type);
  748.  
  749.     /* The length of the data bytes to follow */
  750.     WriteVarLen(size); 
  751.  
  752.     for(i = 0; i < size; i++)
  753.     {
  754.     if(eputc(data[i]) != data[i])
  755.         return(-1); 
  756.     }
  757.     return(size);
  758. } /* end mf_write_meta_event */
  759.  
  760. void 
  761. mf_write_tempo(tempo)
  762. unsigned long tempo;
  763. {
  764.     /* Write tempo */
  765.     /* all tempos are written as 120 beats/minute, */
  766.     /* expressed in microseconds/quarter note     */
  767.     eputc(0);
  768.     eputc(meta_event);
  769.     eputc(set_tempo);
  770.  
  771.     eputc(3);
  772.     eputc((unsigned)(0xff & (tempo >> 16)));
  773.     eputc((unsigned)(0xff & (tempo >> 8)));
  774.     eputc((unsigned)(0xff & tempo));
  775. }
  776.  
  777. unsigned long 
  778. mf_sec2ticks(secs,division,tempo)
  779. int division;
  780. unsigned int tempo;
  781. float secs;
  782. {    
  783.      return (long)(((secs * 1000.0) / 4.0 * division) / tempo);
  784. }
  785.  
  786. /*
  787.  * Write multi-length bytes to MIDI format files
  788.  */
  789. void 
  790. WriteVarLen(value)
  791. unsigned long value;
  792. {
  793.   unsigned long buffer;
  794.  
  795.   buffer = value & 0x7f;
  796.   while((value >>= 7) > 0)
  797.   {
  798.     buffer <<= 8;
  799.     buffer |= 0x80;
  800.     buffer += (value & 0x7f);
  801.   }
  802.   while(1){
  803.        eputc((unsigned)(buffer & 0xff));
  804.        
  805.     if(buffer & 0x80)
  806.         buffer >>= 8;
  807.     else
  808.         return;
  809.     }
  810. }/* end of WriteVarLen */
  811.  
  812. /* 
  813.  * This routine converts delta times in ticks into seconds. The
  814.  * else statement is needed because the formula is different for tracks
  815.  * based on notes and tracks based on SMPTE times.
  816.  *
  817.  */
  818. float 
  819. mf_ticks2sec(ticks,division,tempo)
  820. int division;
  821. unsigned int tempo;
  822. unsigned long ticks;
  823. {
  824.     float smpte_format, smpte_resolution;
  825.  
  826.     if(division > 0)
  827.         return ((float) (((float)(ticks) * (float)(tempo)) / ((float)(division) * 1000000.0)));
  828.     else
  829.     {
  830.        smpte_format = upperbyte(division);
  831.        smpte_resolution = lowerbyte(division);
  832.        return (float) ((float) ticks / (smpte_format * smpte_resolution * 1000000.0));
  833.     }
  834. } /* end of ticks2sec() */
  835.  
  836.  
  837. /*
  838.  * write32bit()
  839.  * write16bit()
  840.  *
  841.  * These routines are used to make sure that the byte order of
  842.  * the various data types remains constant between machines. This
  843.  * helps make sure that the code will be portable from one system
  844.  * to the next.  It is slightly dangerous that it assumes that longs
  845.  * have at least 32 bits and ints have at least 16 bits, but this
  846.  * has been true at least on PCs, UNIX machines, and Macintosh's.
  847.  *
  848.  */
  849. void 
  850. write32bit(data)
  851. unsigned long data;
  852. {
  853.     eputc((unsigned)((data >> 24) & 0xff));
  854.     eputc((unsigned)((data >> 16) & 0xff));
  855.     eputc((unsigned)((data >> 8 ) & 0xff));
  856.     eputc((unsigned)(data & 0xff));
  857. }
  858.  
  859. void 
  860. write16bit(data)
  861. int data;
  862. {
  863.     eputc((unsigned)((data & 0xff00) >> 8));
  864.     eputc((unsigned)(data & 0xff));
  865. }
  866.  
  867. /* write a single character and abort on error */
  868. eputc(c)            
  869. unsigned char c;
  870. {
  871.     int return_val;
  872.     
  873.     if((Mf_putc) == NULLFUNC)
  874.     {
  875.         mferror("Mf_putc undefined");
  876.         return(-1);
  877.     }
  878.     
  879.     return_val = (Mf_putc)(c);
  880.  
  881.     if ( return_val == EOF )
  882.         mferror("error writing");
  883.         
  884.     Mf_numbyteswritten++;
  885.     return(return_val);
  886. }
  887.