bd0319f2bd1d6779a3ffffd6fbcbfeb7cb1fc8a6
[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, other->_length_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, const int32_t& sub_num)
106         : Region (other, offset, sub_num)
107         , _start_beats (Properties::start_beats, Evoral::Beats())
108         , _length_beats (Properties::length_beats, other->_length_beats)
109 {
110         _start_beats = Evoral::Beats (_session.tempo_map().exact_beat_at_frame ((other->_position + offset), sub_num) - other->beat()) + other->_start_beats;
111         update_length_beats (sub_num);
112         register_properties ();
113
114         assert(_name.val().find("/") == string::npos);
115         midi_source(0)->ModelChanged.connect_same_thread (_source_connection, boost::bind (&MidiRegion::model_changed, this));
116         model_changed ();
117 }
118
119 MidiRegion::~MidiRegion ()
120 {
121 }
122
123 /** Create a new MidiRegion that has its own version of some/all of the Source used by another.
124  */
125 boost::shared_ptr<MidiRegion>
126 MidiRegion::clone (string path) const
127 {
128         boost::shared_ptr<MidiSource> newsrc;
129
130         /* caller must check for pre-existing file */
131         assert (!path.empty());
132         assert (!Glib::file_test (path, Glib::FILE_TEST_EXISTS));
133         newsrc = boost::dynamic_pointer_cast<MidiSource>(
134                 SourceFactory::createWritable(DataType::MIDI, _session,
135                                               path, false, _session.frame_rate()));
136         return clone (newsrc);
137 }
138
139 boost::shared_ptr<MidiRegion>
140 MidiRegion::clone (boost::shared_ptr<MidiSource> newsrc) const
141 {
142         BeatsFramesConverter bfc (_session.tempo_map(), _position);
143         Evoral::Beats const bbegin = bfc.from (_start);
144         Evoral::Beats const bend = bfc.from (_start + _length);
145
146         {
147                 /* Lock our source since we'll be reading from it.  write_to() will
148                    take a lock on newsrc. */
149                 Source::Lock lm (midi_source(0)->mutex());
150                 if (midi_source(0)->write_to (lm, newsrc, bbegin, bend)) {
151                         return boost::shared_ptr<MidiRegion> ();
152                 }
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         boost::shared_ptr<MidiRegion> ret (boost::dynamic_pointer_cast<MidiRegion> (RegionFactory::create (newsrc, plist, true)));
166         ret->set_beat (beat());
167
168         return ret;
169 }
170
171 void
172 MidiRegion::post_set (const PropertyChange& pc)
173 {
174         Region::post_set (pc);
175
176         if (pc.contains (Properties::length) && !pc.contains (Properties::length_beats)) {
177                 /* update non-musically */
178                 update_length_beats (0);
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         _start_beats = Evoral::Beats (beat() - _session.tempo_map().beat_at_frame (_position - _start));
188 }
189
190 void
191 MidiRegion::set_length_internal (framecnt_t len, const int32_t& sub_num)
192 {
193         Region::set_length_internal (len, sub_num);
194         update_length_beats (sub_num);
195 }
196
197 void
198 MidiRegion::update_after_tempo_map_change (bool /* send */)
199 {
200         const framepos_t old_pos = _position;
201         const framepos_t old_length = _length;
202         const framepos_t old_start = _start;
203
204         Region::update_after_tempo_map_change (false);
205
206         /* _start has now been updated. */
207         _length = _session.tempo_map().frame_at_beat (beat() + _length_beats.val().to_double()) - _position;
208
209         PropertyChange s_and_l;
210         if (old_start != _start) {
211                 s_and_l.add (Properties::start);
212         }
213         if (old_length != _length) {
214                 s_and_l.add (Properties::length);
215         }
216         if (old_pos != _position) {
217                 s_and_l.add (Properties::position);
218         }
219
220         send_change (s_and_l);
221 }
222
223 void
224 MidiRegion::update_length_beats (const int32_t& sub_num)
225 {
226         _length_beats = Evoral::Beats (_session.tempo_map().exact_beat_at_frame (_position + _length, sub_num) - beat());
227 }
228
229 void
230 MidiRegion::set_position_internal (framepos_t pos, bool allow_bbt_recompute, const int32_t& sub_num)
231 {
232         Region::set_position_internal (pos, allow_bbt_recompute, sub_num);
233
234         /* set _start to new position in tempo map */
235         _start = _position - _session.tempo_map().frame_at_beat (beat() - _start_beats.val().to_double());
236
237         /* leave _length_beats alone, and change _length to reflect the state of things
238            at the new position (tempo map may dictate a different number of frames).
239         */
240         Region::set_length_internal (_session.tempo_map().frame_at_beat (beat() + _length_beats.val().to_double()) - _position, sub_num);
241 }
242
243 framecnt_t
244 MidiRegion::read_at (Evoral::EventSink<framepos_t>& out,
245                      framepos_t                     position,
246                      framecnt_t                     dur,
247                      uint32_t                       chan_n,
248                      NoteMode                       mode,
249                      MidiStateTracker*              tracker,
250                      MidiChannelFilter*             filter) const
251 {
252         return _read_at (_sources, out, position, dur, chan_n, mode, tracker, filter);
253 }
254
255 framecnt_t
256 MidiRegion::master_read_at (MidiRingBuffer<framepos_t>& out, framepos_t position, framecnt_t dur, uint32_t chan_n, NoteMode mode) const
257 {
258         return _read_at (_master_sources, out, position, dur, chan_n, mode); /* no tracker */
259 }
260
261 framecnt_t
262 MidiRegion::_read_at (const SourceList&              /*srcs*/,
263                       Evoral::EventSink<framepos_t>& dst,
264                       framepos_t                     position,
265                       framecnt_t                     dur,
266                       uint32_t                       chan_n,
267                       NoteMode                       mode,
268                       MidiStateTracker*              tracker,
269                       MidiChannelFilter*             filter) const
270 {
271         frameoffset_t internal_offset = 0;
272         framecnt_t    to_read         = 0;
273
274         /* precondition: caller has verified that we cover the desired section */
275
276         assert(chan_n == 0);
277
278         if (muted()) {
279                 return 0; /* read nothing */
280         }
281
282         if (position < _position) {
283                 /* we are starting the read from before the start of the region */
284                 internal_offset = 0;
285                 dur -= _position - position;
286         } else {
287                 /* we are starting the read from after the start of the region */
288                 internal_offset = position - _position;
289         }
290
291         if (internal_offset >= _length) {
292                 return 0; /* read nothing */
293         }
294
295         if ((to_read = min (dur, _length - internal_offset)) == 0) {
296                 return 0; /* read nothing */
297         }
298
299         boost::shared_ptr<MidiSource> src = midi_source(chan_n);
300
301         Glib::Threads::Mutex::Lock lm(src->mutex());
302
303         src->set_note_mode(lm, mode);
304
305         /*
306           cerr << "MR " << name () << " read @ " << position << " * " << to_read
307           << " _position = " << _position
308           << " _start = " << _start
309           << " intoffset = " << internal_offset
310           << endl;
311         */
312
313         /* This call reads events from a source and writes them to `dst' timed in session frames */
314
315         if (src->midi_read (
316                     lm, // source lock
317                         dst, // destination buffer
318                         _position - _start, // start position of the source in session frames
319                         _start + internal_offset, // where to start reading in the source
320                         to_read, // read duration in frames
321                         tracker,
322                         filter,
323                         _filtered_parameters
324                     ) != to_read) {
325                 return 0; /* "read nothing" */
326         }
327
328         return to_read;
329 }
330
331 XMLNode&
332 MidiRegion::state ()
333 {
334         return Region::state ();
335 }
336
337 int
338 MidiRegion::set_state (const XMLNode& node, int version)
339 {
340         int ret = Region::set_state (node, version);
341
342         if (ret == 0) {
343                 /* set length beats to the frame (non-musical) */
344                 if (position_lock_style() == AudioTime) {
345                         update_length_beats (0);
346                 }
347         }
348
349         return ret;
350 }
351
352 void
353 MidiRegion::recompute_at_end ()
354 {
355         /* our length has changed
356          * so what? stuck notes are dealt with via a note state tracker
357          */
358 }
359
360 void
361 MidiRegion::recompute_at_start ()
362 {
363         /* as above, but the shift was from the front
364          * maybe bump currently active note's note-ons up so they sound here?
365          * that could be undesireable in certain situations though.. maybe
366          * remove the note entirely, including it's note off?  something needs to
367          * be done to keep the played MIDI sane to avoid messing up voices of
368          * polyhonic things etc........
369          */
370 }
371
372 int
373 MidiRegion::separate_by_channel (ARDOUR::Session&, vector< boost::shared_ptr<Region> >&) const
374 {
375         // TODO
376         return -1;
377 }
378
379 boost::shared_ptr<Evoral::Control>
380 MidiRegion::control (const Evoral::Parameter& id, bool create)
381 {
382         return model()->control(id, create);
383 }
384
385 boost::shared_ptr<const Evoral::Control>
386 MidiRegion::control (const Evoral::Parameter& id) const
387 {
388         return model()->control(id);
389 }
390
391 boost::shared_ptr<MidiModel>
392 MidiRegion::model()
393 {
394         return midi_source()->model();
395 }
396
397 boost::shared_ptr<const MidiModel>
398 MidiRegion::model() const
399 {
400         return midi_source()->model();
401 }
402
403 boost::shared_ptr<MidiSource>
404 MidiRegion::midi_source (uint32_t n) const
405 {
406         // Guaranteed to succeed (use a static cast?)
407         return boost::dynamic_pointer_cast<MidiSource>(source(n));
408 }
409
410 void
411 MidiRegion::model_changed ()
412 {
413         if (!model()) {
414                 return;
415         }
416
417         /* build list of filtered Parameters, being those whose automation state is not `Play' */
418
419         _filtered_parameters.clear ();
420
421         Automatable::Controls const & c = model()->controls();
422
423         for (Automatable::Controls::const_iterator i = c.begin(); i != c.end(); ++i) {
424                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl> (i->second);
425                 assert (ac);
426                 if (ac->alist()->automation_state() != Play) {
427                         _filtered_parameters.insert (ac->parameter ());
428                 }
429         }
430
431         /* watch for changes to controls' AutoState */
432         midi_source()->AutomationStateChanged.connect_same_thread (
433                 _model_connection, boost::bind (&MidiRegion::model_automation_state_changed, this, _1)
434                 );
435 }
436
437 void
438 MidiRegion::model_automation_state_changed (Evoral::Parameter const & p)
439 {
440         /* Update our filtered parameters list after a change to a parameter's AutoState */
441
442         boost::shared_ptr<AutomationControl> ac = model()->automation_control (p);
443         if (!ac || ac->alist()->automation_state() == Play) {
444                 /* It should be "impossible" for ac to be NULL, but if it is, don't
445                    filter the parameter so events aren't lost. */
446                 _filtered_parameters.erase (p);
447         } else {
448                 _filtered_parameters.insert (p);
449         }
450
451         /* the source will have an iterator into the model, and that iterator will have been set up
452            for a given set of filtered_parameters, so now that we've changed that list we must invalidate
453            the iterator.
454         */
455         Glib::Threads::Mutex::Lock lm (midi_source(0)->mutex(), Glib::Threads::TRY_LOCK);
456         if (lm.locked()) {
457                 /* TODO: This is too aggressive, we need more fine-grained invalidation. */
458                 midi_source(0)->invalidate (lm);
459         }
460 }
461
462 /** This is called when a trim drag has resulted in a -ve _start time for this region.
463  *  Fix it up by adding some empty space to the source.
464  */
465 void
466 MidiRegion::fix_negative_start ()
467 {
468         BeatsFramesConverter c (_session.tempo_map(), _position);
469
470         model()->insert_silence_at_start (c.from (-_start));
471         _start = 0;
472         _start_beats = Evoral::Beats();
473 }
474
475 void
476 MidiRegion::set_start_internal (framecnt_t s, const int32_t& sub_num)
477 {
478         Region::set_start_internal (s, sub_num);
479
480         if (position_lock_style() == AudioTime) {
481                 set_start_beats_from_start_frames ();
482         }
483 }
484
485 void
486 MidiRegion::trim_to_internal (framepos_t position, framecnt_t length, const int32_t& sub_num)
487 {
488         framepos_t new_start;
489
490         if (locked()) {
491                 return;
492         }
493
494         PropertyChange what_changed;
495
496         /* beat has not been set by set_position_internal */
497         const double beat_delta = _session.tempo_map().exact_beat_at_frame (position, sub_num) - beat();
498
499         /* Set position before length, otherwise for MIDI regions this bad thing happens:
500          * 1. we call set_length_internal; length in beats is computed using the region's current
501          *    (soon-to-be old) position
502          * 2. we call set_position_internal; position is set and length in frames re-computed using
503          *    length in beats from (1) but at the new position, which is wrong if the region
504          *    straddles a tempo/meter change.
505          */
506
507         if (_position != position) {
508                 set_position_internal (position, true, sub_num);
509                 what_changed.add (Properties::position);
510         }
511
512         const double new_beat = _session.tempo_map().exact_beat_at_frame (position, sub_num);
513         const double new_start_beat = _start_beats.val().to_double() + beat_delta;
514
515         new_start = _position - _session.tempo_map().frame_at_beat (new_beat - new_start_beat);
516
517         if (!verify_start_and_length (new_start, length)) {
518                 return;
519         }
520
521         if (_start != new_start) {
522                 _start_beats = Evoral::Beats (new_start_beat);
523                 what_changed.add (Properties::start_beats);
524
525                 set_start_internal (new_start, sub_num);
526                 what_changed.add (Properties::start);
527         }
528
529         if (_length != length) {
530                 set_length_internal (length, sub_num);
531                 what_changed.add (Properties::length);
532                 what_changed.add (Properties::length_beats);
533         }
534
535         set_whole_file (false);
536
537         PropertyChange start_and_length;
538
539         start_and_length.add (Properties::start);
540         start_and_length.add (Properties::length);
541
542         if (what_changed.contains (start_and_length)) {
543                 first_edit ();
544         }
545
546         if (!what_changed.empty()) {
547                 send_change (what_changed);
548         }
549 }