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