Fix repeated linear search on read when cached model iterator reaches end.
[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         , _model_iterator_valid(true)
59         , _length_beats(0.0)
60         , _last_read_end(0)
61         , _last_write_end(0)
62 {
63 }
64
65 MidiSource::MidiSource (Session& s, const XMLNode& node)
66         : Source(s, node)
67         , _read_data_count(0)
68         , _write_data_count(0)
69         , _writing(false)
70         , _model_iterator_valid(true)
71         , _length_beats(0.0)
72         , _last_read_end(0)
73         , _last_write_end(0)
74 {
75         _read_data_count = 0;
76         _write_data_count = 0;
77
78         if (set_state (node, Stateful::loading_state_version)) {
79                 throw failed_constructor();
80         }
81 }
82
83 MidiSource::~MidiSource ()
84 {
85 }
86
87 XMLNode&
88 MidiSource::get_state ()
89 {
90         XMLNode& node (Source::get_state());
91
92         if (_captured_for.length()) {
93                 node.add_property ("captured-for", _captured_for);
94         }
95
96         return node;
97 }
98
99 int
100 MidiSource::set_state (const XMLNode& node, int /*version*/)
101 {
102         const XMLProperty* prop;
103
104         if ((prop = node.property ("captured-for")) != 0) {
105                 _captured_for = prop->value();
106         }
107
108         return 0;
109 }
110
111 sframes_t
112 MidiSource::length (sframes_t pos) const
113 {
114         BeatsFramesConverter converter(_session, pos);
115         return converter.to(_length_beats);
116 }
117
118 void
119 MidiSource::update_length (sframes_t /*pos*/, sframes_t /*cnt*/)
120 {
121         // You're not the boss of me!
122 }
123
124 void
125 MidiSource::invalidate ()
126 {
127         _model_iterator_valid = false;
128 }
129
130 nframes_t
131 MidiSource::midi_read (MidiRingBuffer<nframes_t>& dst, sframes_t source_start,
132                        sframes_t start, nframes_t cnt,
133                        sframes_t stamp_offset, sframes_t negative_stamp_offset,
134                        MidiStateTracker* tracker) const
135 {
136         Glib::Mutex::Lock lm (_lock);
137
138         BeatsFramesConverter converter(_session, source_start);
139
140         if (_model) {
141                 //cerr << "READ @ " << start << " * " << cnt << " (source @ " << source_start << " {" << endl;
142 #define BEATS_TO_FRAMES(t) (converter.to(t) + stamp_offset - negative_stamp_offset)
143
144                 Evoral::Sequence<double>::const_iterator& i = _model_iter;
145
146                 // If the cached iterator is invalid, search for the first event past start
147                 if (_last_read_end == 0 || start != _last_read_end || !_model_iterator_valid) {
148                         for (i = _model->begin(); i != _model->end(); ++i) {
149                                 if (BEATS_TO_FRAMES(i->time()) >= start) {
150                                         break;
151                                 }
152                         }
153                         _model_iterator_valid = true;
154                 }
155
156                 _last_read_end = start + cnt;
157
158                 // Read events up to source_start + start + cnt
159                 for (; i != _model->end(); ++i) {
160                         const sframes_t time_frames = BEATS_TO_FRAMES(i->time());
161                         //cerr << "Read? " << time_frames << " < " << source_start + start + cnt << endl;
162                         if (time_frames < source_start + start + cnt) {
163                                 //cerr << "Read @ " << time_frames << endl;
164                                 dst.write(time_frames, i->event_type(), i->size(), i->buffer());
165                                 if (tracker) {
166                                         Evoral::MIDIEvent<Evoral::MusicalTime>& ev (*(Evoral::MIDIEvent<Evoral::MusicalTime>*) (&(*i)));
167                                         if (ev.is_note_on()) {
168                                                 tracker->add (ev.note(), ev.channel());
169                                         } else if (ev.is_note_off()) {
170                                                 tracker->remove (ev.note(), ev.channel());
171                                         }
172                                 }
173                         } else {
174                                 //cerr << "End" << endl;
175                                 break;
176                         }
177                 }
178                 //cerr << "}" << endl;
179                 return cnt;
180         } else {
181                 return read_unlocked (dst, source_start, start, cnt, stamp_offset, negative_stamp_offset, tracker);
182         }
183 }
184
185 nframes_t
186 MidiSource::midi_write (MidiRingBuffer<nframes_t>& source, sframes_t source_start, nframes_t duration)
187 {
188         Glib::Mutex::Lock lm (_lock);
189         const nframes_t ret = write_unlocked (source, source_start, duration);
190         _last_write_end += duration;
191         return ret;
192 }
193
194 bool
195 MidiSource::file_changed (string path)
196 {
197         struct stat stat_file;
198
199         int e1 = stat (path.c_str(), &stat_file);
200
201         return !e1;
202 }
203
204 void
205 MidiSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
206 {
207         set_timeline_position(start_frame);
208
209         if (_model) {
210                 _model->set_note_mode(mode);
211                 _model->start_write();
212         }
213
214         _last_write_end = start_frame;
215         _writing = true;
216 }
217
218 void
219 MidiSource::mark_streaming_write_started ()
220 {
221         sframes_t start_frame = _session.transport_frame();
222
223         if (_model) {
224                 _model->start_write();
225         }
226
227         _last_write_end = start_frame;
228         _writing = true;
229 }
230
231 void
232 MidiSource::mark_streaming_write_completed ()
233 {
234         if (_model) {
235                 _model->end_write(false);
236         }
237
238         _writing = false;
239 }
240
241 void
242 MidiSource::session_saved()
243 {
244         flush_midi();
245
246         if (_model && _model->edited()) {
247                 string newname;
248                 const string basename = PBD::basename_nosuffix(_name);
249                 string::size_type last_dash = basename.find_last_of("-");
250                 if (last_dash == string::npos || last_dash == basename.find_first_of("-")) {
251                         newname = basename + "-1";
252                 } else {
253                         stringstream ss(basename.substr(last_dash+1));
254                         unsigned write_count = 0;
255                         ss >> write_count;
256                         // cerr << "WRITE COUNT: " << write_count << endl;
257                         ++write_count; // start at 1
258                         ss.clear();
259                         ss << basename.substr(0, last_dash) << "-" << write_count;
260                         newname = ss.str();
261                 }
262
263                 string newpath = _session.session_directory().midi_path().to_string() +"/"+ newname + ".mid";
264
265                 boost::shared_ptr<MidiSource> newsrc = boost::dynamic_pointer_cast<MidiSource>(
266                                 SourceFactory::createWritable(DataType::MIDI, _session,
267                                                 newpath, true, false, _session.frame_rate()));
268
269                 newsrc->set_timeline_position(_timeline_position);
270                 _model->write_to(newsrc);
271
272                 // cyclic dependency here, ugly :(
273                 newsrc->set_model(_model);
274                 _model->set_midi_source(newsrc.get());
275
276                 newsrc->flush_midi();
277
278                 Switched.emit(newsrc);
279         }
280 }
281
282 void
283 MidiSource::set_note_mode(NoteMode mode)
284 {
285         if (_model) {
286                 _model->set_note_mode(mode);
287         }
288 }
289