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