Skip to content

Commit a3a7c03

Browse files
Fixed ppq and tick timing on MIDI>IMF decoding.
1 parent de0ab07 commit a3a7c03

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

ugbc/src/targets/common/_music.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ static int decode_midi_inside_memory_limits( ) {
120120
// It returns always 0.
121121
static int decode_midi_payload_set_tempo( MidiMessagePayload * _payload ) {
122122

123+
// printf( "iBPM = %d\n", _payload->MsgData.MetaEvent.Data.Tempo.iBPM );
124+
123125
tempo = _payload->MsgData.MetaEvent.Data.Tempo.iBPM;
124126

125127
return 0;
@@ -454,7 +456,7 @@ Variable * music_load_to_variable( Environment * _environment, char * _filename,
454456
if ( mf ) {
455457

456458
imfBuffer = malloc( 16 * MAX_TEMPORARY_STORAGE );
457-
int ppq = 120;
459+
int ppq = midiFileGetPPQN(mf);
458460
int midiConversionDone = 0;
459461
int track = 0;
460462

@@ -626,10 +628,21 @@ Variable * music_load_to_variable( Environment * _environment, char * _filename,
626628
// If the minimum position is valid...
627629
if ( midiMinPosition >= midiPosition && midiMinPosition < (midiPosition + 0xffffff) ) {
628630

631+
// just divide 60,000 by your tempo and you will get the number of milliseconds per beat.
632+
// Thereafter you can divide by two for eighth notes or four for sixteenth notes.
633+
// microseconds per tick = microseconds per quarter note / ticks per quarter note
634+
635+
float kMillisecondsPerBPM = (float)( 60 * 1000 ) / (float)tempo;
636+
float kMillisecondsPerTick = kMillisecondsPerBPM / ppq;
637+
float deltaTimeInMilliseconds = ( midiMinPosition - midiPosition ) * kMillisecondsPerTick;
638+
629639
// We must calculate the effective delay (in jiffies)
630640
// to introduce into the IMF stream, and it is based
631641
// on the real MIDI tempo.
632-
int jiffies = ( ( midiMinPosition - midiPosition ) * 600 ) / ( tempo * ppq );
642+
int jiffies = deltaTimeInMilliseconds / 20;
643+
644+
// printf( " ( midiMinPosition - midiPosition ): %d\n", ( midiMinPosition - midiPosition ) );
645+
// printf( "deltaTimeInMilliseconds: %f, jiffies: %d\n", deltaTimeInMilliseconds, jiffies );
633646

634647
// printf(" DELAY: %d jiffies\n", jiffies );
635648

0 commit comments

Comments
 (0)