fix portengin get_ports() flags API
[ardour.git] / libs / backends / portaudio / portaudio_backend.cc
1 /*
2  * Copyright (C) 2015-2015 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2013 Paul Davis
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <regex.h>
21
22 #ifndef PLATFORM_WINDOWS
23 #include <sys/mman.h>
24 #include <sys/time.h>
25 #endif
26
27 #include <glibmm.h>
28
29 #include "portaudio_backend.h"
30 #include "rt_thread.h"
31
32 #include "pbd/compose.h"
33 #include "pbd/error.h"
34 #include "pbd/file_utils.h"
35 #include "ardour/filesystem_paths.h"
36 #include "ardour/port_manager.h"
37 #include "i18n.h"
38
39 using namespace ARDOUR;
40
41 static std::string s_instance_name;
42 size_t PortAudioBackend::_max_buffer_size = 8192;
43 std::vector<std::string> PortAudioBackend::_midi_options;
44 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_audio_device_status;
45
46 PortAudioBackend::PortAudioBackend (AudioEngine& e, AudioBackendInfo& info)
47         : AudioBackend (e, info)
48         , _pcmio (0)
49         , _run (false)
50         , _active (false)
51         , _freewheel (false)
52         , _measure_latency (false)
53         , _last_process_start (0)
54         , _audio_device("")
55         , _midi_driver_option(_("None"))
56         , _samplerate (48000)
57         , _samples_per_period (1024)
58         , _n_inputs (0)
59         , _n_outputs (0)
60         , _systemic_audio_input_latency (0)
61         , _systemic_audio_output_latency (0)
62         , _dsp_load (0)
63         , _processed_samples (0)
64         , _port_change_flag (false)
65 {
66         _instance_name = s_instance_name;
67         pthread_mutex_init (&_port_callback_mutex, 0);
68
69         _pcmio = new PortAudioIO ();
70 }
71
72 PortAudioBackend::~PortAudioBackend ()
73 {
74         delete _pcmio; _pcmio = 0;
75         pthread_mutex_destroy (&_port_callback_mutex);
76 }
77
78 /* AUDIOBACKEND API */
79
80 std::string
81 PortAudioBackend::name () const
82 {
83         return X_("PortAudio");
84 }
85
86 bool
87 PortAudioBackend::is_realtime () const
88 {
89         return true;
90 }
91
92 std::vector<AudioBackend::DeviceStatus>
93 PortAudioBackend::enumerate_devices () const
94 {
95         _pcmio->discover();
96         _audio_device_status.clear();
97         std::map<int, std::string> devices;
98         _pcmio->device_list(devices);
99
100         for (std::map<int, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
101                 if (_audio_device == "") _audio_device = i->second;
102                 _audio_device_status.push_back (DeviceStatus (i->second, true));
103         }
104         return _audio_device_status;
105 }
106
107 std::vector<float>
108 PortAudioBackend::available_sample_rates (const std::string&) const
109 {
110         std::vector<float> sr;
111         _pcmio->available_sample_rates(name_to_id(_audio_device), sr);
112         return sr;
113 }
114
115 std::vector<uint32_t>
116 PortAudioBackend::available_buffer_sizes (const std::string&) const
117 {
118         std::vector<uint32_t> bs;
119         _pcmio->available_buffer_sizes(name_to_id(_audio_device), bs);
120         return bs;
121 }
122
123 uint32_t
124 PortAudioBackend::available_input_channel_count (const std::string&) const
125 {
126         return 128; // TODO query current device
127 }
128
129 uint32_t
130 PortAudioBackend::available_output_channel_count (const std::string&) const
131 {
132         return 128; // TODO query current device
133 }
134
135 bool
136 PortAudioBackend::can_change_sample_rate_when_running () const
137 {
138         return false;
139 }
140
141 bool
142 PortAudioBackend::can_change_buffer_size_when_running () const
143 {
144         return false; // TODO
145 }
146
147 int
148 PortAudioBackend::set_device_name (const std::string& d)
149 {
150         _audio_device = d;
151         return 0;
152 }
153
154 int
155 PortAudioBackend::set_sample_rate (float sr)
156 {
157         if (sr <= 0) { return -1; }
158         // TODO check if it's in the list of valid SR
159         _samplerate = sr;
160         engine.sample_rate_change (sr);
161         return 0;
162 }
163
164 int
165 PortAudioBackend::set_buffer_size (uint32_t bs)
166 {
167         if (bs <= 0 || bs >= _max_buffer_size) {
168                 return -1;
169         }
170         _samples_per_period = bs;
171         engine.buffer_size_change (bs);
172         return 0;
173 }
174
175 int
176 PortAudioBackend::set_interleaved (bool yn)
177 {
178         if (!yn) { return 0; }
179         return -1;
180 }
181
182 int
183 PortAudioBackend::set_input_channels (uint32_t cc)
184 {
185         _n_inputs = cc;
186         return 0;
187 }
188
189 int
190 PortAudioBackend::set_output_channels (uint32_t cc)
191 {
192         _n_outputs = cc;
193         return 0;
194 }
195
196 int
197 PortAudioBackend::set_systemic_input_latency (uint32_t sl)
198 {
199         _systemic_audio_input_latency = sl;
200         return 0;
201 }
202
203 int
204 PortAudioBackend::set_systemic_output_latency (uint32_t sl)
205 {
206         _systemic_audio_output_latency = sl;
207         return 0;
208 }
209
210 /* Retrieving parameters */
211 std::string
212 PortAudioBackend::device_name () const
213 {
214         return _audio_device;
215 }
216
217 float
218 PortAudioBackend::sample_rate () const
219 {
220         return _samplerate;
221 }
222
223 uint32_t
224 PortAudioBackend::buffer_size () const
225 {
226         return _samples_per_period;
227 }
228
229 bool
230 PortAudioBackend::interleaved () const
231 {
232         return false;
233 }
234
235 uint32_t
236 PortAudioBackend::input_channels () const
237 {
238         return _n_inputs;
239 }
240
241 uint32_t
242 PortAudioBackend::output_channels () const
243 {
244         return _n_outputs;
245 }
246
247 uint32_t
248 PortAudioBackend::systemic_input_latency () const
249 {
250         return _systemic_audio_input_latency;
251 }
252
253 uint32_t
254 PortAudioBackend::systemic_output_latency () const
255 {
256         return _systemic_audio_output_latency;
257 }
258
259 /* MIDI */
260
261 std::vector<std::string>
262 PortAudioBackend::enumerate_midi_options () const
263 {
264         if (_midi_options.empty()) {
265                 //_midi_options.push_back (_("PortMidi"));
266                 _midi_options.push_back (_("None"));
267         }
268         return _midi_options;
269 }
270
271 int
272 PortAudioBackend::set_midi_option (const std::string& opt)
273 {
274         if (opt != _("None") /* && opt != _("PortMidi")*/) {
275                 return -1;
276         }
277         _midi_driver_option = opt;
278         return 0;
279 }
280
281 std::string
282 PortAudioBackend::midi_option () const
283 {
284         return _midi_driver_option;
285 }
286
287 /* State Control */
288
289 static void * pthread_process (void *arg)
290 {
291         PortAudioBackend *d = static_cast<PortAudioBackend *>(arg);
292         d->main_process_thread ();
293         pthread_exit (0);
294         return 0;
295 }
296
297 int
298 PortAudioBackend::_start (bool for_latency_measurement)
299 {
300         if (!_active && _run) {
301                 // recover from 'halted', reap threads
302                 stop();
303         }
304
305         if (_active || _run) {
306                 PBD::error << _("PortAudioBackend: already active.") << endmsg;
307                 return -1;
308         }
309
310         if (_ports.size()) {
311                 PBD::warning << _("PortAudioBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
312                 _system_inputs.clear();
313                 _system_outputs.clear();
314                 _system_midi_in.clear();
315                 _system_midi_out.clear();
316                 _ports.clear();
317         }
318
319         /* reset internal state */
320         _dsp_load = 0;
321         _freewheeling = false;
322         _freewheel = false;
323         _last_process_start = 0;
324
325         _pcmio->pcm_setup (name_to_id(_audio_device), name_to_id(_audio_device), _samplerate, _samples_per_period);
326
327         switch (_pcmio->state ()) {
328                 case 0: /* OK */ break;
329                 case -1: PBD::error << _("PortAudioBackend: failed to open device.") << endmsg; break;
330                 default: PBD::error << _("PortAudioBackend: initialization failed.") << endmsg; break;
331         }
332         if (_pcmio->state ()) {
333                 return -1;
334         }
335
336         if (_n_outputs != _pcmio->n_playback_channels ()) {
337                 _n_outputs = _pcmio->n_playback_channels ();
338                 PBD::info << _("PortAudioBackend: adjusted output channel count to match device.") << endmsg;
339         }
340
341         if (_n_inputs != _pcmio->n_capture_channels ()) {
342                 _n_inputs = _pcmio->n_capture_channels ();
343                 PBD::info << _("PortAudioBackend: adjusted input channel count to match device.") << endmsg;
344         }
345 #if 0
346         if (_pcmio->samples_per_period() != _samples_per_period) {
347                 _samples_per_period = _pcmio->samples_per_period();
348                 PBD::warning << _("PortAudioBackend: samples per period does not match.") << endmsg;
349         }
350 #endif
351
352         if (_pcmio->sample_rate() != _samplerate) {
353                 _samplerate = _pcmio->sample_rate();
354                 engine.sample_rate_change (_samplerate);
355                 PBD::warning << _("PortAudioBackend: sample rate does not match.") << endmsg;
356         }
357
358         _measure_latency = for_latency_measurement;
359
360         _run = true;
361         _port_change_flag = false;
362
363         // TODO MIDI
364
365         if (register_system_audio_ports()) {
366                 PBD::error << _("PortAudioBackend: failed to register system ports.") << endmsg;
367                 _run = false;
368                 return -1;
369         }
370
371         engine.sample_rate_change (_samplerate);
372         engine.buffer_size_change (_samples_per_period);
373
374         if (engine.reestablish_ports ()) {
375                 PBD::error << _("PortAudioBackend: Could not re-establish ports.") << endmsg;
376                 _run = false;
377                 return -1;
378         }
379
380         engine.reconnect_ports ();
381         _run = true;
382         _port_change_flag = false;
383
384         if (_realtime_pthread_create (SCHED_FIFO, -20, 100000,
385                                 &_main_thread, pthread_process, this))
386         {
387                 if (pthread_create (&_main_thread, NULL, pthread_process, this))
388                 {
389                         PBD::error << _("PortAudioBackend: failed to create process thread.") << endmsg;
390                         _run = false;
391                         return -1;
392                 } else {
393                         PBD::warning << _("PortAudioBackend: cannot acquire realtime permissions.") << endmsg;
394                 }
395         }
396
397         int timeout = 5000;
398         while (!_active && --timeout > 0) { Glib::usleep (1000); }
399
400         if (timeout == 0 || !_active) {
401                 PBD::error << _("PortAudioBackend: failed to start.") << endmsg;
402                 _pcmio->pcm_stop();
403                 _run = false;
404                 unregister_ports();
405                 _active = false;
406                 return -1;
407         }
408
409         return 0;
410 }
411
412 int
413 PortAudioBackend::stop ()
414 {
415         void *status;
416         if (!_run) {
417                 return 0;
418         }
419
420         _run = false;
421         if (pthread_join (_main_thread, &status)) {
422                 PBD::error << _("PortAudioBackend: failed to terminate.") << endmsg;
423                 return -1;
424         }
425
426
427         unregister_ports();
428
429         return (_active == false) ? 0 : -1;
430 }
431
432 int
433 PortAudioBackend::freewheel (bool onoff)
434 {
435         if (onoff == _freewheeling) {
436                 return 0;
437         }
438         _freewheeling = onoff;
439         return 0;
440 }
441
442 float
443 PortAudioBackend::dsp_load () const
444 {
445         return 100.f * _dsp_load;
446 }
447
448 size_t
449 PortAudioBackend::raw_buffer_size (DataType t)
450 {
451         switch (t) {
452                 case DataType::AUDIO:
453                         return _samples_per_period * sizeof(Sample);
454                 case DataType::MIDI:
455                         return _max_buffer_size; // XXX not really limited
456         }
457         return 0;
458 }
459
460 /* Process time */
461 framepos_t
462 PortAudioBackend::sample_time ()
463 {
464         return _processed_samples;
465 }
466
467 framepos_t
468 PortAudioBackend::sample_time_at_cycle_start ()
469 {
470         return _processed_samples;
471 }
472
473 pframes_t
474 PortAudioBackend::samples_since_cycle_start ()
475 {
476         if (!_active || !_run || _freewheeling || _freewheel) {
477                 return 0;
478         }
479         if (_last_process_start == 0) {
480                 return 0;
481         }
482
483         const int64_t elapsed_time_us = g_get_monotonic_time() - _last_process_start;
484         return std::max((pframes_t)0, (pframes_t)rint(1e-6 * elapsed_time_us * _samplerate));
485 }
486
487 int
488 PortAudioBackend::name_to_id(std::string device_name) const {
489         uint32_t device_id = UINT32_MAX;
490         std::map<int, std::string> devices;
491         _pcmio->device_list(devices);
492
493         for (std::map<int, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
494                 if (i->second == device_name) {
495                         device_id = i->first;
496                         break;
497                 }
498         }
499         return device_id;
500 }
501
502 void *
503 PortAudioBackend::portaudio_process_thread (void *arg)
504 {
505         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
506         boost::function<void ()> f = td->f;
507         delete td;
508         f ();
509         return 0;
510 }
511
512 int
513 PortAudioBackend::create_process_thread (boost::function<void()> func)
514 {
515         pthread_t thread_id;
516         pthread_attr_t attr;
517         size_t stacksize = 100000;
518
519         ThreadData* td = new ThreadData (this, func, stacksize);
520
521         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
522                                 &thread_id, portaudio_process_thread, td)) {
523                 pthread_attr_init (&attr);
524                 pthread_attr_setstacksize (&attr, stacksize);
525                 if (pthread_create (&thread_id, &attr, portaudio_process_thread, td)) {
526                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
527                         pthread_attr_destroy (&attr);
528                         return -1;
529                 }
530                 pthread_attr_destroy (&attr);
531         }
532
533         _threads.push_back (thread_id);
534         return 0;
535 }
536
537 int
538 PortAudioBackend::join_process_threads ()
539 {
540         int rv = 0;
541
542         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
543         {
544                 void *status;
545                 if (pthread_join (*i, &status)) {
546                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
547                         rv -= 1;
548                 }
549         }
550         _threads.clear ();
551         return rv;
552 }
553
554 bool
555 PortAudioBackend::in_process_thread ()
556 {
557         if (pthread_equal (_main_thread, pthread_self()) != 0) {
558                 return true;
559         }
560
561         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
562         {
563                 if (pthread_equal (*i, pthread_self ()) != 0) {
564                         return true;
565                 }
566         }
567         return false;
568 }
569
570 uint32_t
571 PortAudioBackend::process_thread_count ()
572 {
573         return _threads.size ();
574 }
575
576 void
577 PortAudioBackend::update_latencies ()
578 {
579         // trigger latency callback in RT thread (locked graph)
580         port_connect_add_remove_callback();
581 }
582
583 /* PORTENGINE API */
584
585 void*
586 PortAudioBackend::private_handle () const
587 {
588         return NULL;
589 }
590
591 const std::string&
592 PortAudioBackend::my_name () const
593 {
594         return _instance_name;
595 }
596
597 bool
598 PortAudioBackend::available () const
599 {
600         return _run && _active;
601 }
602
603 uint32_t
604 PortAudioBackend::port_name_size () const
605 {
606         return 256;
607 }
608
609 int
610 PortAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
611 {
612         if (!valid_port (port)) {
613                 PBD::error << _("PortAudioBackend::set_port_name: Invalid Port(s)") << endmsg;
614                 return -1;
615         }
616         return static_cast<PamPort*>(port)->set_name (_instance_name + ":" + name);
617 }
618
619 std::string
620 PortAudioBackend::get_port_name (PortEngine::PortHandle port) const
621 {
622         if (!valid_port (port)) {
623                 PBD::error << _("PortAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
624                 return std::string ();
625         }
626         return static_cast<PamPort*>(port)->name ();
627 }
628
629 PortEngine::PortHandle
630 PortAudioBackend::get_port_by_name (const std::string& name) const
631 {
632         PortHandle port = (PortHandle) find_port (name);
633         return port;
634 }
635
636 int
637 PortAudioBackend::get_ports (
638                 const std::string& port_name_pattern,
639                 DataType type, PortFlags flags,
640                 std::vector<std::string>& port_names) const
641 {
642         int rv = 0;
643         regex_t port_regex;
644         bool use_regexp = false;
645         if (port_name_pattern.size () > 0) {
646                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
647                         use_regexp = true;
648                 }
649         }
650         for (size_t i = 0; i < _ports.size (); ++i) {
651                 PamPort* port = _ports[i];
652                 if ((port->type () == type) && flags == (port->flags () & flags)) {
653                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
654                                 port_names.push_back (port->name ());
655                                 ++rv;
656                         }
657                 }
658         }
659         if (use_regexp) {
660                 regfree (&port_regex);
661         }
662         return rv;
663 }
664
665 DataType
666 PortAudioBackend::port_data_type (PortEngine::PortHandle port) const
667 {
668         if (!valid_port (port)) {
669                 return DataType::NIL;
670         }
671         return static_cast<PamPort*>(port)->type ();
672 }
673
674 PortEngine::PortHandle
675 PortAudioBackend::register_port (
676                 const std::string& name,
677                 ARDOUR::DataType type,
678                 ARDOUR::PortFlags flags)
679 {
680         if (name.size () == 0) { return 0; }
681         if (flags & IsPhysical) { return 0; }
682         return add_port (_instance_name + ":" + name, type, flags);
683 }
684
685 PortEngine::PortHandle
686 PortAudioBackend::add_port (
687                 const std::string& name,
688                 ARDOUR::DataType type,
689                 ARDOUR::PortFlags flags)
690 {
691         assert(name.size ());
692         if (find_port (name)) {
693                 PBD::error << _("PortAudioBackend::register_port: Port already exists:")
694                                 << " (" << name << ")" << endmsg;
695                 return 0;
696         }
697         PamPort* port = NULL;
698         switch (type) {
699                 case DataType::AUDIO:
700                         port = new PortAudioPort (*this, name, flags);
701                         break;
702                 case DataType::MIDI:
703                         port = new PortMidiPort (*this, name, flags);
704                         break;
705                 default:
706                         PBD::error << _("PortAudioBackend::register_port: Invalid Data Type.") << endmsg;
707                         return 0;
708         }
709
710         _ports.push_back (port);
711
712         return port;
713 }
714
715 void
716 PortAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
717 {
718         if (!_run) {
719                 return;
720         }
721         PamPort* port = static_cast<PamPort*>(port_handle);
722         std::vector<PamPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<PamPort*>(port_handle));
723         if (i == _ports.end ()) {
724                 PBD::error << _("PortAudioBackend::unregister_port: Failed to find port") << endmsg;
725                 return;
726         }
727         disconnect_all(port_handle);
728         _ports.erase (i);
729         delete port;
730 }
731
732 int
733 PortAudioBackend::register_system_audio_ports()
734 {
735         LatencyRange lr;
736
737         const uint32_t a_ins = _n_inputs;
738         const uint32_t a_out = _n_outputs;
739
740         // XXX PA reported stream latencies don't match measurements
741         const uint32_t portaudio_reported_input_latency =  _samples_per_period ; //  _pcmio->capture_latency();
742         const uint32_t portaudio_reported_output_latency = /* _samples_per_period + */ _pcmio->playback_latency();
743
744         /* audio ports */
745         lr.min = lr.max = portaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
746         for (uint32_t i = 0; i < a_ins; ++i) {
747                 char tmp[64];
748                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
749                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
750                 if (!p) return -1;
751                 set_latency_range (p, false, lr);
752                 _system_inputs.push_back(static_cast<PortAudioPort*>(p));
753         }
754
755         lr.min = lr.max = portaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
756         for (uint32_t i = 0; i < a_out; ++i) {
757                 char tmp[64];
758                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
759                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
760                 if (!p) return -1;
761                 set_latency_range (p, true, lr);
762                 _system_outputs.push_back(static_cast<PamPort*>(p));
763         }
764         return 0;
765 }
766
767 void
768 PortAudioBackend::unregister_ports (bool system_only)
769 {
770         size_t i = 0;
771         _system_inputs.clear();
772         _system_outputs.clear();
773         _system_midi_in.clear();
774         _system_midi_out.clear();
775         while (i <  _ports.size ()) {
776                 PamPort* port = _ports[i];
777                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
778                         port->disconnect_all ();
779                         delete port;
780                         _ports.erase (_ports.begin() + i);
781                 } else {
782                         ++i;
783                 }
784         }
785 }
786
787 int
788 PortAudioBackend::connect (const std::string& src, const std::string& dst)
789 {
790         PamPort* src_port = find_port (src);
791         PamPort* dst_port = find_port (dst);
792
793         if (!src_port) {
794                 PBD::error << _("PortAudioBackend::connect: Invalid Source port:")
795                                 << " (" << src <<")" << endmsg;
796                 return -1;
797         }
798         if (!dst_port) {
799                 PBD::error << _("PortAudioBackend::connect: Invalid Destination port:")
800                         << " (" << dst <<")" << endmsg;
801                 return -1;
802         }
803         return src_port->connect (dst_port);
804 }
805
806 int
807 PortAudioBackend::disconnect (const std::string& src, const std::string& dst)
808 {
809         PamPort* src_port = find_port (src);
810         PamPort* dst_port = find_port (dst);
811
812         if (!src_port || !dst_port) {
813                 PBD::error << _("PortAudioBackend::disconnect: Invalid Port(s)") << endmsg;
814                 return -1;
815         }
816         return src_port->disconnect (dst_port);
817 }
818
819 int
820 PortAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
821 {
822         PamPort* dst_port = find_port (dst);
823         if (!valid_port (src)) {
824                 PBD::error << _("PortAudioBackend::connect: Invalid Source Port Handle") << endmsg;
825                 return -1;
826         }
827         if (!dst_port) {
828                 PBD::error << _("PortAudioBackend::connect: Invalid Destination Port")
829                         << " (" << dst << ")" << endmsg;
830                 return -1;
831         }
832         return static_cast<PamPort*>(src)->connect (dst_port);
833 }
834
835 int
836 PortAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
837 {
838         PamPort* dst_port = find_port (dst);
839         if (!valid_port (src) || !dst_port) {
840                 PBD::error << _("PortAudioBackend::disconnect: Invalid Port(s)") << endmsg;
841                 return -1;
842         }
843         return static_cast<PamPort*>(src)->disconnect (dst_port);
844 }
845
846 int
847 PortAudioBackend::disconnect_all (PortEngine::PortHandle port)
848 {
849         if (!valid_port (port)) {
850                 PBD::error << _("PortAudioBackend::disconnect_all: Invalid Port") << endmsg;
851                 return -1;
852         }
853         static_cast<PamPort*>(port)->disconnect_all ();
854         return 0;
855 }
856
857 bool
858 PortAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
859 {
860         if (!valid_port (port)) {
861                 PBD::error << _("PortAudioBackend::disconnect_all: Invalid Port") << endmsg;
862                 return false;
863         }
864         return static_cast<PamPort*>(port)->is_connected ();
865 }
866
867 bool
868 PortAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
869 {
870         PamPort* dst_port = find_port (dst);
871         if (!valid_port (src) || !dst_port) {
872                 PBD::error << _("PortAudioBackend::connected_to: Invalid Port") << endmsg;
873                 return false;
874         }
875         return static_cast<PamPort*>(src)->is_connected (dst_port);
876 }
877
878 bool
879 PortAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
880 {
881         if (!valid_port (port)) {
882                 PBD::error << _("PortAudioBackend::physically_connected: Invalid Port") << endmsg;
883                 return false;
884         }
885         return static_cast<PamPort*>(port)->is_physically_connected ();
886 }
887
888 int
889 PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
890 {
891         if (!valid_port (port)) {
892                 PBD::error << _("PortAudioBackend::get_connections: Invalid Port") << endmsg;
893                 return -1;
894         }
895
896         assert (0 == names.size ());
897
898         const std::vector<PamPort*>& connected_ports = static_cast<PamPort*>(port)->get_connections ();
899
900         for (std::vector<PamPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
901                 names.push_back ((*i)->name ());
902         }
903
904         return (int)names.size ();
905 }
906
907 /* MIDI */
908 int
909 PortAudioBackend::midi_event_get (
910                 pframes_t& timestamp,
911                 size_t& size, uint8_t** buf, void* port_buffer,
912                 uint32_t event_index)
913 {
914         if (!buf || !port_buffer) return -1;
915         PortMidiBuffer& source = * static_cast<PortMidiBuffer*>(port_buffer);
916         if (event_index >= source.size ()) {
917                 return -1;
918         }
919         PortMidiEvent * const event = source[event_index].get ();
920
921         timestamp = event->timestamp ();
922         size = event->size ();
923         *buf = event->data ();
924         return 0;
925 }
926
927 int
928 PortAudioBackend::midi_event_put (
929                 void* port_buffer,
930                 pframes_t timestamp,
931                 const uint8_t* buffer, size_t size)
932 {
933         if (!buffer || !port_buffer) return -1;
934         PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
935         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
936 #ifndef NDEBUG
937                 // nevermind, ::get_buffer() sorts events
938                 fprintf (stderr, "PortMidiBuffer: unordered event: %d > %d\n",
939                                 (pframes_t)dst.back ()->timestamp (), timestamp);
940 #endif
941         }
942         dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
943         return 0;
944 }
945
946 uint32_t
947 PortAudioBackend::get_midi_event_count (void* port_buffer)
948 {
949         if (!port_buffer) return 0;
950         return static_cast<PortMidiBuffer*>(port_buffer)->size ();
951 }
952
953 void
954 PortAudioBackend::midi_clear (void* port_buffer)
955 {
956         if (!port_buffer) return;
957         PortMidiBuffer * buf = static_cast<PortMidiBuffer*>(port_buffer);
958         assert (buf);
959         buf->clear ();
960 }
961
962 /* Monitoring */
963
964 bool
965 PortAudioBackend::can_monitor_input () const
966 {
967         return false;
968 }
969
970 int
971 PortAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
972 {
973         return -1;
974 }
975
976 int
977 PortAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
978 {
979         return -1;
980 }
981
982 bool
983 PortAudioBackend::monitoring_input (PortEngine::PortHandle)
984 {
985         return false;
986 }
987
988 /* Latency management */
989
990 void
991 PortAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
992 {
993         if (!valid_port (port)) {
994                 PBD::error << _("PamPort::set_latency_range (): invalid port.") << endmsg;
995         }
996         static_cast<PamPort*>(port)->set_latency_range (latency_range, for_playback);
997 }
998
999 LatencyRange
1000 PortAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1001 {
1002         LatencyRange r;
1003         if (!valid_port (port)) {
1004                 PBD::error << _("PamPort::get_latency_range (): invalid port.") << endmsg;
1005                 r.min = 0;
1006                 r.max = 0;
1007                 return r;
1008         }
1009         PamPort* p = static_cast<PamPort*>(port);
1010         assert(p);
1011
1012         r = p->latency_range (for_playback);
1013         // TODO MIDI
1014         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1015                 if (p->is_input() && for_playback) {
1016                         r.min += _samples_per_period;
1017                         r.max += _samples_per_period;
1018                 }
1019                 if (p->is_output() && !for_playback) {
1020                         r.min += _samples_per_period;
1021                         r.max += _samples_per_period;
1022                 }
1023         }
1024         return r;
1025 }
1026
1027 /* Discovering physical ports */
1028
1029 bool
1030 PortAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1031 {
1032         if (!valid_port (port)) {
1033                 PBD::error << _("PamPort::port_is_physical (): invalid port.") << endmsg;
1034                 return false;
1035         }
1036         return static_cast<PamPort*>(port)->is_physical ();
1037 }
1038
1039 void
1040 PortAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1041 {
1042         for (size_t i = 0; i < _ports.size (); ++i) {
1043                 PamPort* port = _ports[i];
1044                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1045                         port_names.push_back (port->name ());
1046                 }
1047         }
1048 }
1049
1050 void
1051 PortAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1052 {
1053         for (size_t i = 0; i < _ports.size (); ++i) {
1054                 PamPort* port = _ports[i];
1055                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1056                         port_names.push_back (port->name ());
1057                 }
1058         }
1059 }
1060
1061 ChanCount
1062 PortAudioBackend::n_physical_outputs () const
1063 {
1064         int n_midi = 0;
1065         int n_audio = 0;
1066         for (size_t i = 0; i < _ports.size (); ++i) {
1067                 PamPort* port = _ports[i];
1068                 if (port->is_output () && port->is_physical ()) {
1069                         switch (port->type ()) {
1070                                 case DataType::AUDIO: ++n_audio; break;
1071                                 case DataType::MIDI: ++n_midi; break;
1072                                 default: break;
1073                         }
1074                 }
1075         }
1076         ChanCount cc;
1077         cc.set (DataType::AUDIO, n_audio);
1078         cc.set (DataType::MIDI, n_midi);
1079         return cc;
1080 }
1081
1082 ChanCount
1083 PortAudioBackend::n_physical_inputs () const
1084 {
1085         int n_midi = 0;
1086         int n_audio = 0;
1087         for (size_t i = 0; i < _ports.size (); ++i) {
1088                 PamPort* port = _ports[i];
1089                 if (port->is_input () && port->is_physical ()) {
1090                         switch (port->type ()) {
1091                                 case DataType::AUDIO: ++n_audio; break;
1092                                 case DataType::MIDI: ++n_midi; break;
1093                                 default: break;
1094                         }
1095                 }
1096         }
1097         ChanCount cc;
1098         cc.set (DataType::AUDIO, n_audio);
1099         cc.set (DataType::MIDI, n_midi);
1100         return cc;
1101 }
1102
1103 /* Getting access to the data buffer for a port */
1104
1105 void*
1106 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1107 {
1108         if (!port || !valid_port (port)) return NULL;
1109         return static_cast<PamPort*>(port)->get_buffer (nframes);
1110 }
1111
1112
1113 void *
1114 PortAudioBackend::main_process_thread ()
1115 {
1116         AudioEngine::thread_init_callback (this);
1117         _active = true;
1118         _processed_samples = 0;
1119
1120         uint64_t clock1, clock2;
1121         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1122
1123         manager.registration_callback();
1124         manager.graph_order_callback();
1125
1126         if (_pcmio->pcm_start()) {
1127                 _pcmio->pcm_stop ();
1128                 _active = false;
1129                 engine.halted_callback("PortAudio I/O error.");
1130         }
1131
1132         while (_run) {
1133
1134                 if (_freewheeling != _freewheel) {
1135                         _freewheel = _freewheeling;
1136                         engine.freewheel_callback (_freewheel);
1137                 }
1138
1139                 if (!_freewheel) {
1140
1141                         switch (_pcmio->next_cycle (_samples_per_period)) {
1142                                 case 0: // OK
1143                                         break;
1144                                 case 1:
1145 #ifndef NDEBUG
1146                                         printf("PortAudio: Xrun\n");
1147 #endif
1148                                         engine.Xrun ();
1149                                         break;
1150                                 default:
1151                                         PBD::error << _("PortAudioBackend: I/O error. Audio Process Terminated.") << endmsg;
1152                                         break;
1153                         }
1154
1155                         uint32_t i = 0;
1156                         clock1 = g_get_monotonic_time();
1157
1158                         /* get audio */
1159                         i = 0;
1160                         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1161                                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1162                         }
1163
1164                         /* de-queue incoming midi*/
1165                         i=0;
1166                         for (std::vector<PamPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1167                                 PortMidiBuffer* mbuf = static_cast<PortMidiBuffer*>((*it)->get_buffer(0));
1168                                 mbuf->clear();
1169                         }
1170
1171                         /* clear output buffers */
1172                         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1173                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1174                         }
1175
1176                         /* call engine process callback */
1177                         _last_process_start = g_get_monotonic_time();
1178                         if (engine.process_callback (_samples_per_period)) {
1179                                 _pcmio->pcm_stop ();
1180                                 _active = false;
1181                                 return 0;
1182                         }
1183 #if 0
1184                         /* mixdown midi */
1185                         for (std::vector<PamPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1186                                 static_cast<PortBackendMidiPort*>(*it)->next_period();
1187                         }
1188
1189                         /* queue outgoing midi */
1190                         i = 0;
1191                         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1192                                 // TODO
1193                         }
1194 #endif
1195
1196                         /* write back audio */
1197                         i = 0;
1198                         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1199                                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1200                         }
1201
1202                         _processed_samples += _samples_per_period;
1203
1204                         /* calculate DSP load */
1205                         clock2 = g_get_monotonic_time();
1206                         const int64_t elapsed_time = clock2 - clock1;
1207                         _dsp_load = elapsed_time / (float) nomial_time;
1208
1209                 } else {
1210                         // Freewheelin'
1211
1212                         // zero audio input buffers
1213                         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1214                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1215                         }
1216
1217                         clock1 = g_get_monotonic_time();
1218
1219                         // TODO clear midi or stop midi recv when entering fwheelin'
1220
1221                         _last_process_start = 0;
1222                         if (engine.process_callback (_samples_per_period)) {
1223                                 _pcmio->pcm_stop ();
1224                                 _active = false;
1225                                 return 0;
1226                         }
1227
1228                         // drop all outgoing MIDI messages
1229                         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1230                                         void *bptr = (*it)->get_buffer(0);
1231                                         midi_clear(bptr);
1232                         }
1233
1234                         _dsp_load = 1.0;
1235                         Glib::usleep (100); // don't hog cpu
1236                 }
1237
1238                 bool connections_changed = false;
1239                 bool ports_changed = false;
1240                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1241                         if (_port_change_flag) {
1242                                 ports_changed = true;
1243                                 _port_change_flag = false;
1244                         }
1245                         if (!_port_connection_queue.empty ()) {
1246                                 connections_changed = true;
1247                         }
1248                         while (!_port_connection_queue.empty ()) {
1249                                 PortConnectData *c = _port_connection_queue.back ();
1250                                 manager.connect_callback (c->a, c->b, c->c);
1251                                 _port_connection_queue.pop_back ();
1252                                 delete c;
1253                         }
1254                         pthread_mutex_unlock (&_port_callback_mutex);
1255                 }
1256                 if (ports_changed) {
1257                         manager.registration_callback();
1258                 }
1259                 if (connections_changed) {
1260                         manager.graph_order_callback();
1261                 }
1262                 if (connections_changed || ports_changed) {
1263                         engine.latency_callback(false);
1264                         engine.latency_callback(true);
1265                 }
1266
1267         }
1268         _pcmio->pcm_stop ();
1269         _active = false;
1270         if (_run) {
1271                 engine.halted_callback("PortAudio I/O error.");
1272         }
1273         return 0;
1274 }
1275
1276
1277 /******************************************************************************/
1278
1279 static boost::shared_ptr<PortAudioBackend> _instance;
1280
1281 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1282 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1283 static int deinstantiate ();
1284 static bool already_configured ();
1285 static bool available ();
1286
1287 static ARDOUR::AudioBackendInfo _descriptor = {
1288         "PortAudio",
1289         instantiate,
1290         deinstantiate,
1291         backend_factory,
1292         already_configured,
1293         available
1294 };
1295
1296 static boost::shared_ptr<AudioBackend>
1297 backend_factory (AudioEngine& e)
1298 {
1299         if (!_instance) {
1300                 _instance.reset (new PortAudioBackend (e, _descriptor));
1301         }
1302         return _instance;
1303 }
1304
1305 static int
1306 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1307 {
1308         s_instance_name = arg1;
1309         return 0;
1310 }
1311
1312 static int
1313 deinstantiate ()
1314 {
1315         _instance.reset ();
1316         return 0;
1317 }
1318
1319 static bool
1320 already_configured ()
1321 {
1322         return false;
1323 }
1324
1325 static bool
1326 available ()
1327 {
1328         return true;
1329 }
1330
1331 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1332 {
1333         return &_descriptor;
1334 }
1335
1336
1337 /******************************************************************************/
1338 PamPort::PamPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1339         : _osx_backend (b)
1340         , _name  (name)
1341         , _flags (flags)
1342 {
1343         _capture_latency_range.min = 0;
1344         _capture_latency_range.max = 0;
1345         _playback_latency_range.min = 0;
1346         _playback_latency_range.max = 0;
1347 }
1348
1349 PamPort::~PamPort () {
1350         disconnect_all ();
1351 }
1352
1353
1354 int PamPort::connect (PamPort *port)
1355 {
1356         if (!port) {
1357                 PBD::error << _("PamPort::connect (): invalid (null) port") << endmsg;
1358                 return -1;
1359         }
1360
1361         if (type () != port->type ()) {
1362                 PBD::error << _("PamPort::connect (): wrong port-type") << endmsg;
1363                 return -1;
1364         }
1365
1366         if (is_output () && port->is_output ()) {
1367                 PBD::error << _("PamPort::connect (): cannot inter-connect output ports.") << endmsg;
1368                 return -1;
1369         }
1370
1371         if (is_input () && port->is_input ()) {
1372                 PBD::error << _("PamPort::connect (): cannot inter-connect input ports.") << endmsg;
1373                 return -1;
1374         }
1375
1376         if (this == port) {
1377                 PBD::error << _("PamPort::connect (): cannot self-connect ports.") << endmsg;
1378                 return -1;
1379         }
1380
1381         if (is_connected (port)) {
1382 #if 0 // don't bother to warn about this for now. just ignore it
1383                 PBD::error << _("PamPort::connect (): ports are already connected:")
1384                         << " (" << name () << ") -> (" << port->name () << ")"
1385                         << endmsg;
1386 #endif
1387                 return -1;
1388         }
1389
1390         _connect (port, true);
1391         return 0;
1392 }
1393
1394
1395 void PamPort::_connect (PamPort *port, bool callback)
1396 {
1397         _connections.push_back (port);
1398         if (callback) {
1399                 port->_connect (this, false);
1400                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1401         }
1402 }
1403
1404 int PamPort::disconnect (PamPort *port)
1405 {
1406         if (!port) {
1407                 PBD::error << _("PamPort::disconnect (): invalid (null) port") << endmsg;
1408                 return -1;
1409         }
1410
1411         if (!is_connected (port)) {
1412                 PBD::error << _("PamPort::disconnect (): ports are not connected:")
1413                         << " (" << name () << ") -> (" << port->name () << ")"
1414                         << endmsg;
1415                 return -1;
1416         }
1417         _disconnect (port, true);
1418         return 0;
1419 }
1420
1421 void PamPort::_disconnect (PamPort *port, bool callback)
1422 {
1423         std::vector<PamPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1424
1425         assert (it != _connections.end ());
1426
1427         _connections.erase (it);
1428
1429         if (callback) {
1430                 port->_disconnect (this, false);
1431                 _osx_backend.port_connect_callback (name(),  port->name(), false);
1432         }
1433 }
1434
1435
1436 void PamPort::disconnect_all ()
1437 {
1438         while (!_connections.empty ()) {
1439                 _connections.back ()->_disconnect (this, false);
1440                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1441                 _connections.pop_back ();
1442         }
1443 }
1444
1445 bool
1446 PamPort::is_connected (const PamPort *port) const
1447 {
1448         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1449 }
1450
1451 bool PamPort::is_physically_connected () const
1452 {
1453         for (std::vector<PamPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1454                 if ((*it)->is_physical ()) {
1455                         return true;
1456                 }
1457         }
1458         return false;
1459 }
1460
1461 /******************************************************************************/
1462
1463 PortAudioPort::PortAudioPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1464         : PamPort (b, name, flags)
1465 {
1466         memset (_buffer, 0, sizeof (_buffer));
1467 #ifndef PLATFORM_WINDOWS
1468         mlock(_buffer, sizeof (_buffer));
1469 #endif
1470 }
1471
1472 PortAudioPort::~PortAudioPort () { }
1473
1474 void* PortAudioPort::get_buffer (pframes_t n_samples)
1475 {
1476         if (is_input ()) {
1477                 std::vector<PamPort*>::const_iterator it = get_connections ().begin ();
1478                 if (it == get_connections ().end ()) {
1479                         memset (_buffer, 0, n_samples * sizeof (Sample));
1480                 } else {
1481                         PortAudioPort const * source = static_cast<const PortAudioPort*>(*it);
1482                         assert (source && source->is_output ());
1483                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1484                         while (++it != get_connections ().end ()) {
1485                                 source = static_cast<const PortAudioPort*>(*it);
1486                                 assert (source && source->is_output ());
1487                                 Sample* dst = buffer ();
1488                                 const Sample* src = source->const_buffer ();
1489                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1490                                         *dst += *src;
1491                                 }
1492                         }
1493                 }
1494         }
1495         return _buffer;
1496 }
1497
1498
1499 PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1500         : PamPort (b, name, flags)
1501         , _n_periods (1)
1502         , _bufperiod (0)
1503 {
1504         _buffer[0].clear ();
1505         _buffer[1].clear ();
1506 }
1507
1508 PortMidiPort::~PortMidiPort () { }
1509
1510 struct MidiEventSorter {
1511         bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
1512                 return *a < *b;
1513         }
1514 };
1515
1516 void* PortMidiPort::get_buffer (pframes_t /* nframes */)
1517 {
1518         if (is_input ()) {
1519                 (_buffer[_bufperiod]).clear ();
1520                 for (std::vector<PamPort*>::const_iterator i = get_connections ().begin ();
1521                                 i != get_connections ().end ();
1522                                 ++i) {
1523                         const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
1524                         for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1525                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
1526                         }
1527                 }
1528                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1529         }
1530         return &(_buffer[_bufperiod]);
1531 }
1532
1533 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1534         : _size (size)
1535         , _timestamp (timestamp)
1536         , _data (0)
1537 {
1538         if (size > 0) {
1539                 _data = (uint8_t*) malloc (size);
1540                 memcpy (_data, data, size);
1541         }
1542 }
1543
1544 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
1545         : _size (other.size ())
1546         , _timestamp (other.timestamp ())
1547         , _data (0)
1548 {
1549         if (other.size () && other.const_data ()) {
1550                 _data = (uint8_t*) malloc (other.size ());
1551                 memcpy (_data, other.const_data (), other.size ());
1552         }
1553 };
1554
1555 PortMidiEvent::~PortMidiEvent () {
1556         free (_data);
1557 };