craffel / pretty-midi

Utility functions for handling MIDI data in a nice/intuitive way.
MIT License
856 stars 151 forks source link

"program_change" event on any channel only effects the current track #219

Open cyclekiller opened 1 year ago

cyclekiller commented 1 year ago

Hello! This repo is very good, but in https://github.com/craffel/pretty-midi/blob/main/pretty_midi/pretty_midi.py#L317, around line 317 ~ 324, in particular line 324:

        for track_idx, track in enumerate(midi_data.tracks):
            # Keep track of last note on location:
            # key = (instrument, note),
            # value = (note-on tick, velocity)
            last_note_on = collections.defaultdict(list)
            # Keep track of which instrument is playing in each channel
            # initialize to program 0 for all channels
            current_instrument = np.zeros(16, dtype=np.int)

The current_instrument array is reset to zero in each new track. This may cause problem in some MIDIs: If one track sets a program_change event in some channel, another track that shares the same channel (i.e. has some notes in the same channel) is not affected by this program_change. Window's default midi player and MIDIEditor doesn't have this problem. Some DAWs like Cubase also have this problem but doesn't really matter. This MIDI file is an (extreme) example demonstrating this issue.

cyclekiller commented 1 year ago

I know how to fix this "program_change" issue, but should be very careful not to break other parts of the code.

craffel commented 1 year ago

Hi there, if you can find in the MIDI file spec that this is the intended behavior, a PR would be welcome. However, to the best of my knowledge, a program change for some channel on track A should not change the program for the same channel on track B.

cyclekiller commented 1 year ago

Maybe you are right. I can't find any useful information about this issue on the internet. I'm trying to design a rule, for example, when a track has no program change events within it, the program of the last track is assigned to this track. Or a related track that shares the same channel. Something that would be approximately right for many of the abnormal cases.

cyclekiller commented 1 year ago

So regarding to the issue of tracks without programs, here is some discussion I found. Basically, some rule that I just mentioned above is necessary.

caenopy commented 1 year ago

Looks like the MIDI spec is silent on how program changes should be handled between tracks. Tracks are merely an organizational feature of MIDI files, and in General MIDI 1.0, devices have no way of knowing which message corresponds to which track. The assumed behavior should probably be that program changes are global. There are many files in LMD that assume this and program data is currently lost when these are parsed with pretty_midi.