9f7c1e3baa2145f4e8d0dc547f0ab88de885705d
[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_iter_valid(false)
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_iter_valid(false)
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_iter_valid = false;
128         _model_iter.invalidate();
129 }
130
131 nframes_t
132 MidiSource::midi_read (MidiRingBuffer<nframes_t>& dst, sframes_t source_start,
133                        sframes_t start, nframes_t cnt,
134                        sframes_t stamp_offset, sframes_t negative_stamp_offset,
135                        MidiStateTracker* tracker) const
136 {
137         Glib::Mutex::Lock lm (_lock);
138
139         BeatsFramesConverter converter(_session, source_start);
140
141         if (_model) {
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_iter_valid) {
148                         for (i = _model->begin(); i != _model->end(); ++i) {
149                                 if (converter.to(i->time()) >= start) {
150                                         break;
151                                 }
152                         }
153                         _model_iter_valid = true;
154                 }
155
156                 _last_read_end = start + cnt;
157
158                 // Read events up to end
159                 for (; i != _model->end(); ++i) {
160                         const sframes_t time_frames = converter.to(i->time());
161                         if (time_frames < start + cnt) {
162                                 dst.write(time_frames + stamp_offset - negative_stamp_offset,
163                                                 i->event_type(), i->size(), i->buffer());
164                                 if (tracker) {
165                                         Evoral::MIDIEvent<Evoral::MusicalTime>& ev (*(Evoral::MIDIEvent<Evoral::MusicalTime>*) (&(*i)));
166                                         if (ev.is_note_on()) {
167                                                 tracker->add (ev.note(), ev.channel());
168                                         } else if (ev.is_note_off()) {
169                                                 tracker->remove (ev.note(), ev.channel());
170                                         }
171                                 }
172                         } else {
173                                 break;
174                         }
175                 }
176                 return cnt;
177         } else {
178                 return read_unlocked (dst, source_start, start, cnt, stamp_offset, negative_stamp_offset, tracker);
179         }
180 }
181
182 nframes_t
183 MidiSource::midi_write (MidiRingBuffer<nframes_t>& source, sframes_t source_start, nframes_t duration)
184 {
185         Glib::Mutex::Lock lm (_lock);
186         const nframes_t ret = write_unlocked (source, source_start, duration);
187         _last_write_end += duration;
188         return ret;
189 }
190
191 bool
192 MidiSource::file_changed (string path)
193 {
194         struct stat stat_file;
195
196         int e1 = stat (path.c_str(), &stat_file);
197
198         return !e1;
199 }
200
201 void
202 MidiSource::mark_streaming_midi_write_started (NoteMode mode, sframes_t start_frame)
203 {
204         set_timeline_position(start_frame);
205
206         if (_model) {
207                 _model->set_note_mode(mode);
208                 _model->start_write();
209         }
210
211         _last_write_end = start_frame;
212         _writing = true;
213 }
214
215 void
216 MidiSource::mark_streaming_write_started ()
217 {
218         NoteMode note_mode = _model ? _model->note_mode() : Sustained;
219         mark_streaming_midi_write_started(note_mode, _session.transport_frame());
220 }
221
222 void
223 MidiSource::mark_streaming_write_completed ()
224 {
225         if (_model) {
226                 _model->end_write(false);
227         }
228
229         _writing = false;
230 }
231
232 void
233 MidiSource::session_saved()
234 {
235         flush_midi();
236
237         if (_model && _model->edited()) {
238                 string newname;
239                 const string basename = PBD::basename_nosuffix(_name);
240                 string::size_type last_dash = basename.find_last_of("-");
241                 if (last_dash == string::npos || last_dash == basename.find_first_of("-")) {
242                         newname = basename + "-1";
243                 } else {
244                         stringstream ss(basename.substr(last_dash+1));
245                         unsigned write_count = 0;
246                         ss >> write_count;
247                         // cerr << "WRITE COUNT: " << write_count << endl;
248                         ++write_count; // start at 1
249                         ss.clear();
250                         ss << basename.substr(0, last_dash) << "-" << write_count;
251                         newname = ss.str();
252                 }
253
254                 string newpath = _session.session_directory().midi_path().to_string() +"/"+ newname + ".mid";
255
256                 boost::shared_ptr<MidiSource> newsrc = boost::dynamic_pointer_cast<MidiSource>(
257                                 SourceFactory::createWritable(DataType::MIDI, _session,
258                                                 newpath, true, false, _session.frame_rate()));
259
260                 newsrc->set_timeline_position(_timeline_position);
261                 _model->write_to(newsrc);
262
263                 // cyclic dependency here, ugly :(
264                 newsrc->set_model(_model);
265                 _model->set_midi_source(newsrc.get());
266
267                 newsrc->flush_midi();
268
269                 Switched.emit(newsrc);
270         }
271 }
272
273 void
274 MidiSource::set_note_mode(NoteMode mode)
275 {
276         if (_model) {
277                 _model->set_note_mode(mode);
278         }
279 }
280