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