601c3433cb1a24a153229bc76f2ad3c5e9e1f7cb
[ardour.git] / libs / backends / portaudio / portaudio_backend.h
1 /*
2  * Copyright (C) 2014-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 #ifndef __libbackend_portaudio_backend_h__
21 #define __libbackend_portaudio_backend_h__
22
23 #include <string>
24 #include <vector>
25 #include <set>
26
27 #include <stdint.h>
28 #include <pthread.h>
29
30 #include <boost/shared_ptr.hpp>
31
32 #include "ardour/audio_backend.h"
33 #include "ardour/dsp_load_calculator.h"
34 #include "ardour/types.h"
35
36 #include "portaudio_io.h"
37 #include "winmmemidi_io.h"
38 #include "cycle_timer.h"
39
40 namespace ARDOUR {
41
42 class PortAudioBackend;
43
44 class PortMidiEvent {
45         public:
46                 PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size);
47                 PortMidiEvent (const PortMidiEvent& other);
48                 ~PortMidiEvent ();
49                 size_t size () const { return _size; };
50                 pframes_t timestamp () const { return _timestamp; };
51                 const unsigned char* const_data () const { return _data; };
52                 unsigned char* data () { return _data; };
53                 bool operator< (const PortMidiEvent &other) const { return timestamp () < other.timestamp (); };
54         private:
55                 size_t _size;
56                 pframes_t _timestamp;
57                 uint8_t *_data;
58 };
59
60 typedef std::vector<boost::shared_ptr<PortMidiEvent> > PortMidiBuffer;
61
62 class PamPort { // PortAudio / PortMidi Backend Port
63         protected:
64                 PamPort (PortAudioBackend &b, const std::string&, PortFlags);
65         public:
66                 virtual ~PamPort ();
67
68                 const std::string& name () const { return _name; }
69                 const std::string& pretty_name () const { return _pretty_name; }
70                 PortFlags flags () const { return _flags; }
71
72                 int set_name (const std::string &name) { _name = name; return 0; }
73                 int set_pretty_name (const std::string& name) { _pretty_name = name; return 0;}
74
75                 virtual DataType type () const = 0;
76
77                 bool is_input ()     const { return flags () & IsInput; }
78                 bool is_output ()    const { return flags () & IsOutput; }
79                 bool is_physical ()  const { return flags () & IsPhysical; }
80                 bool is_terminal ()  const { return flags () & IsTerminal; }
81                 bool is_connected () const { return _connections.size () != 0; }
82                 bool is_connected (const PamPort *port) const;
83                 bool is_physically_connected () const;
84
85                 const std::vector<PamPort *>& get_connections () const { return _connections; }
86
87                 int connect (PamPort *port);
88                 int disconnect (PamPort *port);
89                 void disconnect_all ();
90
91                 virtual void* get_buffer (pframes_t nframes) = 0;
92
93                 const LatencyRange latency_range (bool for_playback) const
94                 {
95                         return for_playback ? _playback_latency_range : _capture_latency_range;
96                 }
97
98                 void set_latency_range (const LatencyRange &latency_range, bool for_playback)
99                 {
100                         if (for_playback)
101                         {
102                                 _playback_latency_range = latency_range;
103                         }
104                         else
105                         {
106                                 _capture_latency_range = latency_range;
107                         }
108                 }
109
110         private:
111                 PortAudioBackend &_osx_backend;
112                 std::string _name;
113                 std::string _pretty_name;
114                 const PortFlags _flags;
115                 LatencyRange _capture_latency_range;
116                 LatencyRange _playback_latency_range;
117                 std::vector<PamPort*> _connections;
118
119                 void _connect (PamPort* , bool);
120                 void _disconnect (PamPort* , bool);
121
122 }; // class PamPort
123
124 class PortAudioPort : public PamPort {
125         public:
126                 PortAudioPort (PortAudioBackend &b, const std::string&, PortFlags);
127                 ~PortAudioPort ();
128
129                 DataType type () const { return DataType::AUDIO; };
130
131                 Sample* buffer () { return _buffer; }
132                 const Sample* const_buffer () const { return _buffer; }
133                 void* get_buffer (pframes_t nframes);
134
135         private:
136                 Sample _buffer[8192];
137 }; // class PortAudioPort
138
139 class PortMidiPort : public PamPort {
140         public:
141                 PortMidiPort (PortAudioBackend &b, const std::string&, PortFlags);
142                 ~PortMidiPort ();
143
144                 DataType type () const { return DataType::MIDI; };
145
146                 void* get_buffer (pframes_t nframes);
147                 const PortMidiBuffer * const_buffer () const { return & _buffer[_bufperiod]; }
148
149                 void next_period() { if (_n_periods > 1) { get_buffer(0); _bufperiod = (_bufperiod + 1) % _n_periods; } }
150                 void set_n_periods(int n) { if (n > 0 && n < 3) { _n_periods = n; } }
151
152         private:
153                 PortMidiBuffer _buffer[2];
154                 int _n_periods;
155                 int _bufperiod;
156 }; // class PortMidiPort
157
158 class PortAudioBackend : public AudioBackend {
159         friend class PamPort;
160         public:
161                 PortAudioBackend (AudioEngine& e, AudioBackendInfo& info);
162                 ~PortAudioBackend ();
163
164                 /* AUDIOBACKEND API */
165
166                 std::string name () const;
167                 bool is_realtime () const;
168
169                 bool requires_driver_selection() const;
170                 std::string driver_name () const;
171                 std::vector<std::string> enumerate_drivers () const;
172                 int set_driver (const std::string&);
173
174                 bool can_request_update_devices () { return true; }
175                 bool update_devices ();
176
177                 bool can_use_buffered_io () { return true; }
178                 void set_use_buffered_io (bool);
179                 bool get_use_buffered_io () { return _use_blocking_api; }
180
181                 bool use_separate_input_and_output_devices () const;
182                 std::vector<DeviceStatus> enumerate_devices () const;
183                 std::vector<DeviceStatus> enumerate_input_devices () const;
184                 std::vector<DeviceStatus> enumerate_output_devices () const;
185
186                 std::vector<float> available_sample_rates (const std::string& device) const;
187                 std::vector<uint32_t> available_buffer_sizes (const std::string& device) const;
188                 uint32_t available_input_channel_count (const std::string& device) const;
189                 uint32_t available_output_channel_count (const std::string& device) const;
190
191                 bool can_change_sample_rate_when_running () const;
192                 bool can_change_buffer_size_when_running () const;
193
194                 int set_device_name (const std::string&);
195                 int set_input_device_name (const std::string&);
196                 int set_output_device_name (const std::string&);
197                 int set_sample_rate (float);
198                 int set_buffer_size (uint32_t);
199                 int set_interleaved (bool yn);
200                 int set_input_channels (uint32_t);
201                 int set_output_channels (uint32_t);
202                 int set_systemic_input_latency (uint32_t);
203                 int set_systemic_output_latency (uint32_t);
204                 int set_systemic_midi_input_latency (std::string const, uint32_t);
205                 int set_systemic_midi_output_latency (std::string const, uint32_t);
206
207                 int reset_device () { return 0; };
208
209                 /* Retrieving parameters */
210                 std::string  device_name () const;
211                 std::string  input_device_name () const;
212                 std::string  output_device_name () const;
213                 float        sample_rate () const;
214                 uint32_t     buffer_size () const;
215                 bool         interleaved () const;
216                 uint32_t     input_channels () const;
217                 uint32_t     output_channels () const;
218                 uint32_t     systemic_input_latency () const;
219                 uint32_t     systemic_output_latency () const;
220                 uint32_t     systemic_midi_input_latency (std::string const) const;
221                 uint32_t     systemic_midi_output_latency (std::string const) const;
222
223                 bool can_set_systemic_midi_latencies () const { return true; }
224
225                 /* External control app */
226                 std::string control_app_name () const;
227                 void launch_control_app ();
228
229                 /* MIDI */
230                 std::vector<std::string> enumerate_midi_options () const;
231                 int set_midi_option (const std::string&);
232                 std::string midi_option () const;
233
234                 std::vector<DeviceStatus> enumerate_midi_devices () const;
235                 int set_midi_device_enabled (std::string const, bool);
236                 bool midi_device_enabled (std::string const) const;
237
238         protected:
239                 /* State Control */
240                 int _start (bool for_latency_measurement);
241         public:
242                 int stop ();
243                 int freewheel (bool);
244                 float dsp_load () const;
245                 size_t raw_buffer_size (DataType t);
246
247                 /* Process time */
248                 framepos_t sample_time ();
249                 framepos_t sample_time_at_cycle_start ();
250                 pframes_t samples_since_cycle_start ();
251
252                 int create_process_thread (boost::function<void()> func);
253                 int join_process_threads ();
254                 bool in_process_thread ();
255                 uint32_t process_thread_count ();
256
257                 void update_latencies ();
258
259                 /* PORTENGINE API */
260
261                 void* private_handle () const;
262                 const std::string& my_name () const;
263                 bool available () const;
264                 uint32_t port_name_size () const;
265
266                 int         set_port_name (PortHandle, const std::string&);
267                 std::string get_port_name (PortHandle) const;
268                 PortHandle  get_port_by_name (const std::string&) const;
269                 int get_port_property (PortHandle, const std::string& key, std::string& value, std::string& type) const;
270                 int set_port_property (PortHandle, const std::string& key, const std::string& value, const std::string& type);
271
272                 int get_ports (const std::string& port_name_pattern, DataType type, PortFlags flags, std::vector<std::string>&) const;
273
274                 DataType port_data_type (PortHandle) const;
275
276                 PortHandle register_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
277                 void unregister_port (PortHandle);
278
279                 int  connect (const std::string& src, const std::string& dst);
280                 int  disconnect (const std::string& src, const std::string& dst);
281                 int  connect (PortHandle, const std::string&);
282                 int  disconnect (PortHandle, const std::string&);
283                 int  disconnect_all (PortHandle);
284
285                 bool connected (PortHandle, bool process_callback_safe);
286                 bool connected_to (PortHandle, const std::string&, bool process_callback_safe);
287                 bool physically_connected (PortHandle, bool process_callback_safe);
288                 int  get_connections (PortHandle, std::vector<std::string>&, bool process_callback_safe);
289
290                 /* MIDI */
291                 int midi_event_get (pframes_t& timestamp, size_t& size, uint8_t** buf, void* port_buffer, uint32_t event_index);
292                 int midi_event_put (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size);
293                 uint32_t get_midi_event_count (void* port_buffer);
294                 void     midi_clear (void* port_buffer);
295
296                 /* Monitoring */
297
298                 bool can_monitor_input () const;
299                 int  request_input_monitoring (PortHandle, bool);
300                 int  ensure_input_monitoring (PortHandle, bool);
301                 bool monitoring_input (PortHandle);
302
303                 /* Latency management */
304
305                 void         set_latency_range (PortHandle, bool for_playback, LatencyRange);
306                 LatencyRange get_latency_range (PortHandle, bool for_playback);
307
308                 /* Discovering physical ports */
309
310                 bool      port_is_physical (PortHandle) const;
311                 void      get_physical_outputs (DataType type, std::vector<std::string>&);
312                 void      get_physical_inputs (DataType type, std::vector<std::string>&);
313                 ChanCount n_physical_outputs () const;
314                 ChanCount n_physical_inputs () const;
315
316                 /* Getting access to the data buffer for a port */
317
318                 void* get_buffer (PortHandle, pframes_t);
319
320                 void* blocking_process_thread ();
321
322                 void* freewheel_process_thread ();
323
324         private: // Methods
325                 bool start_blocking_process_thread ();
326                 bool stop_blocking_process_thread ();
327                 bool blocking_process_freewheel ();
328                 bool blocking_process_main (const float* interleaved_input_data,
329                                             float* interleaved_output_data);
330
331                 void process_port_connection_changes ();
332                 void process_incoming_midi ();
333                 void process_outgoing_midi ();
334
335                 bool engine_halted ();
336                 bool running ();
337
338                 static int portaudio_callback(const void* input,
339                                           void* output,
340                                           unsigned long frameCount,
341                                           const PaStreamCallbackTimeInfo* timeInfo,
342                                           PaStreamCallbackFlags statusFlags,
343                                           void* userData);
344
345                 bool process_callback(const float* input,
346                                   float* output,
347                                   uint32_t frame_count,
348                                   const PaStreamCallbackTimeInfo* timeInfo,
349                                   PaStreamCallbackFlags statusFlags);
350
351                 bool start_freewheel_process_thread ();
352                 bool stop_freewheel_process_thread ();
353
354                 static bool set_mmcss_pro_audio (HANDLE* task_handle);
355                 static bool reset_mmcss (HANDLE task_handle);
356
357         private:
358                 std::string _instance_name;
359                 PortAudioIO *_pcmio;
360                 WinMMEMidiIO *_midiio;
361
362                 bool  _run; /* keep going or stop, ardour thread */
363                 bool  _active; /* is running, process thread */
364                 bool  _use_blocking_api;
365                 bool  _freewheel;
366                 bool  _freewheeling;
367                 bool  _freewheel_ack;
368                 bool  _reinit_thread_callback;
369                 bool  _measure_latency;
370
371                 ARDOUR::DSPLoadCalculator _dsp_calc;
372
373                 bool _freewheel_thread_active;
374
375                 pthread_mutex_t _freewheel_mutex;
376                 pthread_cond_t _freewheel_signal;
377
378                 uint64_t _cycle_count;
379                 uint64_t _total_deviation_us;
380                 uint64_t _max_deviation_us;
381
382                 CycleTimer _cycle_timer;
383                 uint64_t _last_cycle_start;
384
385                 static std::vector<std::string> _midi_options;
386                 static std::vector<AudioBackend::DeviceStatus> _input_audio_device_status;
387                 static std::vector<AudioBackend::DeviceStatus> _output_audio_device_status;
388                 static std::vector<AudioBackend::DeviceStatus> _midi_device_status;
389
390                 mutable std::string _input_audio_device;
391                 mutable std::string _output_audio_device;
392                 std::string _midi_driver_option;
393
394                 /* audio settings */
395                 float  _samplerate;
396                 size_t _samples_per_period;
397                 static size_t _max_buffer_size;
398
399                 uint32_t _n_inputs;
400                 uint32_t _n_outputs;
401
402                 uint32_t _systemic_audio_input_latency;
403                 uint32_t _systemic_audio_output_latency;
404
405                 MidiDeviceInfo* midi_device_info(const std::string&) const;
406
407                 /* portaudio specific  */
408                 int name_to_id(std::string) const;
409
410                 /* processing */
411                 float  _dsp_load;
412                 framecnt_t _processed_samples;
413
414                 /* blocking thread */
415                 pthread_t _main_blocking_thread;
416
417                 /* main thread in callback mode(or fw thread when running) */
418                 pthread_t _main_thread;
419
420                 /* freewheel thread in callback mode */
421                 pthread_t _pthread_freewheel;
422
423                 /* process threads */
424                 static void* portaudio_process_thread (void *);
425                 std::vector<pthread_t> _threads;
426
427                 struct ThreadData {
428                         PortAudioBackend* engine;
429                         boost::function<void ()> f;
430                         size_t stacksize;
431
432                         ThreadData (PortAudioBackend* e, boost::function<void ()> fp, size_t stacksz)
433                                 : engine (e) , f (fp) , stacksize (stacksz) {}
434                 };
435
436                 /* port engine */
437                 PortHandle add_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
438                 int register_system_audio_ports ();
439                 int register_system_midi_ports ();
440                 void unregister_ports (bool system_only = false);
441
442                 std::vector<PamPort *> _ports;
443                 std::vector<PamPort *> _system_inputs;
444                 std::vector<PamPort *> _system_outputs;
445                 std::vector<PamPort *> _system_midi_in;
446                 std::vector<PamPort *> _system_midi_out;
447
448                 struct PortConnectData {
449                         std::string a;
450                         std::string b;
451                         bool c;
452
453                         PortConnectData (const std::string& a, const std::string& b, bool c)
454                                 : a (a) , b (b) , c (c) {}
455                 };
456
457                 std::vector<PortConnectData *> _port_connection_queue;
458                 pthread_mutex_t _port_callback_mutex;
459                 bool _port_change_flag;
460
461                 void port_connect_callback (const std::string& a, const std::string& b, bool conn) {
462                         pthread_mutex_lock (&_port_callback_mutex);
463                         _port_connection_queue.push_back(new PortConnectData(a, b, conn));
464                         pthread_mutex_unlock (&_port_callback_mutex);
465                 }
466
467                 void port_connect_add_remove_callback () {
468                         pthread_mutex_lock (&_port_callback_mutex);
469                         _port_change_flag = true;
470                         pthread_mutex_unlock (&_port_callback_mutex);
471                 }
472
473                 bool valid_port (PortHandle port) const {
474                         return std::find (_ports.begin (), _ports.end (), (PamPort*)port) != _ports.end ();
475                 }
476
477                 PamPort * find_port (const std::string& port_name) const {
478                         for (std::vector<PamPort*>::const_iterator it = _ports.begin (); it != _ports.end (); ++it) {
479                                 if ((*it)->name () == port_name) {
480                                         return *it;
481                                 }
482                         }
483                         return NULL;
484                 }
485
486                 PamPort * find_port_in (std::vector<PamPort *> plist, const std::string& port_name) const {
487                         for (std::vector<PamPort*>::const_iterator it = plist.begin (); it != plist.end (); ++it) {
488                                 if ((*it)->name () == port_name) {
489                                         return *it;
490                                 }
491                         }
492                         return NULL;
493                 }
494
495 }; // class PortAudioBackend
496
497 } // namespace
498
499 #endif /* __libbackend_portaudio_backend_h__ */