f7294d8e3b2ac3443c27c4aff92142a261bd7f34
[ardour.git] / libs / ardour / midi_track.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Author: David Robillard
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19 #include <cmath>
20
21 #ifdef COMPILER_MSVC
22 #include <float.h>
23
24 // 'std::isinf()' and 'std::isnan()' are not available in MSVC.
25 #define isinf_local(val) !((bool)_finite((double)val))
26 #define isnan_local(val) (bool)_isnan((double)val)
27 #else
28 #define isinf_local std::isinf
29 #define isnan_local std::isnan
30 #endif
31
32 #include "pbd/ffs.h"
33 #include "pbd/enumwriter.h"
34 #include "pbd/convert.h"
35 #include "evoral/midi_util.h"
36
37 #include "ardour/buffer_set.h"
38 #include "ardour/debug.h"
39 #include "ardour/delivery.h"
40 #include "ardour/meter.h"
41 #include "ardour/midi_diskstream.h"
42 #include "ardour/midi_playlist.h"
43 #include "ardour/midi_port.h"
44 #include "ardour/midi_track.h"
45 #include "ardour/parameter_types.h"
46 #include "ardour/port.h"
47 #include "ardour/processor.h"
48 #include "ardour/session.h"
49 #include "ardour/session_playlists.h"
50 #include "ardour/utils.h"
51
52 #include "i18n.h"
53
54 namespace ARDOUR {
55 class InterThreadInfo;
56 class MidiSource;
57 class Region;
58 class SMFSource;
59 }
60
61 using namespace std;
62 using namespace ARDOUR;
63 using namespace PBD;
64
65 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
66         : Track (sess, name, flag, mode, DataType::MIDI)
67         , _immediate_events(1024) // FIXME: size?
68         , _step_edit_ring_buffer(64) // FIXME: size?
69         , _note_mode(Sustained)
70         , _step_editing (false)
71         , _input_active (true)
72         , _playback_channel_mask(0x0000ffff)
73         , _capture_channel_mask(0x0000ffff)
74 {
75 }
76
77 MidiTrack::~MidiTrack ()
78 {
79 }
80
81 int
82 MidiTrack::init ()
83 {
84         if (Track::init ()) {
85                 return -1;
86         }
87
88         _input->changed.connect_same_thread (*this, boost::bind (&MidiTrack::track_input_active, this, _1, _2));
89
90         return 0;
91 }
92
93 boost::shared_ptr<Diskstream>
94 MidiTrack::create_diskstream ()
95 {
96         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (MidiDiskstream::Recordable);
97
98         assert(_mode != Destructive);
99
100         return boost::shared_ptr<Diskstream> (new MidiDiskstream (_session, name(), dflags));
101 }
102
103
104 void
105 MidiTrack::set_record_enabled (bool yn, void *src)
106 {
107         if (_step_editing) {
108                 return;
109         }
110
111         Track::set_record_enabled (yn, src);
112 }
113
114 void
115 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
116 {
117         /* We have to do this here, as Track::set_diskstream will cause a buffer refill,
118            and the diskstream must be set up to fill its buffers using the correct _note_mode.
119         */
120         boost::shared_ptr<MidiDiskstream> mds = boost::dynamic_pointer_cast<MidiDiskstream> (ds);
121         mds->set_note_mode (_note_mode);
122         
123         Track::set_diskstream (ds);
124
125         mds->reset_tracker ();  
126
127         _diskstream->set_track (this);
128         _diskstream->set_destructive (_mode == Destructive);
129         _diskstream->set_record_enabled (false);
130
131         _diskstream_data_recorded_connection.disconnect ();
132         mds->DataRecorded.connect_same_thread (
133                 _diskstream_data_recorded_connection,
134                 boost::bind (&MidiTrack::diskstream_data_recorded, this, _1));
135
136         DiskstreamChanged (); /* EMIT SIGNAL */
137 }
138
139 boost::shared_ptr<MidiDiskstream>
140 MidiTrack::midi_diskstream() const
141 {
142         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
143 }
144
145 int
146 MidiTrack::set_state (const XMLNode& node, int version)
147 {
148         const XMLProperty *prop;
149
150         /* This must happen before Track::set_state(), as there will be a buffer
151            fill during that call, and we must fill buffers using the correct
152            _note_mode.
153         */
154         if ((prop = node.property (X_("note-mode"))) != 0) {
155                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
156         } else {
157                 _note_mode = Sustained;
158         }
159
160         if (Track::set_state (node, version)) {
161                 return -1;
162         }
163
164         // No destructive MIDI tracks (yet?)
165         _mode = Normal;
166
167         if ((prop = node.property ("input-active")) != 0) {
168                 set_input_active (string_is_affirmative (prop->value()));
169         }
170
171         ChannelMode playback_channel_mode = AllChannels;
172         ChannelMode capture_channel_mode = AllChannels;
173
174         if ((prop = node.property ("playback-channel-mode")) != 0) {
175                 playback_channel_mode = ChannelMode (string_2_enum(prop->value(), playback_channel_mode));
176         }
177         if ((prop = node.property ("capture-channel-mode")) != 0) {
178                 capture_channel_mode = ChannelMode (string_2_enum(prop->value(), capture_channel_mode));
179         }
180         if ((prop = node.property ("channel-mode")) != 0) {
181                 /* 3.0 behaviour where capture and playback modes were not separated */
182                 playback_channel_mode = ChannelMode (string_2_enum(prop->value(), playback_channel_mode));
183                 capture_channel_mode = playback_channel_mode;
184         }
185
186         unsigned int playback_channel_mask = 0xffff;
187         unsigned int capture_channel_mask = 0xffff;
188
189         if ((prop = node.property ("playback-channel-mask")) != 0) {
190                 sscanf (prop->value().c_str(), "0x%x", &playback_channel_mask);
191         }
192         if ((prop = node.property ("capture-channel-mask")) != 0) {
193                 sscanf (prop->value().c_str(), "0x%x", &capture_channel_mask);
194         }
195         if ((prop = node.property ("channel-mask")) != 0) {
196                 sscanf (prop->value().c_str(), "0x%x", &playback_channel_mask);
197                 capture_channel_mask = playback_channel_mask;
198         }
199
200         set_playback_channel_mode (playback_channel_mode, playback_channel_mask);
201         set_capture_channel_mode (capture_channel_mode, capture_channel_mask);
202
203         pending_state = const_cast<XMLNode*> (&node);
204
205         if (_session.state_of_the_state() & Session::Loading) {
206                 _session.StateReady.connect_same_thread (
207                         *this, boost::bind (&MidiTrack::set_state_part_two, this));
208         } else {
209                 set_state_part_two ();
210         }
211
212         return 0;
213 }
214
215 XMLNode&
216 MidiTrack::state(bool full_state)
217 {
218         XMLNode& root (Track::state(full_state));
219         XMLNode* freeze_node;
220         char buf[64];
221
222         if (_freeze_record.playlist) {
223                 XMLNode* inode;
224
225                 freeze_node = new XMLNode (X_("freeze-info"));
226                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
227                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
228
229                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
230                         inode = new XMLNode (X_("processor"));
231                         (*i)->id.print (buf, sizeof(buf));
232                         inode->add_property (X_("id"), buf);
233                         inode->add_child_copy ((*i)->state);
234
235                         freeze_node->add_child_nocopy (*inode);
236                 }
237
238                 root.add_child_nocopy (*freeze_node);
239         }
240
241         root.add_property("playback_channel-mode", enum_2_string(get_playback_channel_mode()));
242         root.add_property("capture_channel-mode", enum_2_string(get_capture_channel_mode()));
243         snprintf (buf, sizeof(buf), "0x%x", get_playback_channel_mask());
244         root.add_property("playback-channel-mask", buf);
245         snprintf (buf, sizeof(buf), "0x%x", get_capture_channel_mask());
246         root.add_property("capture-channel-mask", buf);
247
248         root.add_property ("note-mode", enum_2_string (_note_mode));
249         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
250         root.add_property ("input-active", (_input_active ? "yes" : "no"));
251
252         return root;
253 }
254
255 void
256 MidiTrack::set_state_part_two ()
257 {
258         XMLNode* fnode;
259         XMLProperty* prop;
260         LocaleGuard lg (X_("POSIX"));
261
262         /* This is called after all session state has been restored but before
263            have been made ports and connections are established.
264         */
265
266         if (pending_state == 0) {
267                 return;
268         }
269
270         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
271
272                 _freeze_record.state = Frozen;
273
274                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
275                         delete *i;
276                 }
277                 _freeze_record.processor_info.clear ();
278
279                 if ((prop = fnode->property (X_("playlist"))) != 0) {
280                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
281                         if (pl) {
282                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
283                         } else {
284                                 _freeze_record.playlist.reset();
285                                 _freeze_record.state = NoFreeze;
286                         return;
287                         }
288                 }
289
290                 if ((prop = fnode->property (X_("state"))) != 0) {
291                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
292                 }
293
294                 XMLNodeConstIterator citer;
295                 XMLNodeList clist = fnode->children();
296
297                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
298                         if ((*citer)->name() != X_("processor")) {
299                                 continue;
300                         }
301
302                         if ((prop = (*citer)->property (X_("id"))) == 0) {
303                                 continue;
304                         }
305
306                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
307                                                                                    boost::shared_ptr<Processor>());
308                         frii->id = prop->value ();
309                         _freeze_record.processor_info.push_back (frii);
310                 }
311         }
312
313         if (midi_diskstream ()) {
314                 midi_diskstream()->set_block_size (_session.get_block_size ());
315         }
316
317         return;
318 }
319
320 /** @param need_butler to be set to true if this track now needs the butler, otherwise it can be left alone
321  *  or set to false.
322  */
323 int
324 MidiTrack::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
325 {
326         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
327         if (!lm.locked()) {
328                 boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
329                 framecnt_t playback_distance = diskstream->calculate_playback_distance(nframes);
330                 if (can_internal_playback_seek(llabs(playback_distance))) {
331                         /* TODO should declick, and/or note-off */
332                         internal_playback_seek(playback_distance);
333                 }
334                 return 0;
335         }
336
337         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
338
339         if (n_outputs().n_total() == 0 && _processors.empty()) {
340                 return 0;
341         }
342
343         if (!_active) {
344                 silence (nframes);
345                 if (_meter_point == MeterInput && (_monitoring & MonitorInput || _diskstream->record_enabled())) {
346                         _meter->reset();
347                 }
348                 return 0;
349         }
350
351         framepos_t transport_frame = _session.transport_frame();
352
353         int dret;
354         framecnt_t playback_distance;
355
356         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
357                 /* need to do this so that the diskstream sets its
358                    playback distance to zero, thus causing diskstream::commit
359                    to do nothing.
360                    */
361                 BufferSet bufs; /* empty set - is OK, since nothing will happen */
362
363                 dret = diskstream->process (bufs, transport_frame, 0, playback_distance, false);
364                 need_butler = diskstream->commit (playback_distance);
365                 return dret;
366         }
367
368         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
369
370         fill_buffers_with_input (bufs, _input, nframes);
371
372         if (_meter_point == MeterInput && (_monitoring & MonitorInput || _diskstream->record_enabled())) {
373                 _meter->run (bufs, start_frame, end_frame, nframes, true);
374         }
375
376         /* filter captured data before the diskstream sees it */
377
378         filter_channels (bufs, get_capture_channel_mode(), get_capture_channel_mask());
379
380         _silent = false;
381
382         if ((dret = diskstream->process (bufs, transport_frame, nframes, playback_distance, (monitoring_state() == MonitoringDisk))) != 0) {
383                 need_butler = diskstream->commit (playback_distance);
384                 silence (nframes);
385                 return dret;
386         }
387
388         /* filter playback data before we do anything else */
389         
390         filter_channels (bufs, get_playback_channel_mode(), get_playback_channel_mask ());
391
392         if (monitoring_state() == MonitoringInput) {
393
394                 /* not actually recording, but we want to hear the input material anyway,
395                    at least potentially (depending on monitoring options)
396                 */
397
398                 /* because the playback buffer is event based and not a
399                  * continuous stream, we need to make sure that we empty
400                  * it of events every cycle to avoid it filling up with events
401                  * read from disk, while we are actually monitoring input
402                  */
403
404                 diskstream->flush_playback (start_frame, end_frame);
405
406         } 
407
408         
409         /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
410         
411         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
412         
413         /* final argument: don't waste time with automation if we're not recording or rolling */
414         
415         process_output_buffers (bufs, start_frame, end_frame, nframes,
416                                 declick, (!diskstream->record_enabled() && !_session.transport_stopped()));
417
418         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
419                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
420                 if (d) {
421                         d->flush_buffers (nframes);
422                 }
423         }
424
425         need_butler = diskstream->commit (playback_distance);
426         
427         return 0;
428 }
429
430 int
431 MidiTrack::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool state_changing)
432 {
433         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing);
434
435         if (ret == 0 && _step_editing) {
436                 push_midi_input_to_step_edit_ringbuffer (nframes);
437         }
438
439         return ret;
440 }
441
442 void
443 MidiTrack::realtime_locate ()
444 {
445         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
446
447         if (!lm.locked ()) {
448                 return;
449         }
450
451         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
452                 (*i)->realtime_locate ();
453         }
454
455         midi_diskstream()->reset_tracker ();
456 }
457
458 void
459 MidiTrack::realtime_handle_transport_stopped ()
460 {
461         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
462
463         if (!lm.locked ()) {
464                 return;
465         }
466
467         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
468                 (*i)->realtime_handle_transport_stopped ();
469         }
470 }
471
472 void
473 MidiTrack::push_midi_input_to_step_edit_ringbuffer (framecnt_t nframes)
474 {
475         PortSet& ports (_input->ports());
476
477         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
478
479                 Buffer& b (p->get_buffer (nframes));
480                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
481                 assert (mb);
482
483                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
484
485                         const Evoral::MIDIEvent<framepos_t> ev(*e, false);
486
487                         /* note on, since for step edit, note length is determined
488                            elsewhere
489                         */
490
491                         if (ev.is_note_on()) {
492                                 /* we don't care about the time for this purpose */
493                                 _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
494                         }
495                 }
496         }
497 }
498
499 void 
500 MidiTrack::filter_channels (BufferSet& bufs, ChannelMode mode, uint32_t mask)
501 {
502         if (mode == AllChannels) {
503                 return;
504         }
505
506         MidiBuffer& buf (bufs.get_midi (0));
507         
508         for (MidiBuffer::iterator e = buf.begin(); e != buf.end(); ) {
509                 
510                 Evoral::MIDIEvent<framepos_t> ev(*e, false);
511
512                 if (ev.is_channel_event()) {
513                         switch (mode) {
514                         case FilterChannels:
515                                 if (0 == ((1<<ev.channel()) & mask)) {
516                                         e = buf.erase (e);
517                                 } else {
518                                         ++e;
519                                 }
520                                 break;
521                         case ForceChannel:
522                                 ev.set_channel (PBD::ffs (mask) - 1);
523                                 ++e;
524                                 break;
525                         case AllChannels:
526                                 /* handled by the opening if() */
527                                 ++e;
528                                 break;
529                         }
530                 } else {
531                         ++e;
532                 }
533         }
534 }
535
536 void
537 MidiTrack::write_out_of_band_data (BufferSet& bufs, framepos_t /*start*/, framepos_t /*end*/, framecnt_t nframes)
538 {
539         MidiBuffer& buf (bufs.get_midi (0));
540
541         // Append immediate events
542
543         if (_immediate_events.read_space()) {
544
545                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 has %2 of immediate events to deliver\n",
546                                                             name(), _immediate_events.read_space()));
547
548                 /* write as many of the immediate events as we can, but give "true" as
549                  * the last argument ("stop on overflow in destination") so that we'll
550                  * ship the rest out next time.
551                  *
552                  * the Port::port_offset() + (nframes-1) argument puts all these events at the last
553                  * possible position of the output buffer, so that we do not
554                  * violate monotonicity when writing. Port::port_offset() will
555                  * be non-zero if we're in a split process cycle.
556                  */
557                 _immediate_events.read (buf, 0, 1, Port::port_offset() + nframes - 1, true);
558         }
559 }
560
561 int
562 MidiTrack::export_stuff (BufferSet& /*bufs*/, framepos_t /*start_frame*/, framecnt_t /*nframes*/, 
563                          boost::shared_ptr<Processor> /*endpoint*/, bool /*include_endpoint*/, bool /*for_export*/, bool /*for_freeze*/)
564 {
565         return -1;
566 }
567
568 boost::shared_ptr<Region>
569 MidiTrack::bounce (InterThreadInfo& /*itt*/)
570 {
571         std::cerr << "MIDI bounce currently unsupported" << std::endl;
572         return boost::shared_ptr<Region> ();
573 }
574
575
576 boost::shared_ptr<Region>
577 MidiTrack::bounce_range (framepos_t /*start*/, framepos_t /*end*/, InterThreadInfo& /*itt*/,
578                          boost::shared_ptr<Processor> /*endpoint*/, bool /*include_endpoint*/)
579 {
580         std::cerr << "MIDI bounce range currently unsupported" << std::endl;
581         return boost::shared_ptr<Region> ();
582 }
583
584 void
585 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
586 {
587         std::cerr << "MIDI freeze currently unsupported" << std::endl;
588 }
589
590 void
591 MidiTrack::unfreeze ()
592 {
593         _freeze_record.state = UnFrozen;
594         FreezeChange (); /* EMIT SIGNAL */
595 }
596
597 void
598 MidiTrack::set_note_mode (NoteMode m)
599 {
600         _note_mode = m;
601         midi_diskstream()->set_note_mode(m);
602 }
603
604 std::string
605 MidiTrack::describe_parameter (Evoral::Parameter param)
606 {
607         const std::string str(instrument_info().get_controller_name(param));
608         return str.empty() ? Automatable::describe_parameter(param) : str;
609 }
610
611 void
612 MidiTrack::midi_panic()
613 {
614         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers panic data\n", name()));
615         for (uint8_t channel = 0; channel <= 0xF; channel++) {
616                 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), ((uint8_t) MIDI_CTL_SUSTAIN), 0 };
617                 write_immediate_event(3, ev);
618                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
619                 write_immediate_event(3, ev);
620                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
621                 write_immediate_event(3, ev);
622         }
623 }
624
625 /** \return true on success, false on failure (no buffer space left)
626  */
627 bool
628 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
629 {
630         if (!Evoral::midi_event_is_valid(buf, size)) {
631                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
632                 return false;
633         }
634         const uint32_t type = midi_parameter_type(buf[0]);
635         return (_immediate_events.write (0, type, size, buf) == size);
636 }
637
638 void
639 MidiTrack::set_parameter_automation_state (Evoral::Parameter param, AutoState state)
640 {
641         switch (param.type()) {
642         case MidiCCAutomation:
643         case MidiPgmChangeAutomation:
644         case MidiPitchBenderAutomation:
645         case MidiChannelPressureAutomation:
646         case MidiSystemExclusiveAutomation:
647                 /* The track control for MIDI parameters is for immediate events to act
648                    as a control surface, write/touch for them is not currently
649                    supported. */
650                 return;
651         default:
652                 Automatable::set_parameter_automation_state(param, state);
653         }
654 }
655
656 void
657 MidiTrack::MidiControl::set_value(double val)
658 {
659         const Evoral::Parameter &parameter = _list ? _list->parameter() : Control::parameter();
660
661         bool valid = false;
662         if (isinf_local(val)) {
663                 cerr << "MIDIControl value is infinity" << endl;
664         } else if (isnan_local(val)) {
665                 cerr << "MIDIControl value is NaN" << endl;
666         } else if (val < parameter.min()) {
667                 cerr << "MIDIControl value is < " << parameter.min() << endl;
668         } else if (val > parameter.max()) {
669                 cerr << "MIDIControl value is > " << parameter.max() << endl;
670         } else {
671                 valid = true;
672         }
673
674         if (!valid) {
675                 return;
676         }
677
678         assert(val <= parameter.max());
679         if ( ! _list || ! automation_playback()) {
680                 size_t size = 3;
681                 uint8_t ev[3] = { parameter.channel(), uint8_t (val), 0 };
682                 switch(parameter.type()) {
683                 case MidiCCAutomation:
684                         ev[0] += MIDI_CMD_CONTROL;
685                         ev[1] = parameter.id();
686                         ev[2] = int(val);
687                         break;
688
689                 case MidiPgmChangeAutomation:
690                         size = 2;
691                         ev[0] += MIDI_CMD_PGM_CHANGE;
692                         ev[1] = int(val);
693                         break;
694
695                 case MidiChannelPressureAutomation:
696                         size = 2;
697                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
698                         ev[1] = int(val);
699                         break;
700
701                 case MidiPitchBenderAutomation:
702                         ev[0] += MIDI_CMD_BENDER;
703                         ev[1] = 0x7F & int(val);
704                         ev[2] = 0x7F & (int(val) >> 7);
705                         break;
706
707                 default:
708                         assert(false);
709                 }
710                 _route->write_immediate_event(size,  ev);
711         }
712
713         AutomationControl::set_value(val);
714 }
715
716 void
717 MidiTrack::set_step_editing (bool yn)
718 {
719         if (_session.record_status() != Session::Disabled) {
720                 return;
721         }
722
723         if (yn != _step_editing) {
724                 _step_editing = yn;
725                 StepEditStatusChange (yn);
726         }
727 }
728
729 boost::shared_ptr<SMFSource>
730 MidiTrack::write_source (uint32_t)
731 {
732         return midi_diskstream()->write_source ();
733 }
734
735 void
736 MidiTrack::set_playback_channel_mode(ChannelMode mode, uint16_t mask) 
737 {
738         ChannelMode old = get_playback_channel_mode ();
739         uint16_t old_mask = get_playback_channel_mask ();
740
741         if (old != mode || mask != old_mask) {
742                 _set_playback_channel_mode (mode, mask);
743                 PlaybackChannelModeChanged ();
744                 _session.set_dirty ();
745         }
746 }
747
748 void
749 MidiTrack::set_capture_channel_mode(ChannelMode mode, uint16_t mask) 
750 {
751         ChannelMode old = get_capture_channel_mode ();
752         uint16_t old_mask = get_capture_channel_mask ();
753
754         if (old != mode || mask != old_mask) {
755                 _set_capture_channel_mode (mode, mask);
756                 CaptureChannelModeChanged ();
757                 _session.set_dirty ();
758         }
759 }
760
761 void
762 MidiTrack::set_playback_channel_mask (uint16_t mask)
763 {
764         uint16_t old = get_playback_channel_mask();
765
766         if (old != mask) {
767                 _set_playback_channel_mask (mask);
768                 PlaybackChannelMaskChanged ();
769                 _session.set_dirty ();
770         }
771 }
772
773 void
774 MidiTrack::set_capture_channel_mask (uint16_t mask)
775 {
776         uint16_t old = get_capture_channel_mask();
777
778         if (old != mask) {
779                 _set_capture_channel_mask (mask);
780                 CaptureChannelMaskChanged ();
781                 _session.set_dirty ();
782         }
783 }
784
785 boost::shared_ptr<MidiPlaylist>
786 MidiTrack::midi_playlist ()
787 {
788         return midi_diskstream()->midi_playlist ();
789 }
790
791 void
792 MidiTrack::diskstream_data_recorded (boost::weak_ptr<MidiSource> src)
793 {
794         DataRecorded (src); /* EMIT SIGNAL */
795 }
796
797 bool
798 MidiTrack::input_active () const
799 {
800         return _input_active;
801 }
802
803 void
804 MidiTrack::set_input_active (bool yn)
805 {
806         if (yn != _input_active) {
807                 _input_active = yn;
808                 map_input_active (yn);
809                 InputActiveChanged (); /* EMIT SIGNAL */
810         }
811 }
812
813 void
814 MidiTrack::map_input_active (bool yn)
815 {
816         if (!_input) {
817                 return;
818         }
819
820         PortSet& ports (_input->ports());
821
822         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
823                 boost::shared_ptr<MidiPort> mp = boost::dynamic_pointer_cast<MidiPort> (*p);
824                 if (yn != mp->input_active()) {
825                         mp->set_input_active (yn);
826                 }
827         }
828 }
829
830 void
831 MidiTrack::track_input_active (IOChange change, void* /* src */)
832 {
833         if (change.type & IOChange::ConfigurationChanged) {
834                 map_input_active (_input_active);
835         }
836 }
837
838 boost::shared_ptr<Diskstream>
839 MidiTrack::diskstream_factory (XMLNode const & node)
840 {
841         return boost::shared_ptr<Diskstream> (new MidiDiskstream (_session, node));
842 }
843
844 boost::shared_ptr<MidiBuffer>
845 MidiTrack::get_gui_feed_buffer () const
846 {
847         return midi_diskstream()->get_gui_feed_buffer ();
848 }
849
850 void
851 MidiTrack::act_on_mute ()
852 {
853         /* this is called right after our mute status has changed.
854            if we are now muted, send suitable output to shutdown
855            all our notes.
856
857            XXX we should should also stop all relevant note trackers.
858         */
859
860         /* If we haven't got a diskstream yet, there's nothing to worry about,
861            and we can't call get_channel_mask() anyway.
862         */
863         if (!midi_diskstream()) {
864                 return;
865         }
866
867         if (muted()) {
868                 /* only send messages for channels we are using */
869
870                 uint16_t mask = get_playback_channel_mask();
871
872                 for (uint8_t channel = 0; channel <= 0xF; channel++) {
873
874                         if ((1<<channel) & mask) {
875
876                                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("%1 delivers mute message to channel %2\n", name(), channel+1));
877                                 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), MIDI_CTL_SUSTAIN, 0 };
878                                 write_immediate_event (3, ev);
879                                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
880                                 write_immediate_event (3, ev);
881                         }
882                 }
883         }
884 }
885         
886 void
887 MidiTrack::set_monitoring (MonitorChoice mc)
888 {
889         if (mc != _monitoring) {
890
891                 Track::set_monitoring (mc);
892                 
893                 /* monitoring state changed, so flush out any on notes at the
894                  * port level.
895                  */
896
897                 PortSet& ports (_output->ports());
898                 
899                 for (PortSet::iterator p = ports.begin(); p != ports.end(); ++p) {
900                         boost::shared_ptr<MidiPort> mp = boost::dynamic_pointer_cast<MidiPort> (*p);
901                         if (mp) {
902                                 mp->require_resolve ();
903                         }
904                 }
905
906                 boost::shared_ptr<MidiDiskstream> md (midi_diskstream());
907                 
908                 if (md) {
909                         md->reset_tracker ();
910                 }
911         }
912 }
913
914 MonitorState
915 MidiTrack::monitoring_state () const
916 {
917         MonitorState ms = Track::monitoring_state();
918         if (ms == MonitoringSilence) {
919                 return MonitoringInput;
920         } 
921         return ms;
922 }
923