Fix compile warning.
[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
21 #include "pbd/enumwriter.h"
22 #include "pbd/convert.h"
23 #include "midi++/events.h"
24 #include "evoral/midi_util.h"
25
26 #include "ardour/amp.h"
27 #include "ardour/buffer_set.h"
28 #include "ardour/delivery.h"
29 #include "ardour/io_processor.h"
30 #include "ardour/meter.h"
31 #include "ardour/midi_diskstream.h"
32 #include "ardour/midi_playlist.h"
33 #include "ardour/midi_port.h"
34 #include "ardour/midi_region.h"
35 #include "ardour/midi_source.h"
36 #include "ardour/midi_track.h"
37 #include "ardour/panner.h"
38 #include "ardour/port.h"
39 #include "ardour/processor.h"
40 #include "ardour/route_group_specialized.h"
41 #include "ardour/session.h"
42 #include "ardour/session_playlists.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         , _default_channel (0)
58         , _midi_thru (true)
59 {
60 }
61
62 MidiTrack::~MidiTrack ()
63 {
64 }
65
66 void
67 MidiTrack::use_new_diskstream ()
68 {
69         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
70
71         if (_flags & Hidden) {
72                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
73         } else {
74                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
75         }
76
77         assert(_mode != Destructive);
78
79         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
80         ds->do_refill_with_alloc ();
81         ds->set_block_size (_session.get_block_size ());
82
83         set_diskstream (ds);
84 }
85
86 void
87 MidiTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
88 {
89         Track::set_diskstream (ds);
90         
91         _diskstream->set_track (this);
92         _diskstream->set_destructive (_mode == Destructive);
93
94         _diskstream->set_record_enabled (false);
95         //_diskstream->monitor_input (false);
96
97         DiskstreamChanged (); /* EMIT SIGNAL */
98 }
99
100 boost::shared_ptr<MidiDiskstream>
101 MidiTrack::midi_diskstream() const
102 {
103         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
104 }
105
106 int
107 MidiTrack::set_state (const XMLNode& node, int version)
108 {
109         return _set_state (node, version, true);
110 }
111
112 int
113 MidiTrack::_set_state (const XMLNode& node, int version, bool call_base)
114 {
115         const XMLProperty *prop;
116         XMLNodeConstIterator iter;
117
118         if (Route::_set_state (node, version, call_base)) {
119                 return -1;
120         }
121
122         // No destructive MIDI tracks (yet?)
123         _mode = Normal;
124
125         if ((prop = node.property (X_("note-mode"))) != 0) {
126                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
127         } else {
128                 _note_mode = Sustained;
129         }
130
131         if ((prop = node.property ("midi-thru")) != 0) {
132                 set_midi_thru (prop->value() == "yes");
133         }
134
135         if ((prop = node.property ("default-channel")) != 0) {
136                 set_default_channel ((uint8_t) atoi (prop->value()));
137         }
138
139         XMLNodeList nlist;
140         XMLNodeConstIterator niter;
141         XMLNode *child;
142
143         nlist = node.children();
144         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
145                 child = *niter;
146
147                 if (child->name() == X_("recenable")) {
148                         _rec_enable_control->set_state (*child, version);
149                         _session.add_controllable (_rec_enable_control);
150                 }
151         }
152
153         if (version >= 3000) {
154                 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
155                         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *child));
156                         ds->do_refill_with_alloc ();
157                         set_diskstream (ds);
158                 }
159         }
160
161         pending_state = const_cast<XMLNode*> (&node);
162
163         if (_session.state_of_the_state() & Session::Loading) {
164                 _session.StateReady.connect_same_thread (*this, boost::bind (&MidiTrack::set_state_part_two, this));
165         } else {
166                 set_state_part_two ();
167         }
168
169         return 0;
170 }
171
172 XMLNode&
173 MidiTrack::state(bool full_state)
174 {
175         XMLNode& root (Route::state(full_state));
176         XMLNode* freeze_node;
177         char buf[64];
178
179         if (_freeze_record.playlist) {
180                 XMLNode* inode;
181
182                 freeze_node = new XMLNode (X_("freeze-info"));
183                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
184                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
185
186                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
187                         inode = new XMLNode (X_("processor"));
188                         (*i)->id.print (buf, sizeof(buf));
189                         inode->add_property (X_("id"), buf);
190                         inode->add_child_copy ((*i)->state);
191
192                         freeze_node->add_child_nocopy (*inode);
193                 }
194
195                 root.add_child_nocopy (*freeze_node);
196         }
197
198         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
199         root.add_child_nocopy (_rec_enable_control->get_state());
200         root.add_child_nocopy (_diskstream->get_state ());
201
202         root.add_property ("step-editing", (_step_editing ? "yes" : "no"));
203         root.add_property ("note-mode", enum_2_string (_note_mode));
204         root.add_property ("midi-thru", (_midi_thru ? "yes" : "no"));
205         snprintf (buf, sizeof (buf), "%d", (int) _default_channel);
206         root.add_property ("default-channel", buf);
207
208         return root;
209 }
210
211 void
212 MidiTrack::set_state_part_two ()
213 {
214         XMLNode* fnode;
215         XMLProperty* prop;
216         LocaleGuard lg (X_("POSIX"));
217
218         /* This is called after all session state has been restored but before
219            have been made ports and connections are established.
220         */
221
222         if (pending_state == 0) {
223                 return;
224         }
225
226         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
227
228                 _freeze_record.state = Frozen;
229
230                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
231                         delete *i;
232                 }
233                 _freeze_record.processor_info.clear ();
234
235                 if ((prop = fnode->property (X_("playlist"))) != 0) {
236                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
237                         if (pl) {
238                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
239                         } else {
240                                 _freeze_record.playlist.reset();
241                                 _freeze_record.state = NoFreeze;
242                         return;
243                         }
244                 }
245
246                 if ((prop = fnode->property (X_("state"))) != 0) {
247                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
248                 }
249
250                 XMLNodeConstIterator citer;
251                 XMLNodeList clist = fnode->children();
252
253                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
254                         if ((*citer)->name() != X_("processor")) {
255                                 continue;
256                         }
257
258                         if ((prop = (*citer)->property (X_("id"))) == 0) {
259                                 continue;
260                         }
261
262                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
263                                                                                    boost::shared_ptr<Processor>());
264                         frii->id = prop->value ();
265                         _freeze_record.processor_info.push_back (frii);
266                 }
267         }
268
269         if ((fnode = find_named_node (*pending_state, X_("Diskstream"))) != 0) {
270                 boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, *fnode));
271                 ds->do_refill_with_alloc ();
272                 ds->set_block_size (_session.get_block_size ());
273                 set_diskstream (ds);
274         }
275
276         return;
277 }
278
279 int
280 MidiTrack::roll (nframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick,
281                  bool can_record, bool rec_monitors_input, bool& needs_butler)
282 {
283         int dret;
284         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
285
286         {
287                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
288                 if (lm.locked()) {
289                         // automation snapshot can also be called from the non-rt context
290                         // and it uses the redirect list, so we take the lock out here
291                         automation_snapshot (start_frame);
292                 }
293         }
294
295         if (n_outputs().n_total() == 0 && _processors.empty()) {
296                 return 0;
297         }
298
299         if (!_active) {
300                 silence (nframes);
301                 return 0;
302         }
303
304         nframes_t transport_frame = _session.transport_frame();
305
306
307         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
308                 /* need to do this so that the diskstream sets its
309                    playback distance to zero, thus causing diskstream::commit
310                    to do nothing.
311                    */
312                 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input, needs_butler);
313         }
314
315         _silent = false;
316
317         if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input, needs_butler)) != 0) {
318                 silence (nframes);
319                 return dret;
320         }
321
322         /* special condition applies */
323
324         if (_meter_point == MeterInput) {
325                 _input->process_input (_meter, start_frame, end_frame, nframes);
326         }
327
328         if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
329
330                 /* not actually recording, but we want to hear the input material anyway,
331                    at least potentially (depending on monitoring options)
332                 */
333
334                 passthru (start_frame, end_frame, nframes, 0);
335
336         } else {
337                 /*
338                    XXX is it true that the earlier test on n_outputs()
339                    means that we can avoid checking it again here? i think
340                    so, because changing the i/o configuration of an IO
341                    requires holding the AudioEngine lock, which we hold
342                    while in the process() tree.
343                    */
344
345
346                 /* copy the diskstream data to all output buffers */
347
348                 //const size_t limit = n_process_buffers().n_audio();
349                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
350                 MidiBuffer& mbuf (bufs.get_midi (0));
351
352                 diskstream->get_playback (mbuf, start_frame, end_frame);
353
354                 /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
355
356                 write_out_of_band_data (bufs, start_frame, end_frame, nframes);
357
358                 process_output_buffers (bufs, start_frame, end_frame, nframes,
359                                         (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
360
361         }
362
363         _main_outs->flush (nframes, end_frame - start_frame - 1);
364
365         return 0;
366 }
367
368 int
369 MidiTrack::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
370                     bool state_changing, bool can_record, bool rec_monitors_input)
371 {
372         int ret = Track::no_roll (nframes, start_frame, end_frame, state_changing, can_record, rec_monitors_input);
373
374         if (ret == 0 && _diskstream->record_enabled() && _step_editing) {
375                 push_midi_input_to_step_edit_ringbuffer (nframes);
376         }
377
378         return ret;
379 }
380
381 void
382 MidiTrack::handle_transport_stopped (bool abort, bool did_locate, bool flush_processors)
383 {
384
385         _main_outs->transport_stopped ();
386         Route::handle_transport_stopped (abort, did_locate, flush_processors);
387 }
388
389
390 void
391 MidiTrack::push_midi_input_to_step_edit_ringbuffer (nframes_t nframes)
392 {
393         PortSet& ports (_input->ports());
394
395         for (PortSet::iterator p = ports.begin(DataType::MIDI); p != ports.end(DataType::MIDI); ++p) {
396
397                 Buffer& b (p->get_buffer (nframes));
398                 const MidiBuffer* const mb = dynamic_cast<MidiBuffer*>(&b);
399                 assert (mb);
400
401                 for (MidiBuffer::const_iterator e = mb->begin(); e != mb->end(); ++e) {
402
403                         const Evoral::MIDIEvent<nframes_t> ev(*e, false);
404
405                         /* we don't care about the time for this purpose */
406
407                         _step_edit_ring_buffer.write (0, ev.type(), ev.size(), ev.buffer());
408                 }
409         }
410 }
411
412 void
413 MidiTrack::write_out_of_band_data (BufferSet& bufs, sframes_t /*start*/, sframes_t /*end*/, nframes_t nframes)
414 {
415         // Append immediate events
416         MidiBuffer& buf (bufs.get_midi (0));
417         _immediate_events.read (buf, 0, 0, nframes - 1); // all stamps = 0
418
419         // MIDI thru: send incoming data "through" output
420         if (_midi_thru && _session.transport_speed() != 0.0f && _input->n_ports().n_midi()) {
421                 buf.merge_in_place (_input->midi(0)->get_midi_buffer(nframes));
422         }
423 }
424
425 int
426 MidiTrack::export_stuff (BufferSet& /*bufs*/, nframes_t /*nframes*/, sframes_t /*end_frame*/)
427 {
428         return -1;
429 }
430
431 void
432 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
433 {
434         Route::set_latency_delay (longest_session_latency);
435         _diskstream->set_roll_delay (_roll_delay);
436 }
437
438 boost::shared_ptr<Region>
439 MidiTrack::bounce (InterThreadInfo& /*itt*/)
440 {
441         throw;
442         // vector<MidiSource*> srcs;
443         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
444         return boost::shared_ptr<Region> ();
445 }
446
447
448 boost::shared_ptr<Region>
449 MidiTrack::bounce_range (nframes_t /*start*/, nframes_t /*end*/, InterThreadInfo& /*itt*/, bool /*enable_processing*/)
450 {
451         throw;
452         //vector<MidiSource*> srcs;
453         //return _session.write_one_track (*this, start, end, false, srcs, itt);
454         return boost::shared_ptr<Region> ();
455 }
456
457 void
458 MidiTrack::freeze_me (InterThreadInfo& /*itt*/)
459 {
460 }
461
462 void
463 MidiTrack::unfreeze ()
464 {
465         _freeze_record.state = UnFrozen;
466         FreezeChange (); /* EMIT SIGNAL */
467 }
468
469 void
470 MidiTrack::set_note_mode (NoteMode m)
471 {
472         _note_mode = m;
473         midi_diskstream()->set_note_mode(m);
474 }
475
476 void
477 MidiTrack::midi_panic()
478 {
479         for (uint8_t channel = 0; channel <= 0xF; channel++) {
480                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
481                 write_immediate_event(3, ev);
482                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
483                 write_immediate_event(3, ev);
484                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
485                 write_immediate_event(3, ev);
486         }
487 }
488
489 /** \return true on success, false on failure (no buffer space left)
490  */
491 bool
492 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
493 {
494         if (!Evoral::midi_event_is_valid(buf, size)) {
495                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
496                 return false;
497         }
498         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
499         return (_immediate_events.write(0, type, size, buf) == size);
500 }
501
502 void
503 MidiTrack::MidiControl::set_value(float val)
504 {
505         bool valid = false;
506         if (isinf(val)) {
507                 cerr << "MIDIControl value is infinity" << endl;
508         } else if (isnan(val)) {
509                 cerr << "MIDIControl value is NaN" << endl;
510         } else if (val < _list->parameter().min()) {
511                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
512         } else if (val > _list->parameter().max()) {
513                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
514         } else {
515                 valid = true;
516         }
517
518         if (!valid) {
519                 return;
520         }
521
522         assert(val <= _list->parameter().max());
523         if ( ! automation_playback()) {
524                 size_t size = 3;
525                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
526                 switch(_list->parameter().type()) {
527                 case MidiCCAutomation:
528                         ev[0] += MIDI_CMD_CONTROL;
529                         ev[1] = _list->parameter().id();
530                         ev[2] = int(val);
531                         break;
532
533                 case MidiPgmChangeAutomation:
534                         size = 2;
535                         ev[0] += MIDI_CMD_PGM_CHANGE;
536                         ev[1] = int(val);
537                         break;
538
539                 case MidiChannelPressureAutomation:
540                         size = 2;
541                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
542                         ev[1] = int(val);
543                         break;
544
545                 case MidiPitchBenderAutomation:
546                         ev[0] += MIDI_CMD_BENDER;
547                         ev[1] = 0x7F & int(val);
548                         ev[2] = 0x7F & (int(val) >> 7);
549                         break;
550
551                 default:
552                         assert(false);
553                 }
554                 _route->write_immediate_event(size,  ev);
555         }
556
557         AutomationControl::set_value(val);
558 }
559
560 void
561 MidiTrack::set_step_editing (bool yn)
562 {
563         _step_editing = yn;
564 }
565
566 void
567 MidiTrack::set_default_channel (uint8_t chn)
568 {
569         _default_channel = std::min ((unsigned int) chn, 15U);
570 }
571
572 void
573 MidiTrack::set_midi_thru (bool yn)
574 {
575         _midi_thru = yn;
576 }
577
578 boost::shared_ptr<SMFSource>
579 MidiTrack::write_source (uint32_t n)
580 {
581         return midi_diskstream()->write_source ();
582 }
583
584 void
585 MidiTrack::set_channel_mode (ChannelMode mode, uint16_t mask)
586 {
587         midi_diskstream()->set_channel_mode (mode, mask);
588 }
589
590 ChannelMode
591 MidiTrack::get_channel_mode ()
592 {
593         return midi_diskstream()->get_channel_mode ();
594 }
595
596 uint16_t
597 MidiTrack::get_channel_mask ()
598 {
599         return midi_diskstream()->get_channel_mask ();
600 }
601
602 boost::shared_ptr<MidiPlaylist>
603 MidiTrack::midi_playlist ()
604 {
605         return midi_diskstream()->midi_playlist ();
606 }