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