Fix dropped MIDI events, especially with record enabled.
[ardour.git] / libs / ardour / midi_region.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18     $Id: midiregion.cc 746 2006-08-02 02:44:23Z drobilla $
19 */
20
21 #include <cmath>
22 #include <climits>
23 #include <cfloat>
24
25 #include <set>
26
27 #include <glibmm/threads.h>
28 #include <glibmm/fileutils.h>
29 #include <glibmm/miscutils.h>
30
31 #include "pbd/xml++.h"
32 #include "pbd/basename.h"
33
34 #include "ardour/automation_control.h"
35 #include "ardour/midi_model.h"
36 #include "ardour/midi_region.h"
37 #include "ardour/midi_ring_buffer.h"
38 #include "ardour/midi_source.h"
39 #include "ardour/region_factory.h"
40 #include "ardour/session.h"
41 #include "ardour/source_factory.h"
42 #include "ardour/tempo.h"
43 #include "ardour/types.h"
44
45 #include "i18n.h"
46 #include <locale.h>
47
48 using namespace std;
49 using namespace ARDOUR;
50 using namespace PBD;
51
52 namespace ARDOUR {
53         namespace Properties {
54                 PBD::PropertyDescriptor<void*>                midi_data;
55                 PBD::PropertyDescriptor<Evoral::MusicalTime>  start_beats;
56                 PBD::PropertyDescriptor<Evoral::MusicalTime>  length_beats;
57         }
58 }
59
60 void
61 MidiRegion::make_property_quarks ()
62 {
63         Properties::midi_data.property_id = g_quark_from_static_string (X_("midi-data"));
64         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for midi-data = %1\n", Properties::midi_data.property_id));
65         Properties::start_beats.property_id = g_quark_from_static_string (X_("start-beats"));
66         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for start-beats = %1\n", Properties::start_beats.property_id));
67         Properties::length_beats.property_id = g_quark_from_static_string (X_("length-beats"));
68         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for length-beats = %1\n", Properties::length_beats.property_id));
69 }
70
71 void
72 MidiRegion::register_properties ()
73 {
74         add_property (_start_beats);
75         add_property (_length_beats);
76 }
77
78 /* Basic MidiRegion constructor (many channels) */
79 MidiRegion::MidiRegion (const SourceList& srcs)
80         : Region (srcs)
81         , _start_beats (Properties::start_beats, 0)
82         , _length_beats (Properties::length_beats, midi_source(0)->length_beats())
83 {
84         register_properties ();
85
86         midi_source(0)->ModelChanged.connect_same_thread (_source_connection, boost::bind (&MidiRegion::model_changed, this));
87         model_changed ();
88         assert(_name.val().find("/") == string::npos);
89         assert(_type == DataType::MIDI);
90 }
91
92 MidiRegion::MidiRegion (boost::shared_ptr<const MidiRegion> other)
93         : Region (other)
94         , _start_beats (Properties::start_beats, other->_start_beats)
95         , _length_beats (Properties::length_beats, (Evoral::MusicalTime) 0)
96 {
97         update_length_beats ();
98         register_properties ();
99
100         assert(_name.val().find("/") == string::npos);
101         midi_source(0)->ModelChanged.connect_same_thread (_source_connection, boost::bind (&MidiRegion::model_changed, this));
102         model_changed ();
103 }
104
105 /** Create a new MidiRegion that is part of an existing one */
106 MidiRegion::MidiRegion (boost::shared_ptr<const MidiRegion> other, frameoffset_t offset)
107         : Region (other, offset)
108         , _start_beats (Properties::start_beats, (Evoral::MusicalTime) 0)
109         , _length_beats (Properties::length_beats, (Evoral::MusicalTime) 0)
110 {
111         BeatsFramesConverter bfc (_session.tempo_map(), _position);
112         Evoral::MusicalTime const offset_beats = bfc.from (offset);
113
114         _start_beats = other->_start_beats + offset_beats;
115         _length_beats = other->_length_beats - offset_beats;
116
117         register_properties ();
118
119         assert(_name.val().find("/") == string::npos);
120         midi_source(0)->ModelChanged.connect_same_thread (_source_connection, boost::bind (&MidiRegion::model_changed, this));
121         model_changed ();
122 }
123
124 MidiRegion::~MidiRegion ()
125 {
126 }
127
128 /** Create a new MidiRegion that has its own version of some/all of the Source used by another.
129  */
130 boost::shared_ptr<MidiRegion>
131 MidiRegion::clone (string path) const
132 {
133         boost::shared_ptr<MidiSource> newsrc;
134
135         /* caller must check for pre-existing file */
136         assert (!path.empty());
137         assert (!Glib::file_test (path, Glib::FILE_TEST_EXISTS));
138         newsrc = boost::dynamic_pointer_cast<MidiSource>(
139                 SourceFactory::createWritable(DataType::MIDI, _session,
140                                               path, false, _session.frame_rate()));
141         return clone (newsrc);
142 }
143
144 boost::shared_ptr<MidiRegion>
145 MidiRegion::clone (boost::shared_ptr<MidiSource> newsrc) const
146 {
147         BeatsFramesConverter bfc (_session.tempo_map(), _position);
148         Evoral::MusicalTime const bbegin = bfc.from (_start);
149         Evoral::MusicalTime const bend = bfc.from (_start + _length);
150
151         if (midi_source(0)->write_to (newsrc, bbegin, bend)) {
152                 return boost::shared_ptr<MidiRegion> ();
153         }
154
155         PropertyList plist;
156
157         plist.add (Properties::name, PBD::basename_nosuffix (newsrc->name()));
158         plist.add (Properties::whole_file, true);
159         plist.add (Properties::start, _start);
160         plist.add (Properties::start_beats, _start_beats);
161         plist.add (Properties::length, _length);
162         plist.add (Properties::length_beats, _length_beats);
163         plist.add (Properties::layer, 0);
164
165         return boost::dynamic_pointer_cast<MidiRegion> (RegionFactory::create (newsrc, plist, true));
166 }
167
168 void
169 MidiRegion::post_set (const PropertyChange& pc)
170 {
171         Region::post_set (pc);
172
173         if (pc.contains (Properties::length) && !pc.contains (Properties::length_beats)) {
174                 update_length_beats ();
175         } else if (pc.contains (Properties::start) && !pc.contains (Properties::start_beats)) {
176                 set_start_beats_from_start_frames ();
177         }
178 }
179
180 void
181 MidiRegion::set_start_beats_from_start_frames ()
182 {
183         BeatsFramesConverter c (_session.tempo_map(), _position - _start);
184         _start_beats = c.from (_start);
185 }
186
187 void
188 MidiRegion::set_length_internal (framecnt_t len)
189 {
190         Region::set_length_internal (len);
191         update_length_beats ();
192 }
193
194 void
195 MidiRegion::update_after_tempo_map_change ()
196 {
197         Region::update_after_tempo_map_change ();
198
199         /* _position has now been updated for the new tempo map */
200         _start = _position - _session.tempo_map().framepos_minus_beats (_position, _start_beats);
201
202         send_change (Properties::start);
203 }
204
205 void
206 MidiRegion::update_length_beats ()
207 {
208         BeatsFramesConverter converter (_session.tempo_map(), _position);
209         _length_beats = converter.from (_length);
210 }
211
212 void
213 MidiRegion::set_position_internal (framepos_t pos, bool allow_bbt_recompute)
214 {
215         Region::set_position_internal (pos, allow_bbt_recompute);
216         /* zero length regions don't exist - so if _length_beats is zero, this object
217            is under construction.
218         */
219         if (_length_beats) {
220                 /* leave _length_beats alone, and change _length to reflect the state of things
221                    at the new position (tempo map may dictate a different number of frames
222                 */
223                 BeatsFramesConverter converter (_session.tempo_map(), _position);
224                 Region::set_length_internal (converter.to (_length_beats));
225         }
226 }
227
228 framecnt_t
229 MidiRegion::read_at (Evoral::EventSink<framepos_t>& out, framepos_t position, framecnt_t dur, uint32_t chan_n, NoteMode mode, MidiStateTracker* tracker) const
230 {
231         return _read_at (_sources, out, position, dur, chan_n, mode, tracker);
232 }
233
234 framecnt_t
235 MidiRegion::master_read_at (MidiRingBuffer<framepos_t>& out, framepos_t position, framecnt_t dur, uint32_t chan_n, NoteMode mode) const
236 {
237         return _read_at (_master_sources, out, position, dur, chan_n, mode); /* no tracker */
238 }
239
240 framecnt_t
241 MidiRegion::_read_at (const SourceList& /*srcs*/, Evoral::EventSink<framepos_t>& dst, framepos_t position, framecnt_t dur, uint32_t chan_n,
242                       NoteMode mode, MidiStateTracker* tracker) const
243 {
244         frameoffset_t internal_offset = 0;
245         framecnt_t to_read         = 0;
246
247         /* precondition: caller has verified that we cover the desired section */
248
249         assert(chan_n == 0);
250
251         if (muted()) {
252                 return 0; /* read nothing */
253         }
254
255         if (position < _position) {
256                 /* we are starting the read from before the start of the region */
257                 internal_offset = 0;
258                 dur -= _position - position;
259         } else {
260                 /* we are starting the read from after the start of the region */
261                 internal_offset = position - _position;
262         }
263
264         if (internal_offset >= _length) {
265                 return 0; /* read nothing */
266         }
267
268         if ((to_read = min (dur, _length - internal_offset)) == 0) {
269                 return 0; /* read nothing */
270         }
271
272         boost::shared_ptr<MidiSource> src = midi_source(chan_n);
273         src->set_note_mode(mode);
274
275         /*
276           cerr << "MR " << name () << " read @ " << position << " * " << to_read
277           << " _position = " << _position
278           << " _start = " << _start
279           << " intoffset = " << internal_offset
280           << endl;
281         */
282
283         /* This call reads events from a source and writes them to `dst' timed in session frames */
284
285         if (src->midi_read (
286                         dst, // destination buffer
287                         _position - _start, // start position of the source in session frames
288                         _start + internal_offset, // where to start reading in the source
289                         to_read, // read duration in frames
290                         tracker,
291                         _filtered_parameters
292                     ) != to_read) {
293                 return 0; /* "read nothing" */
294         }
295
296         return to_read;
297 }
298
299 XMLNode&
300 MidiRegion::state ()
301 {
302         return Region::state ();
303 }
304
305 int
306 MidiRegion::set_state (const XMLNode& node, int version)
307 {
308         int ret = Region::set_state (node, version);
309
310         if (ret == 0) {
311                 update_length_beats ();
312         }
313
314         return ret;
315 }
316
317 void
318 MidiRegion::recompute_at_end ()
319 {
320         /* our length has changed
321          * so what? stuck notes are dealt with via a note state tracker
322          */
323 }
324
325 void
326 MidiRegion::recompute_at_start ()
327 {
328         /* as above, but the shift was from the front
329          * maybe bump currently active note's note-ons up so they sound here?
330          * that could be undesireable in certain situations though.. maybe
331          * remove the note entirely, including it's note off?  something needs to
332          * be done to keep the played MIDI sane to avoid messing up voices of
333          * polyhonic things etc........
334          */
335 }
336
337 int
338 MidiRegion::separate_by_channel (ARDOUR::Session&, vector< boost::shared_ptr<Region> >&) const
339 {
340         // TODO
341         return -1;
342 }
343
344 boost::shared_ptr<Evoral::Control>
345 MidiRegion::control (const Evoral::Parameter& id, bool create)
346 {
347         return model()->control(id, create);
348 }
349
350 boost::shared_ptr<const Evoral::Control>
351 MidiRegion::control (const Evoral::Parameter& id) const
352 {
353         return model()->control(id);
354 }
355
356 boost::shared_ptr<MidiModel>
357 MidiRegion::model()
358 {
359         return midi_source()->model();
360 }
361
362 boost::shared_ptr<const MidiModel>
363 MidiRegion::model() const
364 {
365         return midi_source()->model();
366 }
367
368 boost::shared_ptr<MidiSource>
369 MidiRegion::midi_source (uint32_t n) const
370 {
371         // Guaranteed to succeed (use a static cast?)
372         return boost::dynamic_pointer_cast<MidiSource>(source(n));
373 }
374
375 void
376 MidiRegion::model_changed ()
377 {
378         if (!model()) {
379                 return;
380         }
381
382         /* build list of filtered Parameters, being those whose automation state is not `Play' */
383
384         _filtered_parameters.clear ();
385
386         Automatable::Controls const & c = model()->controls();
387
388         for (Automatable::Controls::const_iterator i = c.begin(); i != c.end(); ++i) {
389                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (i->second);
390                 assert (ac);
391                 if (ac->alist()->automation_state() != Play) {
392                         _filtered_parameters.insert (ac->parameter ());
393                 }
394         }
395
396         /* watch for changes to controls' AutoState */
397         midi_source()->AutomationStateChanged.connect_same_thread (
398                 _model_connection, boost::bind (&MidiRegion::model_automation_state_changed, this, _1)
399                 );
400
401         model()->ContentsChanged.connect_same_thread (
402                 _model_contents_connection, boost::bind (&MidiRegion::model_contents_changed, this));
403 }
404
405 void
406 MidiRegion::model_contents_changed ()
407 {
408         send_change (PropertyChange (Properties::midi_data));
409 }
410
411 void
412 MidiRegion::model_automation_state_changed (Evoral::Parameter const & p)
413 {
414         /* Update our filtered parameters list after a change to a parameter's AutoState */
415
416         boost::shared_ptr<AutomationControl> ac = model()->automation_control (p);
417         if (!ac || ac->alist()->automation_state() == Play) {
418                 /* It should be "impossible" for ac to be NULL, but if it is, don't
419                    filter the parameter so events aren't lost. */
420                 _filtered_parameters.erase (p);
421         } else {
422                 _filtered_parameters.insert (p);
423         }
424 }
425
426 /** This is called when a trim drag has resulted in a -ve _start time for this region.
427  *  Fix it up by adding some empty space to the source.
428  */
429 void
430 MidiRegion::fix_negative_start ()
431 {
432         BeatsFramesConverter c (_session.tempo_map(), _position);
433
434         model()->insert_silence_at_start (c.from (-_start));
435         _start = 0;
436         _start_beats = 0;
437 }
438
439 /** Transpose the notes in this region by a given number of semitones */
440 void
441 MidiRegion::transpose (int semitones)
442 {
443         BeatsFramesConverter c (_session.tempo_map(), _start);
444         model()->transpose (c.from (_start), c.from (_start + _length), semitones);
445 }
446
447 void
448 MidiRegion::set_start_internal (framecnt_t s)
449 {
450         Region::set_start_internal (s);
451         set_start_beats_from_start_frames ();
452 }