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