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