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