Clean up some MIDI code.
[ardour.git] / libs / ardour / ardour / midi_state_tracker.h
1 /*
2     Copyright (C) 2008 Paul Davis
3     Author: Torben Hohn
4
5     This program is free software; you can redistribute it and/or modify it
6     under the terms of the GNU General Public License as published by the Free
7     Software Foundation; either version 2 of the License, or (at your option)
8     any later version.
9
10     This program is distributed in the hope that it will be useful, but WITHOUT
11     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13     for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #ifndef __ardour_midi_state_tracker_h__
21 #define __ardour_midi_state_tracker_h__
22
23 #include "ardour/midi_buffer.h"
24
25 namespace Evoral {
26 template <typename T> class EventSink;
27 }
28
29 namespace ARDOUR {
30
31 class MidiSource;
32
33 /** Tracks played notes, so they can be resolved in potential stuck note
34  * situations (e.g. looping, transport stop, etc).
35  */
36 class LIBARDOUR_API MidiStateTracker
37 {
38 public:
39         MidiStateTracker();
40
41         void track (const MidiBuffer::iterator& from, const MidiBuffer::iterator& to);
42         void add (uint8_t note, uint8_t chn);
43         void remove (uint8_t note, uint8_t chn);
44         void resolve_notes (MidiBuffer& buffer, framepos_t time);
45         void resolve_notes (Evoral::EventSink<framepos_t>& buffer, framepos_t time);
46         void resolve_notes (MidiSource& src, Evoral::MusicalTime time);
47         void dump (std::ostream&);
48         void reset ();
49         bool empty() const { return _on == 0; }
50         uint16_t on() const { return _on; }
51         bool active (uint8_t note, uint8_t channel) {
52                 return _active_notes[(channel*128)+note] > 0;
53         }
54
55         template<typename Time>
56         void track (const Evoral::Event<Time>& ev) {
57                 const uint8_t type = ev.buffer()[0] & 0xF0;
58                 const uint8_t chan = ev.buffer()[0] & 0x0F;
59                 switch (type) {
60                 case MIDI_CTL_ALL_NOTES_OFF:
61                         reset();
62                         break;
63                 case MIDI_CMD_NOTE_ON:
64                         add(ev.buffer()[1], chan);
65                         break;
66                 case MIDI_CMD_NOTE_OFF:
67                         remove(ev.buffer()[1], chan);
68                         break;
69                 }
70         }
71
72 private:
73         uint8_t  _active_notes[128*16];
74         uint16_t _on;
75 };
76
77
78 } // namespace ARDOUR
79
80 #endif // __ardour_midi_state_tracker_h__