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