track notes at the region level in MidiPlaylist; resolve them (deliver note offs...
[ardour.git] / libs / ardour / midi_source.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3         Written by Dave Robillard, 2006
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <poll.h>
24 #include <float.h>
25 #include <cerrno>
26 #include <ctime>
27 #include <cmath>
28 #include <iomanip>
29 #include <algorithm>
30
31 #include "pbd/xml++.h"
32 #include "pbd/pthread_utils.h"
33 #include "pbd/basename.h"
34
35 #include "ardour/audioengine.h"
36 #include "ardour/midi_model.h"
37 #include "ardour/midi_ring_buffer.h"
38 #include "ardour/midi_state_tracker.h"
39 #include "ardour/midi_source.h"
40 #include "ardour/session.h"
41 #include "ardour/session_directory.h"
42 #include "ardour/source_factory.h"
43 #include "ardour/tempo.h"
44
45 #include "i18n.h"
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace PBD;
50
51 sigc::signal<void,MidiSource *> MidiSource::MidiSourceCreated;
52
53 MidiSource::MidiSource (Session& s, string name, Source::Flag flags)
54         : Source (s, DataType::MIDI, name, flags)
55         , _read_data_count(0)
56         , _write_data_count(0)
57         , _writing (false)
58         , _length_beats(0.0)
59         , _last_read_end(0)
60         , _last_write_end(0)
61 {
62 }
63
64 MidiSource::MidiSource (Session& s, const XMLNode& node)
65         : Source (s, node)
66         , _read_data_count(0)
67         , _write_data_count(0)
68         , _writing (false)
69         , _length_beats(0.0)
70         , _last_read_end(0)
71         , _last_write_end(0)
72 {
73         _read_data_count = 0;
74         _write_data_count = 0;
75
76         if (set_state (node, Stateful::loading_state_version)) {
77                 throw failed_constructor();
78         }
79 }
80
81 MidiSource::~MidiSource ()
82 {
83 }
84
85 XMLNode&
86 MidiSource::get_state ()
87 {
88         XMLNode& node (Source::get_state());
89
90         if (_captured_for.length()) {
91                 node.add_property ("captured-for", _captured_for);
92         }
93
94         return node;
95 }
96
97 int
98 MidiSource::set_state (const XMLNode& node, int version)
99 {
100         const XMLProperty* prop;
101
102         if ((prop = node.property ("captured-for")) != 0) {
103                 _captured_for = prop->value();
104         }
105
106         return 0;
107 }
108
109 sframes_t
110 MidiSource::length (sframes_t pos) const
111 {
112         BeatsFramesConverter converter(_session, pos);
113         return converter.to(_length_beats);
114 }
115
116 void
117 MidiSource::update_length (sframes_t /*pos*/, sframes_t /*cnt*/)
118 {
119         // You're not the boss of me!
120 }
121
122 void
123 MidiSource::invalidate ()
124 {
125         _model_iter.invalidate();
126 }
127
128 nframes_t
129 MidiSource::midi_read (MidiRingBuffer<nframes_t>& dst, sframes_t source_start,
130                        sframes_t start, nframes_t cnt,
131                        sframes_t stamp_offset, sframes_t negative_stamp_offset,
132                        MidiStateTracker* tracker) const
133 {
134         Glib::Mutex::Lock lm (_lock);
135
136         BeatsFramesConverter converter(_session, source_start);
137
138         if (_model) {
139 #define BEATS_TO_FRAMES(t) (converter.to(t) + stamp_offset - negative_stamp_offset)
140
141                 Evoral::Sequence<double>::const_iterator& i = _model_iter;
142
143                 if (_last_read_end == 0 || start != _last_read_end || !i.valid()) {
144                         for (i = _model->begin(); i != _model->end(); ++i) {
145                                 if (BEATS_TO_FRAMES(i->time()) >= start) {
146                                         break;
147                                 }
148                         }
149                 }
150
151                 _last_read_end = start + cnt;
152
153                 for (; i != _model->end(); ++i) {
154                         const sframes_t time_frames = BEATS_TO_FRAMES(i->time());
155                         if (time_frames < source_start + start + cnt) {
156                                 dst.write(time_frames, i->event_type(), i->size(), i->buffer());
157                                 if (tracker) {
158                                         Evoral::MIDIEvent<Evoral::MusicalTime>& ev (*(Evoral::MIDIEvent<Evoral::MusicalTime>*) (&(*i)));
159                                         if (ev.is_note_on()) {
160                                                 tracker->add (ev.note(), ev.channel());
161                                         } else if (ev.is_note_off()) {
162                                                 tracker->remove (ev.note(), ev.channel());
163                                         }
164                                 }
165                         } else {
166                                 break;
167                         }
168                 }
169                 return cnt;
170         } else {
171                 return read_unlocked (dst, source_start, start, cnt, stamp_offset, negative_stamp_offset, tracker);
172         }
173 }
174
175 nframes_t
176 MidiSource::midi_write (MidiRingBuffer<nframes_t>& source, sframes_t source_start, nframes_t duration)
177 {
178         Glib::Mutex::Lock lm (_lock);
179         const nframes_t ret = write_unlocked (source, source_start, duration);
180         _last_write_end += duration;
181         return ret;
182 }
183
184 bool
185 MidiSource::file_changed (string path)
186 {
187         struct stat stat_file;
188
189         int e1 = stat (path.c_str(), &stat_file);
190
191         return !e1;
192 }
193
194 void
195 MidiSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
196 {
197         set_timeline_position(start_frame);
198
199         if (_model) {
200                 _model->set_note_mode(mode);
201                 _model->start_write();
202         }
203
204         _last_write_end = start_frame;
205         _writing = true;
206 }
207
208 void
209 MidiSource::mark_streaming_write_started ()
210 {
211         sframes_t start_frame = _session.transport_frame();
212
213         if (_model) {
214                 _model->start_write();
215         }
216
217         _last_write_end = start_frame;
218         _writing = true;
219 }
220
221 void
222 MidiSource::mark_streaming_write_completed ()
223 {
224         if (_model) {
225                 _model->end_write(false);
226         }
227
228         _writing = false;
229 }
230
231 void
232 MidiSource::session_saved()
233 {
234         flush_midi();
235
236         if (_model && _model->edited()) {
237                 string newname;
238                 const string basename = PBD::basename_nosuffix(_name);
239                 string::size_type last_dash = basename.find_last_of("-");
240                 if (last_dash == string::npos || last_dash == basename.find_first_of("-")) {
241                         newname = basename + "-1";
242                 } else {
243                         stringstream ss(basename.substr(last_dash+1));
244                         unsigned write_count = 0;
245                         ss >> write_count;
246                         // cerr << "WRITE COUNT: " << write_count << endl;
247                         ++write_count; // start at 1
248                         ss.clear();
249                         ss << basename.substr(0, last_dash) << "-" << write_count;
250                         newname = ss.str();
251                 }
252
253                 string newpath = _session.session_directory().midi_path().to_string() +"/"+ newname + ".mid";
254
255                 boost::shared_ptr<MidiSource> newsrc = boost::dynamic_pointer_cast<MidiSource>(
256                                 SourceFactory::createWritable(DataType::MIDI, _session,
257                                                 newpath, true, false, _session.frame_rate()));
258
259                 newsrc->set_timeline_position(_timeline_position);
260                 _model->write_to(newsrc);
261
262                 // cyclic dependency here, ugly :(
263                 newsrc->set_model(_model);
264                 _model->set_midi_source(newsrc.get());
265
266                 newsrc->flush_midi();
267
268                 Switched.emit(newsrc);
269         }
270 }
271
272 void
273 MidiSource::set_note_mode(NoteMode mode)
274 {
275         if (_model) {
276                 _model->set_note_mode(mode);
277         }
278 }
279