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