* first prototype implementation of playing back MIDI notes when selected
[ardour.git] / libs / ardour / midi_track.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3         By Dave Robillard, 2006
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 <pbd/error.h>
20 #include <sigc++/retype.h>
21 #include <sigc++/retype_return.h>
22 #include <sigc++/bind.h>
23
24 #include <pbd/enumwriter.h>
25 #include <midi++/events.h>
26
27 #include <ardour/midi_track.h>
28 #include <ardour/midi_diskstream.h>
29 #include <ardour/session.h>
30 #include <ardour/io_processor.h>
31 #include <ardour/midi_region.h>
32 #include <ardour/midi_source.h>
33 #include <ardour/route_group_specialized.h>
34 #include <ardour/processor.h>
35 #include <ardour/midi_playlist.h>
36 #include <ardour/panner.h>
37 #include <ardour/utils.h>
38 #include <ardour/buffer_set.h>
39 #include <ardour/meter.h>
40
41
42 #include "i18n.h"
43
44 using namespace std;
45 using namespace ARDOUR;
46 using namespace PBD;
47
48 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
49         : Track (sess, name, flag, mode, DataType::MIDI)
50         , _immediate_events(1024) // FIXME: size?
51         , _note_mode(Sustained)
52 {
53         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
54
55         if (_flags & Hidden) {
56                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
57         } else {
58                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
59         }
60
61         assert(mode != Destructive);
62
63         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name, dflags));
64         _session.add_diskstream (ds);
65
66         set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
67         
68         _declickable = true;
69         _freeze_record.state = NoFreeze;
70         _saved_meter_point = _meter_point;
71         _mode = mode;
72
73         set_input_minimum(ChanCount(DataType::MIDI, 1));
74         set_input_maximum(ChanCount(DataType::MIDI, 1));
75         set_output_minimum(ChanCount(DataType::MIDI, 1));
76         set_output_maximum(ChanCount(DataType::MIDI, 1));
77
78         PortCountChanged(ChanCount(DataType::MIDI, 2)); /* EMIT SIGNAL */
79 }
80
81 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
82         : Track (sess, node, DataType::MIDI )
83         , _immediate_events(1024) // FIXME: size?
84         , _note_mode(Sustained)
85 {
86         _set_state(node, false);
87         
88         set_input_minimum(ChanCount(DataType::MIDI, 1));
89         set_input_maximum(ChanCount(DataType::MIDI, 1));
90         set_output_minimum(ChanCount(DataType::MIDI, 1));
91         set_output_maximum(ChanCount(DataType::MIDI, 1));
92         
93         PortCountChanged(ChanCount(DataType::MIDI, 2)); /* EMIT SIGNAL */
94 }
95
96 MidiTrack::~MidiTrack ()
97 {
98 }
99
100
101 int
102 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
103 {
104         _diskstream = ds;
105         _diskstream->set_io (*this);
106         _diskstream->set_destructive (_mode == Destructive);
107
108         _diskstream->set_record_enabled (false);
109         //_diskstream->monitor_input (false);
110
111         ic_connection.disconnect();
112         ic_connection = input_changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
113
114         DiskstreamChanged (); /* EMIT SIGNAL */
115
116         return 0;
117 }       
118
119 int 
120 MidiTrack::use_diskstream (string name)
121 {
122         boost::shared_ptr<MidiDiskstream> dstream;
123
124         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream>(_session.diskstream_by_name (name))) == 0) {
125                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), name) << endmsg;
126                 return -1;
127         }
128         
129         return set_diskstream (dstream);
130 }
131
132 int 
133 MidiTrack::use_diskstream (const PBD::ID& id)
134 {
135         boost::shared_ptr<MidiDiskstream> dstream;
136
137         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
138                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
139                 return -1;
140         }
141         
142         return set_diskstream (dstream);
143 }
144
145 boost::shared_ptr<MidiDiskstream>
146 MidiTrack::midi_diskstream() const
147 {
148         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
149 }
150
151 int
152 MidiTrack::set_state (const XMLNode& node)
153 {
154         return _set_state (node, true);
155 }
156
157 int
158 MidiTrack::_set_state (const XMLNode& node, bool call_base)
159 {
160         const XMLProperty *prop;
161         XMLNodeConstIterator iter;
162
163         if (Route::_set_state (node, call_base)) {
164                 return -1;
165         }
166         
167         // No destructive MIDI tracks (yet?)
168         _mode = Normal;
169         
170         if ((prop = node.property (X_("note-mode"))) != 0) {
171                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
172         } else {
173                 _note_mode = Sustained;
174         }
175
176         if ((prop = node.property ("diskstream-id")) == 0) {
177                 
178                 /* some old sessions use the diskstream name rather than the ID */
179
180                 if ((prop = node.property ("diskstream")) == 0) {
181                         fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
182                         /*NOTREACHED*/
183                         return -1;
184                 }
185
186                 if (use_diskstream (prop->value())) {
187                         return -1;
188                 }
189
190         } else {
191                 
192                 PBD::ID id (prop->value());
193                 
194                 if (use_diskstream (id)) {
195                         return -1;
196                 }
197         }
198
199
200         XMLNodeList nlist;
201         XMLNodeConstIterator niter;
202         XMLNode *child;
203
204         nlist = node.children();
205         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
206                 child = *niter;
207
208                 if (child->name() == X_("recenable")) {
209                         _rec_enable_control->set_state (*child);
210                         _session.add_controllable (_rec_enable_control);
211                 }
212         }
213
214         pending_state = const_cast<XMLNode*> (&node);
215
216         _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
217
218         return 0;
219 }
220
221 XMLNode& 
222 MidiTrack::state(bool full_state)
223 {
224         XMLNode& root (Route::state(full_state));
225         XMLNode* freeze_node;
226         char buf[64];
227
228         if (_freeze_record.playlist) {
229                 XMLNode* inode;
230
231                 freeze_node = new XMLNode (X_("freeze-info"));
232                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
233                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
234
235                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
236                         inode = new XMLNode (X_("processor"));
237                         (*i)->id.print (buf, sizeof(buf));
238                         inode->add_property (X_("id"), buf);
239                         inode->add_child_copy ((*i)->state);
240                 
241                         freeze_node->add_child_nocopy (*inode);
242                 }
243
244                 root.add_child_nocopy (*freeze_node);
245         }
246
247         /* Alignment: act as a proxy for the diskstream */
248         
249         XMLNode* align_node = new XMLNode (X_("alignment"));
250         AlignStyle as = _diskstream->alignment_style ();
251         align_node->add_property (X_("style"), enum_2_string (as));
252         root.add_child_nocopy (*align_node);
253
254         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
255         
256         /* we don't return diskstream state because we don't
257            own the diskstream exclusively. control of the diskstream
258            state is ceded to the Session, even if we create the
259            diskstream.
260         */
261
262         _diskstream->id().print (buf, sizeof(buf));
263         root.add_property ("diskstream-id", buf);
264         
265         root.add_child_nocopy (_rec_enable_control->get_state());
266
267         return root;
268 }
269
270 void
271 MidiTrack::set_state_part_two ()
272 {
273         XMLNode* fnode;
274         XMLProperty* prop;
275         LocaleGuard lg (X_("POSIX"));
276
277         /* This is called after all session state has been restored but before
278            have been made ports and connections are established.
279         */
280
281         if (pending_state == 0) {
282                 return;
283         }
284
285         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
286
287                 
288                 _freeze_record.have_mementos = false;
289                 _freeze_record.state = Frozen;
290                 
291                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
292                         delete *i;
293                 }
294                 _freeze_record.processor_info.clear ();
295                 
296                 if ((prop = fnode->property (X_("playlist"))) != 0) {
297                         boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
298                         if (pl) {
299                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
300                         } else {
301                                 _freeze_record.playlist.reset();
302                                 _freeze_record.state = NoFreeze;
303                         return;
304                         }
305                 }
306                 
307                 if ((prop = fnode->property (X_("state"))) != 0) {
308                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
309                 }
310                 
311                 XMLNodeConstIterator citer;
312                 XMLNodeList clist = fnode->children();
313                 
314                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
315                         if ((*citer)->name() != X_("processor")) {
316                                 continue;
317                         }
318                         
319                         if ((prop = (*citer)->property (X_("id"))) == 0) {
320                                 continue;
321                         }
322                         
323                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
324                                                                                    boost::shared_ptr<Processor>());
325                         frii->id = prop->value ();
326                         _freeze_record.processor_info.push_back (frii);
327                 }
328         }
329
330         /* Alignment: act as a proxy for the diskstream */
331
332         if ((fnode = find_named_node (*pending_state, X_("alignment"))) != 0) {
333
334                 if ((prop = fnode->property (X_("style"))) != 0) {
335
336                         /* fix for older sessions from before EnumWriter */
337
338                         string pstr;
339
340                         if (prop->value() == "capture") {
341                                 pstr = "CaptureTime";
342                         } else if (prop->value() == "existing") {
343                                 pstr = "ExistingMaterial";
344                         } else {
345                                 pstr = prop->value();
346                         }
347
348                         AlignStyle as = AlignStyle (string_2_enum (pstr, as));
349                         _diskstream->set_persistent_align_style (as);
350                 }
351         }
352         return;
353 }       
354
355 int 
356 MidiTrack::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
357                      bool session_state_changing, bool can_record, bool rec_monitors_input)
358 {
359         if (n_outputs().n_midi() == 0) {
360                 return 0;
361         }
362
363         if (!_active) {
364                 silence (nframes, offset);
365         }
366
367         if (session_state_changing) {
368
369                 /* XXX is this safe to do against transport state changes? */
370
371                 passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
372                 return 0;
373         }
374
375         midi_diskstream()->check_record_status (start_frame, nframes, can_record);
376
377         bool send_silence;
378         
379         if (_have_internal_generator) {
380                 /* since the instrument has no input streams,
381                    there is no reason to send any signal
382                    into the route.
383                 */
384                 send_silence = true;
385         } else {
386
387                 if (Config->get_auto_input()) {
388                         if (Config->get_monitoring_model() == SoftwareMonitoring) {
389                                 send_silence = false;
390                         } else {
391                                 send_silence = true;
392                         }
393                 } else {
394                         if (_diskstream->record_enabled()) {
395                                 if (Config->get_monitoring_model() == SoftwareMonitoring) {
396                                         send_silence = false;
397                                 } else {
398                                         send_silence = true;
399                                 }
400                         } else {
401                                 send_silence = true;
402                         }
403                 }
404         }
405
406         apply_gain_automation = false;
407
408         if (send_silence) {
409                 
410                 /* if we're sending silence, but we want the meters to show levels for the signal,
411                    meter right here.
412                 */
413                 
414                 if (_have_internal_generator) {
415                         passthru_silence (start_frame, end_frame, nframes, offset, 0, true);
416                 } else {
417                         if (_meter_point == MeterInput) {
418                                 just_meter_input (start_frame, end_frame, nframes, offset);
419                         }
420                         passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
421                 }
422
423         } else {
424         
425                 /* we're sending signal, but we may still want to meter the input. 
426                  */
427
428                 passthru (start_frame, end_frame, nframes, offset, 0, (_meter_point == MeterInput));
429         }
430
431         return 0;
432 }
433
434 int
435 MidiTrack::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
436                   bool can_record, bool rec_monitors_input)
437 {
438         int dret;
439         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
440         
441         // I guess this is the right place to call cycle_start for our ports.
442         // but it actually sucks, to directly mess with the IO.... oh well.
443         
444         prepare_inputs( nframes, offset );
445
446         {
447                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
448                 if (lm.locked()) {
449                         // automation snapshot can also be called from the non-rt context
450                         // and it uses the redirect list, so we take the lock out here
451                         automation_snapshot (start_frame);
452                 }
453         }
454
455         if (n_outputs().n_total() == 0 && _processors.empty()) {
456                 return 0;
457         }
458
459         if (!_active) {
460                 silence (nframes, offset);
461                 return 0;
462         }
463
464         nframes_t transport_frame = _session.transport_frame();
465
466         
467         if ((nframes = check_initial_delay (nframes, offset, transport_frame)) == 0) {
468                 /* need to do this so that the diskstream sets its
469                    playback distance to zero, thus causing diskstream::commit
470                    to do nothing.
471                    */
472                 return diskstream->process (transport_frame, 0, 0, can_record, rec_monitors_input);
473         } 
474
475         _silent = false;
476
477         if ((dret = diskstream->process (transport_frame, nframes, offset, can_record, rec_monitors_input)) != 0) {
478
479                 silence (nframes, offset);
480
481                 return dret;
482         }
483
484         /* special condition applies */
485
486         if (_meter_point == MeterInput) {
487                 just_meter_input (start_frame, end_frame, nframes, offset);
488         }
489
490         if (diskstream->record_enabled() && !can_record && !Config->get_auto_input()) {
491
492                 /* not actually recording, but we want to hear the input material anyway,
493                    at least potentially (depending on monitoring options)
494                    */
495
496                 passthru (start_frame, end_frame, nframes, offset, 0, true);
497
498         } else {
499                 /*
500                    XXX is it true that the earlier test on n_outputs()
501                    means that we can avoid checking it again here? i think
502                    so, because changing the i/o configuration of an IO
503                    requires holding the AudioEngine lock, which we hold
504                    while in the process() tree.
505                    */
506
507
508                 /* copy the diskstream data to all output buffers */
509
510                 //const size_t limit = n_process_buffers().n_audio();
511                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
512
513                 diskstream->get_playback(bufs.get_midi(0), start_frame, end_frame, offset);
514
515                 process_output_buffers (bufs, start_frame, end_frame, nframes, offset,
516                                 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick, (_meter_point != MeterInput));
517         
518         }
519
520         flush_outputs( nframes, offset );
521
522         return 0;
523 }
524
525 int
526 MidiTrack::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
527                          bool can_record, bool rec_monitors_input)
528 {
529         if (n_outputs().n_midi() == 0 && _processors.empty()) {
530                 return 0;
531         }
532
533         if (!_active) {
534                 silence (nframes, offset);
535                 return 0;
536         }
537
538         _silent = true;
539         apply_gain_automation = false;
540
541         silence (nframes, offset);
542
543         return midi_diskstream()->process (_session.transport_frame() + offset, nframes, offset, can_record, rec_monitors_input);
544 }
545
546 void
547 MidiTrack::process_output_buffers (BufferSet& bufs,
548                                nframes_t start_frame, nframes_t end_frame, 
549                                nframes_t nframes, nframes_t offset, bool with_processors, int declick,
550                                bool meter)
551 {
552         /* There's no such thing as a MIDI bus for the time being.
553          * We'll do all the MIDI route work here for now, but the long-term goal is to have
554          * Route::process_output_buffers handle everything */
555         
556         if (meter && (_meter_point == MeterInput || _meter_point == MeterPreFader)) {
557                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
558         }
559
560         // Run all processors
561         if (with_processors) {
562                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
563                 if (rm.locked()) {
564                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
565                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
566                         }
567                 } 
568         }
569         
570         if (meter && (_meter_point == MeterPostFader)) {
571                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
572         }
573         
574         // Main output stage
575         if (muted()) {
576                 IO::silence(nframes, offset);
577         } else {
578
579                 // Write 'automation' controllers (e.g. CC events from a UI slider)
580                 write_controller_messages(bufs.get_midi(0), start_frame, end_frame, nframes, offset);
581                 
582                 deliver_output(bufs, start_frame, end_frame, nframes, offset);
583         }
584 }
585
586 void
587 MidiTrack::write_controller_messages(MidiBuffer& output_buf, nframes_t start_frame, nframes_t end_frame, 
588                                nframes_t nframes, nframes_t offset)
589 {
590 #if 0
591         BufferSet& mix_buffers = _session.get_mix_buffers(ChanCount(DataType::MIDI, 2));
592
593         /* FIXME: this could be more realtimey */
594
595         // Write immediate events (UI controls)
596         MidiBuffer& cc_buf = mix_buffers.get_midi(0);
597         cc_buf.silence(nframes, offset);
598         
599         uint8_t buf[3]; // CC = 3 bytes
600         buf[0] = MIDI_CMD_CONTROL;
601         Evoral::Event ev(0, 3, buf, false);
602
603         // Write track controller automation
604         // This now lives in MidiModel.  Any need for track automation like this?
605         // Relative Velocity?
606         if (_session.transport_rolling()) {
607                 for (Controls::const_iterator i = _controls.begin(); i != _controls.end(); ++i) {
608                         const boost::shared_ptr<AutomationList> list = (*i).second->list();
609
610                         if ( (!list->automation_playback())
611                                         || (list->parameter().type() != MidiCCAutomation))
612                                 continue;
613
614                         double start = start_frame;
615                         double x, y;
616                         while ((*i).second->list()->rt_safe_earliest_event(start, end_frame, x, y)) {
617                                 assert(x >= start_frame);
618                                 assert(x <= end_frame);
619
620                                 const nframes_t stamp = (nframes_t)floor(x - start_frame);
621                                 assert(stamp < nframes);
622
623                                 assert(y >= 0.0);
624                                 assert(y <= 127.0);
625
626                                 ev.time() = stamp;
627                                 ev.buffer()[1] = (uint8_t)list->parameter().id();
628                                 ev.buffer()[2] = (uint8_t)y;
629
630                                 cc_buf.push_back(ev);
631
632                                 start = x + 1; // FIXME?  maybe?
633                         }
634                 }
635         }
636
637         /* FIXME: too much copying! */
638
639         // Merge cc buf into output
640         if (cc_buf.size() > 0) {
641
642                 // Both CC and route, must merge
643                 if (output_buf.size() > 0) {
644
645                         MidiBuffer& mix_buf = mix_buffers.get_midi(1);
646                         mix_buf.merge(output_buf, cc_buf);
647                         output_buf.copy(mix_buf);
648
649                 } else {
650                         output_buf.copy(cc_buf);
651                 }
652         }
653 #endif
654
655         // Append immediate events (UI controls)
656         _immediate_events.read(output_buf, 0, 0, offset + nframes-1); // all stamps = 0
657 }
658
659 int
660 MidiTrack::export_stuff (BufferSet& bufs, nframes_t nframes, nframes_t end_frame)
661 {
662         return -1;
663 }
664
665 void
666 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
667 {
668         Route::set_latency_delay (longest_session_latency);
669         _diskstream->set_roll_delay (_roll_delay);
670 }
671
672 boost::shared_ptr<Region>
673 MidiTrack::bounce (InterThreadInfo& itt)
674 {
675         throw;
676         // vector<MidiSource*> srcs;
677         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
678         return boost::shared_ptr<Region> ();
679 }
680
681
682 boost::shared_ptr<Region>
683 MidiTrack::bounce_range (nframes_t start, nframes_t end, InterThreadInfo& itt)
684 {
685         throw;
686         //vector<MidiSource*> srcs;
687         //return _session.write_one_track (*this, start, end, false, srcs, itt);
688         return boost::shared_ptr<Region> ();
689 }
690
691 void
692 MidiTrack::freeze (InterThreadInfo& itt)
693 {
694 }
695
696 void
697 MidiTrack::unfreeze ()
698 {
699         _freeze_record.state = UnFrozen;
700         FreezeChange (); /* EMIT SIGNAL */
701 }
702
703 void
704 MidiTrack::set_note_mode (NoteMode m)
705 {
706         cout << _name << " SET NOTE MODE " << m << endl;
707         _note_mode = m;
708         midi_diskstream()->set_note_mode(m);
709 }
710
711 void
712 MidiTrack::midi_panic() 
713 {
714         for (uint8_t channel = 0; channel <= 0xF; channel++) {
715                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
716                 write_immediate_event(3, ev);
717                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
718                 write_immediate_event(3, ev);
719                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
720                 write_immediate_event(3, ev);
721         }
722 }
723
724 /** \return true on success, false on failure (no buffer space left)
725  */
726 bool
727 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
728 {
729         printf("Write immediate event: ");
730         for (size_t i=0; i < size; ++i) {
731                 printf("%X ", buf[i]);
732         }
733         printf("\n");
734         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
735         return (_immediate_events.write(0, type, size, buf) == size);
736 }
737
738 void
739 MidiTrack::MidiControl::set_value(float val)
740 {
741         bool valid = false;
742         if (isinf(val)) {
743                 cerr << "MIDIControl value is infinity" << endl;
744         } else if (isnan(val)) {
745                 cerr << "MIDIControl value is NaN" << endl;
746         } else if (val < _list->parameter().min()) {
747                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
748         } else if (val > _list->parameter().max()) {
749                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
750         } else {
751                 valid = true;
752         }
753         
754         if (!valid) {
755                 return;
756         }
757
758         assert(val <= _list->parameter().max());
759         size_t size = 3;
760
761         if ( ! automation_playback()) {
762                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
763                 switch(_list->parameter().type()) {
764                 case MidiCCAutomation:
765                         ev[0] += MIDI_CMD_CONTROL;
766                         ev[1] = _list->parameter().id();
767                         ev[2] = int(val);
768                         break;
769                         
770                 case MidiPgmChangeAutomation:
771                         size = 2;
772                         ev[0] += MIDI_CMD_PGM_CHANGE;
773                         ev[1] = int(val);
774                         break;
775                         
776                 case MidiChannelPressureAutomation:
777                         size = 2;
778                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
779                         ev[1] = int(val);
780                         break;
781                         
782                 case MidiPitchBenderAutomation:
783                         ev[0] += MIDI_CMD_BENDER;
784                         ev[1] = 0x7F & int(val);
785                         ev[2] = 0x7F & (int(val) >> 7);
786                         break;
787                         
788                 default:
789                         assert(false);
790                 }
791                 _route->write_immediate_event(size,  ev);
792         }
793
794         AutomationControl::set_value(val);
795
796