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