Add utility functions in PortaudioBackend for re/setting MMCSS thread characteristics
[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/types.h"
34
35 #include "portaudio_io.h"
36 #include "winmmemidi_io.h"
37 #include "cycle_timer.h"
38 #include "dsp_load_calculator.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 use_separate_input_and_output_devices () const;
178                 std::vector<DeviceStatus> enumerate_devices () const;
179                 std::vector<DeviceStatus> enumerate_input_devices () const;
180                 std::vector<DeviceStatus> enumerate_output_devices () const;
181
182                 std::vector<float> available_sample_rates (const std::string& device) const;
183                 std::vector<uint32_t> available_buffer_sizes (const std::string& device) const;
184                 uint32_t available_input_channel_count (const std::string& device) const;
185                 uint32_t available_output_channel_count (const std::string& device) const;
186
187                 bool can_change_sample_rate_when_running () const;
188                 bool can_change_buffer_size_when_running () const;
189
190                 int set_device_name (const std::string&);
191                 int set_input_device_name (const std::string&);
192                 int set_output_device_name (const std::string&);
193                 int set_sample_rate (float);
194                 int set_buffer_size (uint32_t);
195                 int set_interleaved (bool yn);
196                 int set_input_channels (uint32_t);
197                 int set_output_channels (uint32_t);
198                 int set_systemic_input_latency (uint32_t);
199                 int set_systemic_output_latency (uint32_t);
200                 int set_systemic_midi_input_latency (std::string const, uint32_t) { return 0; }
201                 int set_systemic_midi_output_latency (std::string const, uint32_t) { return 0; }
202
203                 int reset_device () { return 0; };
204
205                 /* Retrieving parameters */
206                 std::string  device_name () const;
207                 std::string  input_device_name () const;
208                 std::string  output_device_name () const;
209                 float        sample_rate () const;
210                 uint32_t     buffer_size () const;
211                 bool         interleaved () const;
212                 uint32_t     input_channels () const;
213                 uint32_t     output_channels () const;
214                 uint32_t     systemic_input_latency () const;
215                 uint32_t     systemic_output_latency () const;
216                 uint32_t     systemic_midi_input_latency (std::string const) const { return 0; }
217                 uint32_t     systemic_midi_output_latency (std::string const) const { return 0; }
218
219                 bool can_set_systemic_midi_latencies () const { return false; }
220
221                 /* External control app */
222                 std::string control_app_name () const;
223                 void launch_control_app ();
224
225                 /* MIDI */
226                 std::vector<std::string> enumerate_midi_options () const;
227                 int set_midi_option (const std::string&);
228                 std::string midi_option () const;
229
230                 std::vector<DeviceStatus> enumerate_midi_devices () const {
231                         return std::vector<AudioBackend::DeviceStatus> ();
232                 }
233                 int set_midi_device_enabled (std::string const, bool) {
234                         return 0;
235                 }
236                 bool midi_device_enabled (std::string const) const {
237                         return true;
238                 }
239
240         protected:
241                 /* State Control */
242                 int _start (bool for_latency_measurement);
243         public:
244                 int stop ();
245                 int freewheel (bool);
246                 float dsp_load () const;
247                 size_t raw_buffer_size (DataType t);
248
249                 /* Process time */
250                 framepos_t sample_time ();
251                 framepos_t sample_time_at_cycle_start ();
252                 pframes_t samples_since_cycle_start ();
253
254                 int create_process_thread (boost::function<void()> func);
255                 int join_process_threads ();
256                 bool in_process_thread ();
257                 uint32_t process_thread_count ();
258
259                 void update_latencies ();
260
261                 /* PORTENGINE API */
262
263                 void* private_handle () const;
264                 const std::string& my_name () const;
265                 bool available () const;
266                 uint32_t port_name_size () const;
267
268                 int         set_port_name (PortHandle, const std::string&);
269                 std::string get_port_name (PortHandle) const;
270                 PortHandle  get_port_by_name (const std::string&) const;
271                 int get_port_property (PortHandle, const std::string& key, std::string& value, std::string& type) const;
272
273                 int get_ports (const std::string& port_name_pattern, DataType type, PortFlags flags, std::vector<std::string>&) const;
274
275                 DataType port_data_type (PortHandle) const;
276
277                 PortHandle register_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
278                 void unregister_port (PortHandle);
279
280                 int  connect (const std::string& src, const std::string& dst);
281                 int  disconnect (const std::string& src, const std::string& dst);
282                 int  connect (PortHandle, const std::string&);
283                 int  disconnect (PortHandle, const std::string&);
284                 int  disconnect_all (PortHandle);
285
286                 bool connected (PortHandle, bool process_callback_safe);
287                 bool connected_to (PortHandle, const std::string&, bool process_callback_safe);
288                 bool physically_connected (PortHandle, bool process_callback_safe);
289                 int  get_connections (PortHandle, std::vector<std::string>&, bool process_callback_safe);
290
291                 /* MIDI */
292                 int midi_event_get (pframes_t& timestamp, size_t& size, uint8_t** buf, void* port_buffer, uint32_t event_index);
293                 int midi_event_put (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size);
294                 uint32_t get_midi_event_count (void* port_buffer);
295                 void     midi_clear (void* port_buffer);
296
297                 /* Monitoring */
298
299                 bool can_monitor_input () const;
300                 int  request_input_monitoring (PortHandle, bool);
301                 int  ensure_input_monitoring (PortHandle, bool);
302                 bool monitoring_input (PortHandle);
303
304                 /* Latency management */
305
306                 void         set_latency_range (PortHandle, bool for_playback, LatencyRange);
307                 LatencyRange get_latency_range (PortHandle, bool for_playback);
308
309                 /* Discovering physical ports */
310
311                 bool      port_is_physical (PortHandle) const;
312                 void      get_physical_outputs (DataType type, std::vector<std::string>&);
313                 void      get_physical_inputs (DataType type, std::vector<std::string>&);
314                 ChanCount n_physical_outputs () const;
315                 ChanCount n_physical_inputs () const;
316
317                 /* Getting access to the data buffer for a port */
318
319                 void* get_buffer (PortHandle, pframes_t);
320
321                 void* main_blocking_process_thread ();
322
323         private: // Methods
324                 bool start_blocking_process_thread ();
325                 bool stop_blocking_process_thread ();
326                 bool blocking_process_freewheel ();
327                 bool blocking_process_main (const float* interleaved_input_data,
328                                             float* interleaved_output_data);
329
330                 void process_port_connection_changes ();
331                 void process_incoming_midi ();
332                 void process_outgoing_midi ();
333
334                 bool engine_halted ();
335                 bool running ();
336
337                 static bool set_mmcss_pro_audio (HANDLE* task_handle);
338                 static bool reset_mmcss (HANDLE task_handle);
339
340         private:
341                 std::string _instance_name;
342                 PortAudioIO *_pcmio;
343                 WinMMEMidiIO *_midiio;
344
345                 bool  _run; /* keep going or stop, ardour thread */
346                 bool  _active; /* is running, process thread */
347                 bool  _freewheel;
348                 bool  _freewheeling;
349                 bool  _measure_latency;
350
351                 DSPLoadCalculator m_dsp_calc;
352
353                 uint64_t m_cycle_count;
354                 uint64_t m_total_deviation_us;
355                 uint64_t m_max_deviation_us;
356
357                 CycleTimer m_cycle_timer;
358                 uint64_t m_last_cycle_start;
359
360                 static std::vector<std::string> _midi_options;
361                 static std::vector<AudioBackend::DeviceStatus> _input_audio_device_status;
362                 static std::vector<AudioBackend::DeviceStatus> _output_audio_device_status;
363                 static std::vector<AudioBackend::DeviceStatus> _midi_device_status;
364
365                 mutable std::string _input_audio_device;
366                 mutable std::string _output_audio_device;
367                 std::string _midi_driver_option;
368
369                 /* audio settings */
370                 float  _samplerate;
371                 size_t _samples_per_period;
372                 static size_t _max_buffer_size;
373
374                 uint32_t _n_inputs;
375                 uint32_t _n_outputs;
376
377                 uint32_t _systemic_audio_input_latency;
378                 uint32_t _systemic_audio_output_latency;
379
380                 /* portaudio specific  */
381                 int name_to_id(std::string) const;
382
383                 /* processing */
384                 float  _dsp_load;
385                 framecnt_t _processed_samples;
386
387                 /* blocking thread */
388                 pthread_t _main_blocking_thread;
389
390                 /* process threads */
391                 static void* portaudio_process_thread (void *);
392                 std::vector<pthread_t> _threads;
393
394                 struct ThreadData {
395                         PortAudioBackend* engine;
396                         boost::function<void ()> f;
397                         size_t stacksize;
398
399                         ThreadData (PortAudioBackend* e, boost::function<void ()> fp, size_t stacksz)
400                                 : engine (e) , f (fp) , stacksize (stacksz) {}
401                 };
402
403                 /* port engine */
404                 PortHandle add_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
405                 int register_system_audio_ports ();
406                 int register_system_midi_ports ();
407                 void unregister_ports (bool system_only = false);
408
409                 std::vector<PamPort *> _ports;
410                 std::vector<PamPort *> _system_inputs;
411                 std::vector<PamPort *> _system_outputs;
412                 std::vector<PamPort *> _system_midi_in;
413                 std::vector<PamPort *> _system_midi_out;
414
415                 struct PortConnectData {
416                         std::string a;
417                         std::string b;
418                         bool c;
419
420                         PortConnectData (const std::string& a, const std::string& b, bool c)
421                                 : a (a) , b (b) , c (c) {}
422                 };
423
424                 std::vector<PortConnectData *> _port_connection_queue;
425                 pthread_mutex_t _port_callback_mutex;
426                 bool _port_change_flag;
427
428                 void port_connect_callback (const std::string& a, const std::string& b, bool conn) {
429                         pthread_mutex_lock (&_port_callback_mutex);
430                         _port_connection_queue.push_back(new PortConnectData(a, b, conn));
431                         pthread_mutex_unlock (&_port_callback_mutex);
432                 }
433
434                 void port_connect_add_remove_callback () {
435                         pthread_mutex_lock (&_port_callback_mutex);
436                         _port_change_flag = true;
437                         pthread_mutex_unlock (&_port_callback_mutex);
438                 }
439
440                 bool valid_port (PortHandle port) const {
441                         return std::find (_ports.begin (), _ports.end (), (PamPort*)port) != _ports.end ();
442                 }
443
444                 PamPort * find_port (const std::string& port_name) const {
445                         for (std::vector<PamPort*>::const_iterator it = _ports.begin (); it != _ports.end (); ++it) {
446                                 if ((*it)->name () == port_name) {
447                                         return *it;
448                                 }
449                         }
450                         return NULL;
451                 }
452
453                 PamPort * find_port_in (std::vector<PamPort *> plist, const std::string& port_name) const {
454                         for (std::vector<PamPort*>::const_iterator it = plist.begin (); it != plist.end (); ++it) {
455                                 if ((*it)->name () == port_name) {
456                                         return *it;
457                                 }
458                         }
459                         return NULL;
460                 }
461
462 }; // class PortAudioBackend
463
464 } // namespace
465
466 #endif /* __libbackend_portaudio_backend_h__ */