Delay note-off until multiple note-ons have been released

Kim Morken's icon

Hi! I'm working with MIDI in Max and I have a situation where the same note (e.g. MIDI note 60) is played twice in quick succession — meaning two note-on events are triggered before any note-off.

I'm splitting note-on and note-off handling into separate parts of my patch, but I want to make sure that note-off is only sent after all note-ons have been released. That is:

  • If a note-on for note 60 comes in twice,

  • I need two corresponding note-offs before I actually send out the note-off message.

Basically, I want to keep track of how many times a note has been triggered, and only send the note-off when the count for that note reaches zero.

Context:
I'm building a playable arpeggiator, where every key press — regardless of pitch — triggers the next note in a pre-defined sequence. The sequence can include the same note multiple times, so a single note might be "turned on" multiple times before it's supposed to turn off.

Is there a clean way to implement this kind of reference counting for MIDI notes in Max?

Thanks!