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