Wouldn't it be nice if plugin presets had a description/comment?
[ardour.git] / libs / ardour / port_manager.cc
1 /*
2     Copyright (C) 2013 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef COMPILER_MSVC
21 #include <io.h> // Microsoft's nearest equivalent to <unistd.h>
22 #include <ardourext/misc.h>
23 #else
24 #include <regex.h>
25 #endif
26
27 #include <glibmm/fileutils.h>
28 #include <glibmm/miscutils.h>
29
30 #include "pbd/error.h"
31
32 #include "ardour/async_midi_port.h"
33 #include "ardour/audio_backend.h"
34 #include "ardour/audio_port.h"
35 #include "ardour/debug.h"
36 #include "ardour/filesystem_paths.h"
37 #include "ardour/midi_port.h"
38 #include "ardour/midiport_manager.h"
39 #include "ardour/port_manager.h"
40 #include "ardour/profile.h"
41 #include "ardour/rt_tasklist.h"
42 #include "ardour/session.h"
43 #include "ardour/types_convert.h"
44
45 #include "pbd/i18n.h"
46
47 using namespace ARDOUR;
48 using namespace PBD;
49 using std::string;
50 using std::vector;
51
52 PortManager::PortManager ()
53         : ports (new Ports)
54         , _port_remove_in_progress (false)
55         , _port_deletions_pending (8192) /* ick, arbitrary sizing */
56         , midi_info_dirty (true)
57 {
58         load_midi_port_info ();
59 }
60
61 void
62 PortManager::clear_pending_port_deletions ()
63 {
64         Port* p;
65
66         DEBUG_TRACE (DEBUG::Ports, string_compose ("pending port deletions: %1\n", _port_deletions_pending.read_space()));
67
68         while (_port_deletions_pending.read (&p, 1) == 1) {
69                 delete p;
70         }
71 }
72
73 void
74 PortManager::remove_all_ports ()
75 {
76         /* make sure that JACK callbacks that will be invoked as we cleanup
77          * ports know that they have nothing to do.
78          */
79
80         _port_remove_in_progress = true;
81
82         /* process lock MUST be held by caller
83         */
84
85         {
86                 RCUWriter<Ports> writer (ports);
87                 boost::shared_ptr<Ports> ps = writer.get_copy ();
88                 ps->clear ();
89         }
90
91         /* clear dead wood list in RCU */
92
93         ports.flush ();
94
95         /* clear out pending port deletion list. we know this is safe because
96          * the auto connect thread in Session is already dead when this is
97          * done. It doesn't use shared_ptr<Port> anyway.
98          */
99
100         _port_deletions_pending.reset ();
101
102         _port_remove_in_progress = false;
103 }
104
105
106 string
107 PortManager::make_port_name_relative (const string& portname) const
108 {
109         if (!_backend) {
110                 return portname;
111         }
112
113         string::size_type colon = portname.find (':');
114
115         if (colon == string::npos) {
116                 return portname;
117         }
118
119         if (portname.substr (0, colon) == _backend->my_name()) {
120                 return portname.substr (colon+1);
121         }
122
123         return portname;
124 }
125
126 string
127 PortManager::make_port_name_non_relative (const string& portname) const
128 {
129         string str;
130
131         if (portname.find_first_of (':') != string::npos) {
132                 return portname;
133         }
134
135         str  = _backend->my_name();
136         str += ':';
137         str += portname;
138
139         return str;
140 }
141
142 std::string
143 PortManager::get_pretty_name_by_name(const std::string& portname) const
144 {
145         PortEngine::PortHandle ph = _backend->get_port_by_name (portname);
146         if (ph) {
147                 std::string value;
148                 std::string type;
149                 if (0 == _backend->get_port_property (ph,
150                                         "http://jackaudio.org/metadata/pretty-name",
151                                         value, type))
152                 {
153                         return value;
154                 }
155         }
156         return "";
157 }
158
159 bool
160 PortManager::port_is_mine (const string& portname) const
161 {
162         if (!_backend) {
163                 return true;
164         }
165
166         string self = _backend->my_name();
167
168         if (portname.find_first_of (':') != string::npos) {
169                 if (portname.substr (0, self.length ()) != self) {
170                         return false;
171                 }
172         }
173
174         return true;
175 }
176
177 bool
178 PortManager::port_is_physical (const std::string& portname) const
179 {
180         if (!_backend) {
181                 return false;
182         }
183
184         PortEngine::PortHandle ph = _backend->get_port_by_name (portname);
185         if (!ph) {
186                 return false;
187         }
188
189         return _backend->port_is_physical (ph);
190 }
191
192 void
193 PortManager::filter_midi_ports (vector<string>& ports, MidiPortFlags include, MidiPortFlags exclude)
194 {
195
196         if (!include && !exclude) {
197                 return;
198         }
199
200         {
201                 Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
202
203                 fill_midi_port_info_locked ();
204
205                 for (vector<string>::iterator si = ports.begin(); si != ports.end(); ) {
206
207                         MidiPortInfo::iterator x = midi_port_info.find (*si);
208
209                         if (x == midi_port_info.end()) {
210                                 ++si;
211                                 continue;
212                         }
213
214                         MidiPortInformation& mpi (x->second);
215
216                         if (mpi.pretty_name.empty()) {
217                                 /* no information !!! */
218                                 ++si;
219                                 continue;
220                         }
221
222                         if (include) {
223                                 if ((mpi.properties & include) != include) {
224                                         /* properties do not include requested ones */
225                                         si = ports.erase (si);
226                                         continue;
227                                 }
228                         }
229
230                         if (exclude) {
231                                 if ((mpi.properties & exclude)) {
232                                         /* properties include ones to avoid */
233                                         si = ports.erase (si);
234                                         continue;
235                                 }
236                         }
237
238                         ++si;
239                 }
240         }
241 }
242
243 void
244 PortManager::get_physical_outputs (DataType type, std::vector<std::string>& s, MidiPortFlags include, MidiPortFlags exclude)
245 {
246         if (!_backend) {
247                 s.clear ();
248                 return;
249         }
250         _backend->get_physical_outputs (type, s);
251         filter_midi_ports (s, include, exclude);
252 }
253
254 void
255 PortManager::get_physical_inputs (DataType type, std::vector<std::string>& s, MidiPortFlags include, MidiPortFlags exclude)
256 {
257         if (!_backend) {
258                 s.clear ();
259                 return;
260         }
261
262         _backend->get_physical_inputs (type, s);
263         filter_midi_ports (s, include, exclude);
264 }
265
266 ChanCount
267 PortManager::n_physical_outputs () const
268 {
269         if (!_backend) {
270                 return ChanCount::ZERO;
271         }
272
273         return _backend->n_physical_outputs ();
274 }
275
276 ChanCount
277 PortManager::n_physical_inputs () const
278 {
279         if (!_backend) {
280                 return ChanCount::ZERO;
281         }
282         return _backend->n_physical_inputs ();
283 }
284
285 /** @param name Full or short name of port
286  *  @return Corresponding Port or 0.
287  */
288 boost::shared_ptr<Port>
289 PortManager::get_port_by_name (const string& portname)
290 {
291         if (!_backend) {
292                 return boost::shared_ptr<Port>();
293         }
294
295         if (!port_is_mine (portname)) {
296                 /* not an ardour port */
297                 return boost::shared_ptr<Port> ();
298         }
299
300         boost::shared_ptr<Ports> pr = ports.reader();
301         std::string rel = make_port_name_relative (portname);
302         Ports::iterator x = pr->find (rel);
303
304         if (x != pr->end()) {
305                 /* its possible that the port was renamed by some 3rd party and
306                  * we don't know about it. check for this (the check is quick
307                  * and cheap), and if so, rename the port (which will alter
308                  * the port map as a side effect).
309                  */
310                 const std::string check = make_port_name_relative (_backend->get_port_name (x->second->port_handle()));
311                 if (check != rel) {
312                         x->second->set_name (check);
313                 }
314                 return x->second;
315         }
316
317         return boost::shared_ptr<Port> ();
318 }
319
320 void
321 PortManager::port_renamed (const std::string& old_relative_name, const std::string& new_relative_name)
322 {
323         RCUWriter<Ports> writer (ports);
324         boost::shared_ptr<Ports> p = writer.get_copy();
325         Ports::iterator x = p->find (old_relative_name);
326
327         if (x != p->end()) {
328                 boost::shared_ptr<Port> port = x->second;
329                 p->erase (x);
330                 p->insert (make_pair (new_relative_name, port));
331         }
332 }
333
334 int
335 PortManager::get_ports (DataType type, PortList& pl)
336 {
337         boost::shared_ptr<Ports> plist = ports.reader();
338         for (Ports::iterator p = plist->begin(); p != plist->end(); ++p) {
339                 if (p->second->type() == type) {
340                         pl.push_back (p->second);
341                 }
342         }
343         return pl.size();
344 }
345
346 int
347 PortManager::get_ports (const string& port_name_pattern, DataType type, PortFlags flags, vector<string>& s)
348 {
349         s.clear();
350
351         if (!_backend) {
352                 return 0;
353         }
354
355         return _backend->get_ports (port_name_pattern, type, flags, s);
356 }
357
358 void
359 PortManager::port_registration_failure (const std::string& portname)
360 {
361         if (!_backend) {
362                 return;
363         }
364
365         string full_portname = _backend->my_name();
366         full_portname += ':';
367         full_portname += portname;
368
369
370         PortEngine::PortHandle p = _backend->get_port_by_name (full_portname);
371         string reason;
372
373         if (p) {
374                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
375         } else {
376                 reason = string_compose (_("No more ports are available. You will need to stop %1 and restart with more ports if you need this many tracks."), PROGRAM_NAME);
377         }
378
379         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
380 }
381
382 struct PortDeleter
383 {
384         void operator() (Port* p) {
385                 AudioEngine::instance()->add_pending_port_deletion (p);
386         }
387 };
388
389 boost::shared_ptr<Port>
390 PortManager::register_port (DataType dtype, const string& portname, bool input, bool async, PortFlags flags)
391 {
392         boost::shared_ptr<Port> newport;
393
394         /* limit the possible flags that can be set */
395
396         flags = PortFlags (flags & (Hidden|Shadow|IsTerminal));
397
398         try {
399                 if (dtype == DataType::AUDIO) {
400                         DEBUG_TRACE (DEBUG::Ports, string_compose ("registering AUDIO port %1, input %2\n",
401                                                                    portname, input));
402                         newport.reset (new AudioPort (portname, PortFlags ((input ? IsInput : IsOutput) | flags)),
403                                        PortDeleter());
404                 } else if (dtype == DataType::MIDI) {
405                         if (async) {
406                                 DEBUG_TRACE (DEBUG::Ports, string_compose ("registering ASYNC MIDI port %1, input %2\n",
407                                                                            portname, input));
408                                 newport.reset (new AsyncMIDIPort (portname, PortFlags ((input ? IsInput : IsOutput) | flags)),
409                                                PortDeleter());
410                         } else {
411                                 DEBUG_TRACE (DEBUG::Ports, string_compose ("registering MIDI port %1, input %2\n",
412                                                                            portname, input));
413                                 newport.reset (new MidiPort (portname, PortFlags ((input ? IsInput : IsOutput) | flags)),
414                                                PortDeleter());
415                         }
416                 } else {
417                         throw PortRegistrationFailure("unable to create port (unknown type)");
418                 }
419
420                 RCUWriter<Ports> writer (ports);
421                 boost::shared_ptr<Ports> ps = writer.get_copy ();
422                 ps->insert (make_pair (make_port_name_relative (portname), newport));
423
424                 /* writer goes out of scope, forces update */
425
426         }
427
428         catch (PortRegistrationFailure& err) {
429                 throw err;
430         } catch (std::exception& e) {
431                 throw PortRegistrationFailure(string_compose(
432                                 _("unable to create port: %1"), e.what()).c_str());
433         } catch (...) {
434                 throw PortRegistrationFailure("unable to create port (unknown error)");
435         }
436
437         DEBUG_TRACE (DEBUG::Ports, string_compose ("\t%2 port registration success, ports now = %1\n", ports.reader()->size(), this));
438         return newport;
439 }
440
441 boost::shared_ptr<Port>
442 PortManager::register_input_port (DataType type, const string& portname, bool async, PortFlags extra_flags)
443 {
444         return register_port (type, portname, true, async, extra_flags);
445 }
446
447 boost::shared_ptr<Port>
448 PortManager::register_output_port (DataType type, const string& portname, bool async, PortFlags extra_flags)
449 {
450         return register_port (type, portname, false, async, extra_flags);
451 }
452
453 int
454 PortManager::unregister_port (boost::shared_ptr<Port> port)
455 {
456         /* This is a little subtle. We do not call the backend's port
457          * unregistration code from here. That is left for the Port
458          * destructor. We are trying to drop references to the Port object
459          * here, so that its destructor will run and it will unregister itself.
460          */
461
462         /* caller must hold process lock */
463
464         {
465                 RCUWriter<Ports> writer (ports);
466                 boost::shared_ptr<Ports> ps = writer.get_copy ();
467                 Ports::iterator x = ps->find (make_port_name_relative (port->name()));
468
469                 if (x != ps->end()) {
470                         DEBUG_TRACE (DEBUG::Ports, string_compose ("removing %1 from port map (uc=%2)\n", port->name(), port.use_count()));
471                         ps->erase (x);
472                 }
473
474                 /* writer goes out of scope, forces update */
475         }
476
477         ports.flush ();
478
479         return 0;
480 }
481
482 bool
483 PortManager::connected (const string& port_name)
484 {
485         if (!_backend) {
486                 return false;
487         }
488
489         PortEngine::PortHandle handle = _backend->get_port_by_name (port_name);
490
491         if (!handle) {
492                 return false;
493         }
494
495         return _backend->connected (handle);
496 }
497
498 bool
499 PortManager::physically_connected (const string& port_name)
500 {
501         if (!_backend) {
502                 return false;
503         }
504
505         PortEngine::PortHandle handle = _backend->get_port_by_name (port_name);
506
507         if (!handle) {
508                 return false;
509         }
510
511         return _backend->physically_connected (handle);
512 }
513
514 int
515 PortManager::get_connections (const string& port_name, std::vector<std::string>& s)
516 {
517         if (!_backend) {
518                 s.clear ();
519                 return 0;
520         }
521
522         PortEngine::PortHandle handle = _backend->get_port_by_name (port_name);
523
524         if (!handle) {
525                 s.clear ();
526                 return 0;
527         }
528
529         return _backend->get_connections (handle, s);
530 }
531
532 int
533 PortManager::connect (const string& source, const string& destination)
534 {
535         int ret;
536
537         string s = make_port_name_non_relative (source);
538         string d = make_port_name_non_relative (destination);
539
540         boost::shared_ptr<Port> src = get_port_by_name (s);
541         boost::shared_ptr<Port> dst = get_port_by_name (d);
542
543         if (src) {
544                 ret = src->connect (d);
545         } else if (dst) {
546                 ret = dst->connect (s);
547         } else {
548                 /* neither port is known to us ...hand-off to the PortEngine
549                  */
550                 if (_backend) {
551                         ret = _backend->connect (s, d);
552                 } else {
553                         ret = -1;
554                 }
555         }
556
557         if (ret > 0) {
558                 /* already exists - no error, no warning */
559         } else if (ret < 0) {
560                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
561                                         source, s, destination, d)
562                       << endmsg;
563         }
564
565         return ret;
566 }
567
568 int
569 PortManager::disconnect (const string& source, const string& destination)
570 {
571         int ret;
572
573         string s = make_port_name_non_relative (source);
574         string d = make_port_name_non_relative (destination);
575
576         boost::shared_ptr<Port> src = get_port_by_name (s);
577         boost::shared_ptr<Port> dst = get_port_by_name (d);
578
579         if (src) {
580                 ret = src->disconnect (d);
581         } else if (dst) {
582                 ret = dst->disconnect (s);
583         } else {
584                 /* neither port is known to us ...hand-off to the PortEngine
585                  */
586                 if (_backend) {
587                         ret = _backend->disconnect (s, d);
588                 } else {
589                         ret = -1;
590                 }
591         }
592         return ret;
593 }
594
595 int
596 PortManager::disconnect (boost::shared_ptr<Port> port)
597 {
598         return port->disconnect_all ();
599 }
600
601 int
602 PortManager::disconnect (std::string const & name)
603 {
604         PortEngine::PortHandle ph = _backend->get_port_by_name (name);
605         if (ph) {
606                 return _backend->disconnect_all (ph);
607         }
608         return -2;
609 }
610
611 int
612 PortManager::reestablish_ports ()
613 {
614         Ports::iterator i;
615
616         boost::shared_ptr<Ports> p = ports.reader ();
617
618         DEBUG_TRACE (DEBUG::Ports, string_compose ("reestablish %1 ports\n", p->size()));
619
620         for (i = p->begin(); i != p->end(); ++i) {
621                 if (i->second->reestablish ()) {
622                         error << string_compose (_("Re-establising port %1 failed"), i->second->name()) << endmsg;
623                         std::cerr << string_compose (_("Re-establising port %1 failed"), i->second->name()) << std::endl;
624                         break;
625                 }
626         }
627
628         if (i != p->end()) {
629                 /* failed */
630                 remove_all_ports ();
631                 return -1;
632         }
633
634         return 0;
635 }
636
637 int
638 PortManager::reconnect_ports ()
639 {
640         boost::shared_ptr<Ports> p = ports.reader ();
641
642         if (!Profile->get_trx()) {
643                 /* re-establish connections */
644
645                 DEBUG_TRACE (DEBUG::Ports, string_compose ("reconnect %1 ports\n", p->size()));
646
647                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
648                         i->second->reconnect ();
649                 }
650         }
651
652         return 0;
653 }
654
655 void
656 PortManager::connect_callback (const string& a, const string& b, bool conn)
657 {
658         boost::shared_ptr<Port> port_a;
659         boost::shared_ptr<Port> port_b;
660         Ports::iterator x;
661         boost::shared_ptr<Ports> pr = ports.reader ();
662
663         x = pr->find (make_port_name_relative (a));
664         if (x != pr->end()) {
665                 port_a = x->second;
666         }
667
668         x = pr->find (make_port_name_relative (b));
669         if (x != pr->end()) {
670                 port_b = x->second;
671         }
672
673         if (conn) {
674                 if (port_a && !port_b) {
675                         port_a->increment_external_connections ();
676                 } else if (port_b && !port_a) {
677                         port_b->increment_external_connections ();
678                 }
679         } else {
680                 if (port_a && !port_b) {
681                         port_a->decrement_external_connections ();
682                 } else if (port_b && !port_a) {
683                         port_b->decrement_external_connections ();
684                 }
685         }
686
687         PortConnectedOrDisconnected (
688                 port_a, a,
689                 port_b, b,
690                 conn
691                 ); /* EMIT SIGNAL */
692 }
693
694 void
695 PortManager::registration_callback ()
696 {
697         if (!_port_remove_in_progress) {
698
699                 {
700                         Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
701                         midi_info_dirty = true;
702                 }
703
704                 PortRegisteredOrUnregistered (); /* EMIT SIGNAL */
705         }
706 }
707
708 bool
709 PortManager::can_request_input_monitoring () const
710 {
711         if (!_backend) {
712                 return false;
713         }
714
715         return _backend->can_monitor_input ();
716 }
717
718 void
719 PortManager::request_input_monitoring (const string& name, bool yn) const
720 {
721         if (!_backend) {
722                 return;
723         }
724
725         PortEngine::PortHandle ph = _backend->get_port_by_name (name);
726
727         if (ph) {
728                 _backend->request_input_monitoring (ph, yn);
729         }
730 }
731
732 void
733 PortManager::ensure_input_monitoring (const string& name, bool yn) const
734 {
735         if (!_backend) {
736                 return;
737         }
738
739         PortEngine::PortHandle ph = _backend->get_port_by_name (name);
740
741         if (ph) {
742                 _backend->ensure_input_monitoring (ph, yn);
743         }
744 }
745
746 uint32_t
747 PortManager::port_name_size() const
748 {
749         if (!_backend) {
750                 return 0;
751         }
752
753         return _backend->port_name_size ();
754 }
755
756 string
757 PortManager::my_name() const
758 {
759         if (!_backend) {
760                 return string();
761         }
762
763         return _backend->my_name();
764 }
765
766 int
767 PortManager::graph_order_callback ()
768 {
769         if (!_port_remove_in_progress) {
770                 GraphReordered(); /* EMIT SIGNAL */
771         }
772
773         return 0;
774 }
775
776 void
777 PortManager::cycle_start (pframes_t nframes, Session* s)
778 {
779         Port::set_global_port_buffer_offset (0);
780         Port::set_cycle_samplecnt (nframes);
781
782         _cycle_ports = ports.reader ();
783
784         /* TODO optimize
785          *  - when speed == 1.0, the resampler copies data without processing
786          *   it may (or may not) be more efficient to just run all in sequence.
787          *
788          *  - single sequential task for 'lightweight' tasks would make sense
789          *    (run it in parallel with 'heavy' resampling.
790          *    * output ports (sends_output()) only set a flag
791          *    * midi-ports only scale event timestamps
792          *
793          *  - a threshold parallel vs searial processing may be appropriate.
794          *    amount of work (how many connected ports are there, how
795          *    many resamplers need to run) vs. available CPU cores and semaphore
796          *    synchronization overhead.
797          *
798          *  - input ports: it would make sense to resample each input only once
799          *    (rather than resample into each ardour-owned input port).
800          *    A single external source-port may be connected to many ardour
801          *    input-ports. Currently re-sampling is per input.
802          */
803         if (s && s->rt_tasklist () && fabs (Port::speed_ratio ()) != 1.0) {
804                 RTTaskList::TaskList tl;
805                 for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
806                         tl.push_back (boost::bind (&Port::cycle_start, p->second, nframes));
807                 }
808                 s->rt_tasklist()->process (tl);
809         } else {
810                 for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
811                         p->second->cycle_start (nframes);
812                 }
813         }
814 }
815
816 void
817 PortManager::cycle_end (pframes_t nframes, Session* s)
818 {
819         // see optimzation note in ::cycle_start()
820         if (s && s->rt_tasklist () && fabs (Port::speed_ratio ()) != 1.0) {
821                 RTTaskList::TaskList tl;
822                 for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
823                         tl.push_back (boost::bind (&Port::cycle_end, p->second, nframes));
824                 }
825                 s->rt_tasklist()->process (tl);
826         } else {
827                 for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
828                         p->second->cycle_end (nframes);
829                 }
830         }
831
832         for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
833                 p->second->flush_buffers (nframes);
834         }
835
836         _cycle_ports.reset ();
837
838         /* we are done */
839 }
840
841 void
842 PortManager::silence (pframes_t nframes, Session *s)
843 {
844         for (Ports::iterator i = _cycle_ports->begin(); i != _cycle_ports->end(); ++i) {
845                 if (s && i->second == s->mtc_output_port ()) {
846                         continue;
847                 }
848                 if (s && i->second == s->midi_clock_output_port ()) {
849                         continue;
850                 }
851                 if (s && i->second == s->ltc_output_port ()) {
852                         continue;
853                 }
854                 if (boost::dynamic_pointer_cast<AsyncMIDIPort>(i->second)) {
855                         continue;
856                 }
857                 if (i->second->sends_output()) {
858                         i->second->get_buffer(nframes).silence(nframes);
859                 }
860         }
861 }
862
863 void
864 PortManager::silence_outputs (pframes_t nframes)
865 {
866         std::vector<std::string> port_names;
867         if (get_ports("", DataType::AUDIO, IsOutput, port_names)) {
868                 for (std::vector<std::string>::iterator p = port_names.begin(); p != port_names.end(); ++p) {
869                         if (!port_is_mine(*p)) {
870                                 continue;
871                         }
872                         PortEngine::PortHandle ph = _backend->get_port_by_name (*p);
873                         if (!ph) {
874                                 continue;
875                         }
876                         void *buf = _backend->get_buffer(ph, nframes);
877                         if (!buf) {
878                                 continue;
879                         }
880                         memset (buf, 0, sizeof(float) * nframes);
881                 }
882         }
883
884         if (get_ports("", DataType::MIDI, IsOutput, port_names)) {
885                 for (std::vector<std::string>::iterator p = port_names.begin(); p != port_names.end(); ++p) {
886                         if (!port_is_mine(*p)) {
887                                 continue;
888                         }
889                         PortEngine::PortHandle ph = _backend->get_port_by_name (*p);
890                         if (!ph) {
891                                 continue;
892                         }
893                         void *buf = _backend->get_buffer(ph, nframes);
894                         if (!buf) {
895                                 continue;
896                         }
897                         _backend->midi_clear (buf);
898                 }
899         }
900 }
901
902 void
903 PortManager::check_monitoring ()
904 {
905         for (Ports::iterator i = _cycle_ports->begin(); i != _cycle_ports->end(); ++i) {
906
907                 bool x;
908
909                 if (i->second->last_monitor() != (x = i->second->monitoring_input ())) {
910                         i->second->set_last_monitor (x);
911                         /* XXX I think this is dangerous, due to
912                            a likely mutex in the signal handlers ...
913                         */
914                         i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
915                 }
916         }
917 }
918
919 void
920 PortManager::cycle_end_fade_out (gain_t base_gain, gain_t gain_step, pframes_t nframes, Session* s)
921 {
922         // see optimzation note in ::cycle_start()
923         if (s && s->rt_tasklist () && fabs (Port::speed_ratio ()) != 1.0) {
924                 RTTaskList::TaskList tl;
925                 for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
926                         tl.push_back (boost::bind (&Port::cycle_end, p->second, nframes));
927                 }
928                 s->rt_tasklist()->process (tl);
929         } else {
930                 for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
931                         p->second->cycle_end (nframes);
932                 }
933         }
934
935         for (Ports::iterator p = _cycle_ports->begin(); p != _cycle_ports->end(); ++p) {
936                 p->second->flush_buffers (nframes);
937
938                 if (p->second->sends_output()) {
939
940                         boost::shared_ptr<AudioPort> ap = boost::dynamic_pointer_cast<AudioPort> (p->second);
941                         if (ap) {
942                                 Sample* s = ap->engine_get_whole_audio_buffer ();
943                                 gain_t g = base_gain;
944
945                                 for (pframes_t n = 0; n < nframes; ++n) {
946                                         *s++ *= g;
947                                         g -= gain_step;
948                                 }
949                         }
950                 }
951         }
952         _cycle_ports.reset ();
953         /* we are done */
954 }
955
956 PortEngine&
957 PortManager::port_engine()
958 {
959         assert (_backend);
960         return *_backend;
961 }
962
963 bool
964 PortManager::port_is_control_only (std::string const& name)
965 {
966         static regex_t compiled_pattern;
967         static string pattern;
968
969         if (pattern.empty()) {
970
971                 /* This is a list of regular expressions that match ports
972                  * related to physical MIDI devices that we do not want to
973                  * expose as normal physical ports.
974                  */
975
976                 const char * const control_only_ports[] = {
977                         X_(".*Ableton Push.*"),
978                         X_(".*FaderPort .*"),
979                         X_(".*FaderPort8 .*"),
980                         X_(".*FaderPort16 .*"),
981                         X_(".*FaderPort2 .*"),
982                         X_(".*US-2400 .*"),
983                         X_(".*Mackie .*"),
984                 };
985
986                 pattern = "(";
987                 for (size_t n = 0; n < sizeof (control_only_ports)/sizeof (control_only_ports[0]); ++n) {
988                         if (n > 0) {
989                                 pattern += '|';
990                         }
991                         pattern += control_only_ports[n];
992                 }
993                 pattern += ')';
994
995                 regcomp (&compiled_pattern, pattern.c_str(), REG_EXTENDED|REG_NOSUB);
996         }
997
998         return regexec (&compiled_pattern, name.c_str(), 0, 0, 0) == 0;
999 }
1000
1001 PortManager::MidiPortInformation
1002 PortManager::midi_port_information (std::string const & name)
1003 {
1004         Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1005
1006         fill_midi_port_info_locked ();
1007
1008         MidiPortInfo::iterator x = midi_port_info.find (name);
1009
1010         if (x != midi_port_info.end()) {
1011                 return x->second;
1012         }
1013
1014         return MidiPortInformation ();
1015 }
1016
1017 void
1018 PortManager::get_known_midi_ports (vector<string>& copy)
1019 {
1020         Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1021
1022         fill_midi_port_info_locked ();
1023
1024         for (MidiPortInfo::const_iterator x = midi_port_info.begin(); x != midi_port_info.end(); ++x) {
1025                 copy.push_back (x->first);
1026         }
1027 }
1028
1029 void
1030 PortManager::get_midi_selection_ports (vector<string>& copy)
1031 {
1032         Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1033
1034         fill_midi_port_info_locked ();
1035
1036         for (MidiPortInfo::const_iterator x = midi_port_info.begin(); x != midi_port_info.end(); ++x) {
1037                 if (x->second.properties & MidiPortSelection) {
1038                         copy.push_back (x->first);
1039                 }
1040         }
1041 }
1042
1043 void
1044 PortManager::set_midi_port_pretty_name (string const & port, string const & pretty)
1045 {
1046         {
1047                 Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1048
1049                 fill_midi_port_info_locked ();
1050
1051                 MidiPortInfo::iterator x = midi_port_info.find (port);
1052                 if (x == midi_port_info.end()) {
1053                         return;
1054                 }
1055                 x->second.pretty_name = pretty;
1056         }
1057
1058         /* push into back end */
1059
1060         PortEngine::PortHandle ph = _backend->get_port_by_name (port);
1061
1062         if (ph) {
1063                 _backend->set_port_property (ph, "http://jackaudio.org/metadata/pretty-name", pretty, string());
1064         }
1065
1066         MidiPortInfoChanged (); /* EMIT SIGNAL*/
1067 }
1068
1069 void
1070 PortManager::add_midi_port_flags (string const & port, MidiPortFlags flags)
1071 {
1072         bool emit = false;
1073
1074         {
1075                 Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1076
1077                 fill_midi_port_info_locked ();
1078
1079                 MidiPortInfo::iterator x = midi_port_info.find (port);
1080                 if (x != midi_port_info.end()) {
1081                         if ((x->second.properties & flags) != flags) { // at least one missing
1082                                 x->second.properties = MidiPortFlags (x->second.properties | flags);
1083                                 emit = true;
1084                         }
1085                 }
1086         }
1087
1088         if (emit) {
1089                 if (flags & MidiPortSelection) {
1090                         MidiSelectionPortsChanged (); /* EMIT SIGNAL */
1091                 }
1092
1093                 if (flags != MidiPortSelection) {
1094                         MidiPortInfoChanged (); /* EMIT SIGNAL */
1095                 }
1096
1097                 save_midi_port_info ();
1098         }
1099 }
1100
1101 void
1102 PortManager::remove_midi_port_flags (string const & port, MidiPortFlags flags)
1103 {
1104         bool emit = false;
1105
1106         {
1107                 Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1108
1109                 fill_midi_port_info_locked ();
1110
1111                 MidiPortInfo::iterator x = midi_port_info.find (port);
1112                 if (x != midi_port_info.end()) {
1113                         if (x->second.properties & flags) { // at least one is set
1114                                 x->second.properties = MidiPortFlags (x->second.properties & ~flags);
1115                                 emit = true;
1116                         }
1117                 }
1118         }
1119
1120         if (emit) {
1121                 if (flags & MidiPortSelection) {
1122                         MidiSelectionPortsChanged (); /* EMIT SIGNAL */
1123                 }
1124
1125                 if (flags != MidiPortSelection) {
1126                         MidiPortInfoChanged (); /* EMIT SIGNAL */
1127                 }
1128
1129                 save_midi_port_info ();
1130         }
1131 }
1132
1133 string
1134 PortManager::midi_port_info_file ()
1135 {
1136         return Glib::build_filename (user_config_directory(), X_("midi_port_info"));
1137 }
1138
1139 void
1140 PortManager::save_midi_port_info ()
1141 {
1142         string path = midi_port_info_file ();
1143
1144         XMLNode* root = new XMLNode (X_("MidiPortInfo"));
1145
1146         {
1147                 Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1148
1149                 if (midi_port_info.empty()) {
1150                         delete root;
1151                         return;
1152                 }
1153
1154                 for (MidiPortInfo::iterator i = midi_port_info.begin(); i != midi_port_info.end(); ++i) {
1155                         XMLNode* node = new XMLNode (X_("port"));
1156                         node->set_property (X_("name"), i->first);
1157                         node->set_property (X_("input"), i->second.input);
1158                         node->set_property (X_("properties"), i->second.properties);
1159                         root->add_child_nocopy (*node);
1160                 }
1161         }
1162
1163         XMLTree tree;
1164
1165         tree.set_root (root);
1166
1167         if (!tree.write (path)) {
1168                 error << string_compose (_("Could not save MIDI port info to %1"), path) << endmsg;
1169         }
1170 }
1171
1172 void
1173 PortManager::load_midi_port_info ()
1174 {
1175         string path = midi_port_info_file ();
1176         XMLTree tree;
1177
1178         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
1179                 return;
1180         }
1181
1182         if (!tree.read (path)) {
1183                 error << string_compose (_("Cannot load MIDI port info from %1"), path) << endmsg;
1184                 return;
1185         }
1186
1187         midi_port_info.clear ();
1188
1189         for (XMLNodeConstIterator i = tree.root()->children().begin(); i != tree.root()->children().end(); ++i) {
1190                 MidiPortInformation mpi;
1191                 string name;
1192
1193                 if (!(*i)->get_property (X_("name"), name) ||
1194                     !(*i)->get_property (X_("input"), mpi.input) ||
1195                     !(*i)->get_property (X_("properties"), mpi.properties)) {
1196                         continue;
1197                 }
1198
1199                 midi_port_info.insert (make_pair (name, mpi));
1200         }
1201 }
1202
1203 void
1204 PortManager::fill_midi_port_info ()
1205 {
1206         Glib::Threads::Mutex::Lock lm (midi_port_info_mutex);
1207         fill_midi_port_info_locked ();
1208 }
1209
1210 void
1211 PortManager::fill_midi_port_info_locked ()
1212 {
1213         /* MIDI info mutex MUST be held */
1214
1215         if (!midi_info_dirty) {
1216                 return;
1217         }
1218
1219         std::vector<string> ports;
1220
1221         AudioEngine::instance()->get_ports (string(), DataType::MIDI, IsOutput, ports);
1222
1223         for (vector<string>::iterator p = ports.begin(); p != ports.end(); ++p) {
1224
1225                 if (port_is_mine (*p)) {
1226                         continue;
1227                 }
1228
1229                 if (midi_port_info.find (*p) == midi_port_info.end()) {
1230                         MidiPortInformation mpi;
1231                         mpi.pretty_name = *p;
1232                         mpi.input = true;
1233
1234                         if (port_is_control_only (*p)) {
1235                                 mpi.properties = MidiPortFlags (mpi.properties | MidiPortControl);
1236                         }
1237 #ifdef LINUX
1238                         if ((*p.find (X_("Midi Through")) != string::npos ||
1239                              (*p).find (X_("Midi-Through")) != string::npos))
1240                         {
1241                                 mpi.properties = MidiPortFlags (mpi.properties | MidiPortVirtual);
1242                         }
1243 #endif
1244                         midi_port_info.insert (make_pair (*p, mpi));
1245                 }
1246         }
1247
1248         AudioEngine::instance()->get_ports (string(), DataType::MIDI, IsInput, ports);
1249
1250         for (vector<string>::iterator p = ports.begin(); p != ports.end(); ++p) {
1251
1252                 if (port_is_mine (*p)) {
1253                         continue;
1254                 }
1255
1256                 if (midi_port_info.find (*p) == midi_port_info.end()) {
1257                         MidiPortInformation mpi;
1258                         mpi.pretty_name = *p;
1259                         mpi.input = false;
1260
1261                         if (port_is_control_only (*p)) {
1262                                 mpi.properties = MidiPortFlags (mpi.properties | MidiPortControl);
1263                         }
1264 #ifdef LINUX
1265                         if ((*p.find (X_("Midi Through")) != string::npos ||
1266                              (*p).find (X_("Midi-Through")) != string::npos))
1267                         {
1268                                 mpi.properties = MidiPortFlags (mpi.properties | MidiPortVirtual);
1269                         }
1270 #endif
1271                         midi_port_info.insert (make_pair (*p, mpi));
1272                 }
1273         }
1274
1275         /* now push/pull pretty name information between backend and the
1276          * PortManager
1277          */
1278
1279         // rg: I don't understand what this attempts to solve
1280         //
1281         // Naming ports should be left to the backend:
1282         // Ardour cannot associate numeric IDs with corresponding hardware.
1283         // (see also 7dde6c3b)
1284
1285         for (MidiPortInfo::iterator x = midi_port_info.begin(); x != midi_port_info.end(); ++x) {
1286                 PortEngine::PortHandle ph = _backend->get_port_by_name (x->first);
1287
1288                 if (!ph) {
1289                         /* port info saved from some condition where this port
1290                          * existed, but no longer does (i.e. device unplugged
1291                          * at present). We don't remove it from midi_port_info.
1292                          */
1293                         continue;
1294                 }
1295
1296                 /* check with backend for pre-existing pretty name */
1297                 string value;
1298                 string type;
1299
1300                 if (0 == _backend->get_port_property (ph,
1301                                                       "http://jackaudio.org/metadata/pretty-name",
1302                                                       value, type)) {
1303                         x->second.pretty_name = value;
1304                 }
1305         }
1306
1307         midi_info_dirty = false;
1308 }