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