fix up marshall/unmarshall of note data for MidiModel::DiffCommand
[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 #include "evoral/midi_util.h"
27
28 #include "ardour/amp.h"
29 #include "ardour/buffer_set.h"
30 #include "ardour/delivery.h"
31 #include "ardour/io_processor.h"
32 #include "ardour/meter.h"
33 #include "ardour/midi_diskstream.h"
34 #include "ardour/midi_playlist.h"
35 #include "ardour/midi_region.h"
36 #include "ardour/midi_source.h"
37 #include "ardour/midi_track.h"
38 #include "ardour/panner.h"
39 #include "ardour/port.h"
40 #include "ardour/processor.h"
41 #include "ardour/route_group_specialized.h"
42 #include "ardour/session.h"
43 #include "ardour/utils.h"
44
45 #include "i18n.h"
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace PBD;
50
51 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
52         : Track (sess, name, flag, mode, DataType::MIDI)
53         , _immediate_events(1024) // FIXME: size?
54         , _step_edit_ring_buffer(64) // FIXME: size?
55         , _note_mode(Sustained)
56         , _step_editing (false)
57 {
58         use_new_diskstream ();
59
60         _declickable = true;
61         _freeze_record.state = NoFreeze;
62         _saved_meter_point = _meter_point;
63         _mode = mode;
64 }
65
66 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
67         : Track (sess, node, DataType::MIDI )
68         , _immediate_events(1024) // FIXME: size?
69         , _step_edit_ring_buffer(64) // FIXME: size?
70         , _note_mode(Sustained)
71         , _step_editing (false)
72 {
73         _set_state(node, false);
74 }
75
76 MidiTrack::~MidiTrack ()
77 {
78 }
79
80 void
81 MidiTrack::use_new_diskstream ()
82 {
83         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
84
85         if (_flags & Hidden) {
86                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
87         } else {
88                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
89         }
90
91         assert(_mode != Destructive);
92
93         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
94         _session.add_diskstream (ds);
95
96         set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
97 }       
98
99 int
100 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
101 {
102         _diskstream = ds;
103         _diskstream->set_route (*this);
104         _diskstream->set_destructive (_mode == Destructive);
105
106         _diskstream->set_record_enabled (false);
107         //_diskstream->monitor_input (false);
108
109         ic_connection.disconnect();
110         ic_connection = _input->changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
111
112         DiskstreamChanged (); /* EMIT SIGNAL */
113
114         return 0;
115 }       
116
117 int 
118 MidiTrack::use_diskstream (string name)
119 {
120         boost::shared_ptr<MidiDiskstream> dstream;
121
122         cerr << "\n\n\nMIDI use diskstream\n";
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         cerr << "\n\n\nMIDI found DS\n";
130         return set_diskstream (dstream);
131 }
132
133 int 
134 MidiTrack::use_diskstream (const PBD::ID& id)
135 {
136         boost::shared_ptr<MidiDiskstream> dstream;
137
138         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
139                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
140                 return -1;
141         }
142         
143         return set_diskstream (dstream);
144 }
145
146 boost::shared_ptr<MidiDiskstream>
147 MidiTrack::midi_diskstream() const
148 {
149         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
150 }
151
152 int
153 MidiTrack::set_state (const XMLNode& node)
154 {
155         return _set_state (node, true);
156 }
157
158 int
159 MidiTrack::_set_state (const XMLNode& node, bool call_base)
160 {
161         const XMLProperty *prop;
162         XMLNodeConstIterator iter;
163
164         if (Route::_set_state (node, call_base)) {
165                 return -1;
166         }
167         
168         // No destructive MIDI tracks (yet?)
169         _mode = Normal;
170         
171         if ((prop = node.property (X_("note-mode"))) != 0) {
172                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
173         } else {
174                 _note_mode = Sustained;
175         }
176
177         if ((prop = node.property ("diskstream-id")) == 0) {
178                 
179                 /* some old sessions use the diskstream name rather than the ID */
180
181                 if ((prop = node.property ("diskstream")) == 0) {
182                         fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
183                         /*NOTREACHED*/
184                         return -1;
185                 }
186
187                 if (use_diskstream (prop->value())) {
188                         return -1;
189                 }
190
191         } else {
192                 
193                 PBD::ID id (prop->value());
194                 PBD::ID zero ("0");
195                 
196                 /* this wierd hack is used when creating tracks from a template. there isn't
197                    a particularly good time to interpose between setting the first part of
198                    the track state (notably Route::set_state() and the track mode), and the
199                    second part (diskstream stuff). So, we have a special ID for the diskstream
200                    that means "you should create a new diskstream here, not look for
201                    an old one.
202                 */
203
204                 cerr << "\n\n\n\n MIDI track " << name() << " found DS id " << id << endl;
205                 
206                 if (id == zero) {
207                         use_new_diskstream ();
208                 } else if (use_diskstream (id)) {
209                         return -1;
210                 }
211         }
212
213         XMLNodeList nlist;
214         XMLNodeConstIterator niter;
215         XMLNode *child;
216
217         nlist = node.children();
218         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
219                 child = *niter;
220
221                 if (child->name() == X_("recenable")) {
222                         _rec_enable_control->set_state (*child);
223                         _session.add_controllable (_rec_enable_control);
224                 }
225         }
226
227         pending_state = const_cast<XMLNode*> (&node);
228
229         if (_session.state_of_the_state() & Session::Loading) {
230                 _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
231         } else {
232                 set_state_part_two ();
233         }
234
235         return 0;
236 }
237
238 XMLNode& 
239 MidiTrack::state(bool full_state)
240 {
241         XMLNode& root (Route::state(full_state));
242         XMLNode* freeze_node;
243         char buf[64];
244
245         if (_freeze_record.playlist) {
246                 XMLNode* inode;
247
248                 freeze_node = new XMLNode (X_("freeze-info"));
249                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
250                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
251
252                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
253                         inode = new XMLNode (X_("processor"));
254                         (*i)->id.print (buf, sizeof(buf));
255                         inode->add_property (X_("id"), buf);
256                         inode->add_child_copy ((*i)->state);
257                 
258                         freeze_node->add_child_nocopy (*inode);
259                 }
260
261                 root.add_child_nocopy (*freeze_node);
262         }
263
264         /* Alignment: act as a proxy for the diskstream */
265         
266         XMLNode* align_node = new XMLNode (X_("Alignment"));
267         AlignStyle as = _diskstream->alignment_style ();
268         align_node->add_property (X_("style"), enum_2_string (as));
269         root.add_child_nocopy (*align_node);
270
271         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
272         
273         /* we don't return diskstream state because we don't
274            own the diskstream exclusively. control of the diskstream
275            state is ceded to the Session, even if we create the
276            diskstream.
277         */
278
279         _diskstream->id().print (buf, sizeof(buf));
280         root.add_property ("diskstream-id", buf);
281         
282         root.add_child_nocopy (_rec_enable_control->get_state());
283
284         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
285         root.add_property ("note-mode", enum_2_string (_note_mode));
286         
287         return root;
288 }
289
290 void
291 MidiTrack::set_state_part_two ()
292 {
293         XMLNode* fnode;
294         XMLProperty* prop;
295         LocaleGuard lg (X_("POSIX"));
296
297         /* This is called after all session state has been restored but before
298            have been made ports and connections are established.
299         */
300
301         if (pending_state == 0) {
302                 return;
303         }
304
305         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
306
307                 _freeze_record.state = Frozen;
308                 
309                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
310                         delete *i;
311                 }
312                 _freeze_record.processor_info.clear ();
313                 
314                 if ((prop = fnode->property (X_("playlist"))) != 0) {
315                         boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
316                         if (pl) {
317                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
318                         } else {
319                                 _freeze_record.playlist.reset();
320                                 _freeze_record.state = NoFreeze;
321                         return;
322                         }
323                 }
324                 
325                 if ((prop = fnode->property (X_("state"))) != 0) {
326                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
327                 }
328                 
329                 XMLNodeConstIterator citer;
330                 XMLNodeList clist = fnode->children();
331                 
332                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
333                         if ((*citer)->name() != X_("processor")) {
334                                 continue;
335                         }
336                         
337                         if ((prop = (*citer)->property (X_("id"))) == 0) {
338                                 continue;
339                         }
340                         
341                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
342                                                                                    boost::shared_ptr<Processor>());
343                         frii->id = prop->value ();
344                         _freeze_record.processor_info.push_back (frii);
345                 }
346         }
347
348         /* Alignment: act as a proxy for the diskstream */
349
350         if ((fnode = find_named_node (*pending_state, X_("Alignment"))) != 0) {
351
352                 if ((prop = fnode->property (X_("style"))) != 0) {
353
354                         /* fix for older sessions from before EnumWriter */
355
356                         string pstr;
357
358                         if (prop->value() == "capture") {
359                                 pstr = "CaptureTime";
360                         } else if (prop->value() == "existing") {
361                                 pstr = "ExistingMaterial";
362                         } else {
363                                 pstr = prop->value();
364                         }
365
366                         AlignStyle as = AlignStyle (string_2_enum (pstr, as));
367                         _diskstream->set_persistent_align_style (as);
368                 }
369         }
370         return;
371 }       
372
373 int
374 MidiTrack::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
375                  bool can_record, bool rec_monitors_input)
376 {
377         int dret;
378         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
379         
380         {
381                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
382                 if (lm.locked()) {
383                         // automation snapshot can also be called from the non-rt context
384                         // and it uses the redirect list, so we take the lock out here
385                         automation_snapshot (start_frame);
386                 }
387         }
388
389         if (n_outputs().n_total() == 0 && _processors.empty()) {
390                 return 0;
391         }
392
393         if (!_active) {
394                 silence (nframes);
395                 return 0;
396         }
397
398         nframes_t transport_frame = _session.transport_frame();
399
400         
401         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
402                 /* need to do this so that the diskstream sets its
403                    playback distance to zero, thus causing diskstream::commit
404                    to do nothing.
405                    */
406                 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input);
407         } 
408
409         _silent = false;
410
411         if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input)) != 0) {
412                 silence (nframes);
413                 return dret;
414         }
415
416         /* special condition applies */
417
418         if (_meter_point == MeterInput) {
419                 _input->process_input (_meter, start_frame, end_frame, nframes);
420         }
421
422         if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
423
424                 /* not actually recording, but we want to hear the input material anyway,
425                    at least potentially (depending on monitoring options)
426                 */
427
428                 passthru (start_frame, end_frame, nframes, 0);
429                 
430         } else {
431                 /*
432                    XXX is it true that the earlier test on n_outputs()
433                    means that we can avoid checking it again here? i think
434                    so, because changing the i/o configuration of an IO
435                    requires holding the AudioEngine lock, which we hold
436                    while in the process() tree.
437                    */
438
439
440                 /* copy the diskstream data to all output buffers */
441
442                 //const size_t limit = n_process_buffers().n_audio();
443                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
444                 MidiBuffer& mbuf (bufs.get_midi (0));
445                 
446                 diskstream->get_playback (mbuf, start_frame, end_frame);
447
448                 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
449
450                 write_out_of_band_data (bufs, start_frame, end_frame, nframes); 
451
452                 // Feed the data through the MidiStateTracker
453                 bool did_loop;
454
455                 _midi_state_tracker.track (mbuf.begin(), mbuf.end(), did_loop);
456
457                 if (did_loop) {
458                         /* add necessary note offs */
459                         cerr << "DID LOOP, RESOLVE NOTES\n";
460                         _midi_state_tracker.resolve_notes (mbuf, end_frame-start_frame - 1);
461                 }
462
463                 process_output_buffers (bufs, start_frame, end_frame, nframes,
464                                 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
465
466         }
467
468         _main_outs->flush (nframes);
469
470         return 0;
471 }
472
473 int
474 MidiTrack::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, 
475                     bool state_changing, bool can_record, bool rec_monitors_input)
476 {
477         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
478
479         if (ret == 0 && diskstream()->record_enabled() && _step_editing) {
480                 push_midi_input_to_step_edit_ringbuffer (nframes);
481         }
482
483         return ret;
484 }
485
486 void 
487 MidiTrack::handle_transport_stopped (bool abort, bool did_locate, bool flush_processors)
488 {
489         /* turn off any notes that are on */
490
491         MidiBuffer buf (1024); // XXX is this a reasonable size ? 
492         
493         _midi_state_tracker.resolve_notes (buf, 0); // time is zero because notes are immediate
494
495         for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
496                 write_immediate_event ((*i).size(), (*i).buffer());
497         }
498
499         Route::handle_transport_stopped (abort, did_locate, flush_processors);
500 }
501         
502
503 void
504 MidiTrack::push_midi_input_to_step_edit_ringbuffer (nframes_t nframes)
505 {
506         PortSet& ports (_input->ports());
507
508         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
509
510                 Buffer& b (p->get_buffer (nframes));
511                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
512                 assert (mb);
513
514                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
515
516                         const Evoral::MIDIEvent<nframes_t> ev(*e, false);
517                         
518                         /* we don't care about the time for this purpose */
519
520                         _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
521                 }
522         }
523 }
524
525 void
526 MidiTrack::write_out_of_band_data (BufferSet& bufs, sframes_t /*start*/, sframes_t /*end*/, nframes_t nframes)
527 {
528         // Append immediate events
529
530         MidiBuffer& buf (bufs.get_midi (0));
531         _immediate_events.read (buf, 0, 0, nframes - 1); // all stamps = 0
532 }
533
534 int
535 MidiTrack::export_stuff (BufferSet& /*bufs*/, nframes_t /*nframes*/, sframes_t /*end_frame*/)
536 {
537         return -1;
538 }
539
540 void
541 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
542 {
543         Route::set_latency_delay (longest_session_latency);
544         _diskstream->set_roll_delay (_roll_delay);
545 }
546
547 boost::shared_ptr<Region>
548 MidiTrack::bounce (InterThreadInfo& /*itt*/)
549 {
550         throw;
551         // vector<MidiSource*> srcs;
552         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
553         return boost::shared_ptr<Region> ();
554 }
555
556
557 boost::shared_ptr<Region>
558 MidiTrack::bounce_range (nframes_t /*start*/, nframes_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
559 {
560         throw;
561         //vector<MidiSource*> srcs;
562         //return _session.write_one_track (*this, start, end, false, srcs, itt);
563         return boost::shared_ptr<Region> ();
564 }
565
566 void
567 MidiTrack::freeze (InterThreadInfo& /*itt*/)
568 {
569 }
570
571 void
572 MidiTrack::unfreeze ()
573 {
574         _freeze_record.state = UnFrozen;
575         FreezeChange (); /* EMIT SIGNAL */
576 }
577
578 void
579 MidiTrack::set_note_mode (NoteMode m)
580 {
581         _note_mode = m;
582         midi_diskstream()->set_note_mode(m);
583 }
584
585 void
586 MidiTrack::midi_panic() 
587 {
588         for (uint8_t channel = 0; channel <= 0xF; channel++) {
589                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
590                 write_immediate_event(3, ev);
591                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
592                 write_immediate_event(3, ev);
593                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
594                 write_immediate_event(3, ev);
595         }
596 }
597
598 /** \return true on success, false on failure (no buffer space left)
599  */
600 bool
601 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
602 {
603         if (!Evoral::midi_event_is_valid(buf, size)) {
604                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
605                 return false;
606         }
607         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
608         return (_immediate_events.write(0, type, size, buf) == size);
609 }
610
611 void
612 MidiTrack::MidiControl::set_value(float val)
613 {
614         bool valid = false;
615         if (isinf(val)) {
616                 cerr << "MIDIControl value is infinity" << endl;
617         } else if (isnan(val)) {
618                 cerr << "MIDIControl value is NaN" << endl;
619         } else if (val < _list->parameter().min()) {
620                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
621         } else if (val > _list->parameter().max()) {
622                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
623         } else {
624                 valid = true;
625         }
626         
627         if (!valid) {
628                 return;
629         }
630
631         assert(val <= _list->parameter().max());
632         size_t size = 3;
633
634         if ( ! automation_playback()) {
635                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
636                 switch(_list->parameter().type()) {
637                 case MidiCCAutomation:
638                         ev[0] += MIDI_CMD_CONTROL;
639                         ev[1] = _list->parameter().id();
640                         ev[2] = int(val);
641                         break;
642                         
643                 case MidiPgmChangeAutomation:
644                         size = 2;
645                         ev[0] += MIDI_CMD_PGM_CHANGE;
646                         ev[1] = int(val);
647                         break;
648                         
649                 case MidiChannelPressureAutomation:
650                         size = 2;
651                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
652                         ev[1] = int(val);
653                         break;
654                         
655                 case MidiPitchBenderAutomation:
656                         ev[0] += MIDI_CMD_BENDER;
657                         ev[1] = 0x7F & int(val);
658                         ev[2] = 0x7F & (int(val) >> 7);
659                         break;
660                         
661                 default:
662                         assert(false);
663                 }
664                 _route->write_immediate_event(size,  ev);
665         }
666
667         AutomationControl::set_value(val);
668
669
670 void
671 MidiTrack::set_step_editing (bool yn)
672 {
673         _step_editing = yn;
674 }