Only show user-presets in favorite sidebar
[ardour.git] / libs / backends / alsa / alsa_audiobackend.h
1 /*
2  * Copyright (C) 2014 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_alsa_audiobackend_h__
21 #define __libbackend_alsa_audiobackend_h__
22
23 #include <string>
24 #include <vector>
25 #include <map>
26 #include <set>
27
28 #include <stdint.h>
29 #include <pthread.h>
30
31 #include <boost/shared_ptr.hpp>
32
33 #include "pbd/natsort.h"
34 #include "ardour/audio_backend.h"
35 #include "ardour/dsp_load_calculator.h"
36 #include "ardour/system_exec.h"
37 #include "ardour/types.h"
38
39 #include "ardouralsautil/deviceinfo.h"
40
41 #include "zita-alsa-pcmi.h"
42 #include "alsa_rawmidi.h"
43 #include "alsa_sequencer.h"
44 #include "alsa_slave.h"
45
46 namespace ARDOUR {
47
48 class AlsaAudioBackend;
49
50 class AlsaMidiEvent {
51         public:
52                 AlsaMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size);
53                 AlsaMidiEvent (const AlsaMidiEvent& other);
54                 size_t size () const { return _size; };
55                 pframes_t timestamp () const { return _timestamp; };
56                 const uint8_t* data () const { return _data; };
57                 bool operator< (const AlsaMidiEvent &other) const { return timestamp () < other.timestamp (); };
58         private:
59                 size_t _size;
60                 pframes_t _timestamp;
61                 uint8_t _data[MaxAlsaMidiEventSize];
62 };
63
64 typedef std::vector<AlsaMidiEvent> AlsaMidiBuffer;
65
66 class AlsaPort {
67         protected:
68                 AlsaPort (AlsaAudioBackend &b, const std::string&, PortFlags);
69         public:
70                 virtual ~AlsaPort ();
71
72                 const std::string& name () const { return _name; }
73                 const std::string& pretty_name () const { return _pretty_name; }
74                 PortFlags flags () const { return _flags; }
75
76                 int set_name (const std::string &name) { _name = name; return 0; }
77                 int set_pretty_name (const std::string &name) { _pretty_name = name; return 0; }
78
79                 virtual DataType type () const = 0;
80
81                 bool is_input ()     const { return flags () & IsInput; }
82                 bool is_output ()    const { return flags () & IsOutput; }
83                 bool is_physical ()  const { return flags () & IsPhysical; }
84                 bool is_terminal ()  const { return flags () & IsTerminal; }
85                 bool is_connected () const { return _connections.size () != 0; }
86                 bool is_connected (const AlsaPort *port) const;
87                 bool is_physically_connected () const;
88
89                 const std::set<AlsaPort *>& get_connections () const { return _connections; }
90
91                 int connect (AlsaPort *port);
92                 int disconnect (AlsaPort *port);
93                 void disconnect_all ();
94
95                 virtual void* get_buffer (pframes_t nframes) = 0;
96
97                 const LatencyRange latency_range (bool for_playback) const
98                 {
99                         return for_playback ? _playback_latency_range : _capture_latency_range;
100                 }
101
102                 void set_latency_range (const LatencyRange &latency_range, bool for_playback);
103
104                 void update_connected_latency (bool for_playback);
105
106         private:
107                 AlsaAudioBackend &_alsa_backend;
108                 std::string _name;
109                 std::string _pretty_name;
110                 const PortFlags _flags;
111                 LatencyRange _capture_latency_range;
112                 LatencyRange _playback_latency_range;
113                 std::set<AlsaPort*> _connections;
114
115                 void _connect (AlsaPort* , bool);
116                 void _disconnect (AlsaPort* , bool);
117
118 }; // class AlsaPort
119
120 class AlsaAudioPort : public AlsaPort {
121         public:
122                 AlsaAudioPort (AlsaAudioBackend &b, const std::string&, PortFlags);
123                 ~AlsaAudioPort ();
124
125                 DataType type () const { return DataType::AUDIO; };
126
127                 Sample* buffer () { return _buffer; }
128                 const Sample* const_buffer () const { return _buffer; }
129                 void* get_buffer (pframes_t nframes);
130
131         private:
132                 Sample _buffer[8192];
133 }; // class AlsaAudioPort
134
135 class AlsaMidiPort : public AlsaPort {
136         public:
137                 AlsaMidiPort (AlsaAudioBackend &b, const std::string&, PortFlags);
138                 ~AlsaMidiPort ();
139
140                 DataType type () const { return DataType::MIDI; };
141
142                 void* get_buffer (pframes_t nframes);
143                 const AlsaMidiBuffer * const_buffer () const { return & _buffer[_bufperiod]; }
144
145                 void next_period() { if (_n_periods > 1) { get_buffer(0); _bufperiod = (_bufperiod + 1) % _n_periods; } }
146                 void set_n_periods(int n) { if (n > 0 && n < 4) { _n_periods = n; } }
147
148         private:
149                 AlsaMidiBuffer _buffer[3];
150                 int _n_periods;
151                 int _bufperiod;
152 }; // class AlsaMidiPort
153
154 class AlsaDeviceReservation
155 {
156         public:
157                 AlsaDeviceReservation ();
158                 AlsaDeviceReservation (const char* device_name);
159                 ~AlsaDeviceReservation ();
160
161                 bool acquire_device (const char* device_name);
162                 void release_device ();
163
164         private:
165                 ARDOUR::SystemExec* _device_reservation;
166                 PBD::ScopedConnectionList _reservation_connection;
167                 void reservation_stdout (std::string, size_t);
168                 bool _reservation_succeeded;
169 };
170
171 class AlsaAudioBackend : public AudioBackend {
172         friend class AlsaPort;
173         public:
174                 AlsaAudioBackend (AudioEngine& e, AudioBackendInfo& info);
175                 ~AlsaAudioBackend ();
176
177                 /* AUDIOBACKEND API */
178
179                 std::string name () const;
180                 bool is_realtime () const;
181
182                 bool use_separate_input_and_output_devices () const { return true; }
183                 bool match_input_output_devices_or_none () const { return true; }
184                 bool can_set_period_size () const { return true; }
185
186                 std::vector<DeviceStatus> enumerate_devices () const;
187                 std::vector<DeviceStatus> enumerate_input_devices () const;
188                 std::vector<DeviceStatus> enumerate_output_devices () const;
189                 std::vector<float> available_sample_rates (const std::string& device) const;
190                 std::vector<float> available_sample_rates2 (const std::string&, const std::string&) const;
191                 std::vector<uint32_t> available_buffer_sizes (const std::string& device) const;
192                 std::vector<uint32_t> available_buffer_sizes2 (const std::string&, const std::string&) const;
193                 std::vector<uint32_t> available_period_sizes (const std::string& driver) const;
194                 uint32_t available_input_channel_count (const std::string& device) const;
195                 uint32_t available_output_channel_count (const std::string& device) const;
196
197                 bool can_change_sample_rate_when_running () const;
198                 bool can_change_buffer_size_when_running () const;
199
200                 bool can_change_systemic_latency_when_running () const { return true; }
201
202                 int set_device_name (const std::string&);
203                 int set_input_device_name (const std::string&);
204                 int set_output_device_name (const std::string&);
205                 int set_sample_rate (float);
206                 int set_buffer_size (uint32_t);
207                 int set_peridod_size (uint32_t);
208                 int set_interleaved (bool yn);
209                 int set_input_channels (uint32_t);
210                 int set_output_channels (uint32_t);
211                 int set_systemic_input_latency (uint32_t);
212                 int set_systemic_output_latency (uint32_t);
213                 int set_systemic_midi_input_latency (std::string const, uint32_t);
214                 int set_systemic_midi_output_latency (std::string const, uint32_t);
215
216                 int reset_device () { return 0; };
217
218                 /* Retrieving parameters */
219                 std::string  device_name () const;
220                 std::string  input_device_name () const;
221                 std::string  output_device_name () const;
222                 float        sample_rate () const;
223                 uint32_t     buffer_size () const;
224                 uint32_t     period_size () const;
225                 bool         interleaved () const;
226                 uint32_t     input_channels () const;
227                 uint32_t     output_channels () const;
228                 uint32_t     systemic_input_latency () const;
229                 uint32_t     systemic_output_latency () const;
230                 uint32_t     systemic_midi_input_latency (std::string const) const;
231                 uint32_t     systemic_midi_output_latency (std::string const) const;
232
233                 bool can_set_systemic_midi_latencies () const { return true; }
234
235                 /* External control app */
236                 std::string control_app_name () const { return std::string (); }
237                 void launch_control_app () {}
238
239                 /* MIDI */
240                 std::vector<std::string> enumerate_midi_options () const;
241                 int set_midi_option (const std::string&);
242                 std::string midi_option () const;
243
244                 std::vector<DeviceStatus> enumerate_midi_devices () const;
245                 int set_midi_device_enabled (std::string const, bool);
246                 bool midi_device_enabled (std::string const) const;
247
248                 /* State Control */
249         protected:
250                 int _start (bool for_latency_measurement);
251         public:
252                 int stop ();
253                 int freewheel (bool);
254                 float dsp_load () const;
255                 size_t raw_buffer_size (DataType t);
256
257                 /* Process time */
258                 samplepos_t sample_time ();
259                 samplepos_t sample_time_at_cycle_start ();
260                 pframes_t samples_since_cycle_start ();
261
262                 int create_process_thread (boost::function<void()> func);
263                 int join_process_threads ();
264                 bool in_process_thread ();
265                 uint32_t process_thread_count ();
266
267                 void update_latencies ();
268
269                 /* PORTENGINE API */
270
271                 void* private_handle () const;
272                 const std::string& my_name () const;
273                 uint32_t port_name_size () const;
274
275                 int         set_port_name (PortHandle, const std::string&);
276                 std::string get_port_name (PortHandle) const;
277                 PortFlags get_port_flags (PortHandle) const;
278                 PortHandle  get_port_by_name (const std::string&) const;
279
280                 int get_port_property (PortHandle, const std::string& key, std::string& value, std::string& type) const;
281                 int set_port_property (PortHandle, const std::string& key, const std::string& value, const std::string& type);
282
283                 int get_ports (const std::string& port_name_pattern, DataType type, PortFlags flags, std::vector<std::string>&) const;
284
285                 DataType port_data_type (PortHandle) const;
286
287                 PortHandle register_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
288                 void unregister_port (PortHandle);
289
290                 int  connect (const std::string& src, const std::string& dst);
291                 int  disconnect (const std::string& src, const std::string& dst);
292                 int  connect (PortHandle, const std::string&);
293                 int  disconnect (PortHandle, const std::string&);
294                 int  disconnect_all (PortHandle);
295
296                 bool connected (PortHandle, bool process_callback_safe);
297                 bool connected_to (PortHandle, const std::string&, bool process_callback_safe);
298                 bool physically_connected (PortHandle, bool process_callback_safe);
299                 int  get_connections (PortHandle, std::vector<std::string>&, bool process_callback_safe);
300
301                 /* MIDI */
302                 int midi_event_get (pframes_t& timestamp, size_t& size, uint8_t const** buf, void* port_buffer, uint32_t event_index);
303                 int midi_event_put (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size);
304                 uint32_t get_midi_event_count (void* port_buffer);
305                 void     midi_clear (void* port_buffer);
306
307                 /* Monitoring */
308
309                 bool can_monitor_input () const;
310                 int  request_input_monitoring (PortHandle, bool);
311                 int  ensure_input_monitoring (PortHandle, bool);
312                 bool monitoring_input (PortHandle);
313
314                 /* Latency management */
315
316                 void         set_latency_range (PortHandle, bool for_playback, LatencyRange);
317                 LatencyRange get_latency_range (PortHandle, bool for_playback);
318
319                 /* Discovering physical ports */
320
321                 bool      port_is_physical (PortHandle) const;
322                 void      get_physical_outputs (DataType type, std::vector<std::string>&);
323                 void      get_physical_inputs (DataType type, std::vector<std::string>&);
324                 ChanCount n_physical_outputs () const;
325                 ChanCount n_physical_inputs () const;
326
327                 /* Getting access to the data buffer for a port */
328
329                 void* get_buffer (PortHandle, pframes_t);
330
331                 void* main_process_thread ();
332
333         private:
334                 std::string _instance_name;
335                 Alsa_pcmi *_pcmi;
336
337                 bool  _run; /* keep going or stop, ardour thread */
338                 bool  _active; /* is running, process thread */
339                 bool  _freewheel;
340                 bool  _freewheeling;
341                 bool  _measure_latency;
342
343                 uint64_t _last_process_start;
344
345                 static std::vector<std::string> _midi_options;
346                 static std::vector<AudioBackend::DeviceStatus> _input_audio_device_status;
347                 static std::vector<AudioBackend::DeviceStatus> _output_audio_device_status;
348                 static std::vector<AudioBackend::DeviceStatus> _duplex_audio_device_status;
349                 static std::vector<AudioBackend::DeviceStatus> _midi_device_status;
350                 static ARDOUR::ALSADeviceInfo _input_audio_device_info;
351                 static ARDOUR::ALSADeviceInfo _output_audio_device_info;
352
353                 mutable std::string _input_audio_device;
354                 mutable std::string _output_audio_device;
355                 std::string _midi_driver_option;
356
357                 /* audio device reservation */
358                 AlsaDeviceReservation _device_reservation;
359
360                 /* audio settings */
361                 float  _samplerate;
362                 size_t _samples_per_period;
363                 size_t _periods_per_cycle;
364                 static size_t _max_buffer_size;
365
366                 uint32_t _n_inputs;
367                 uint32_t _n_outputs;
368
369                 uint32_t _systemic_audio_input_latency;
370                 uint32_t _systemic_audio_output_latency;
371
372                 /* midi settings */
373                 struct AlsaMidiDeviceInfo {
374                         bool     enabled;
375                         uint32_t systemic_input_latency;
376                         uint32_t systemic_output_latency;
377                         AlsaMidiDeviceInfo()
378                                 : enabled (true)
379                                 , systemic_input_latency (0)
380                                 , systemic_output_latency (0)
381                         {}
382                 };
383
384                 mutable std::map<std::string, struct AlsaMidiDeviceInfo *> _midi_devices;
385                 struct AlsaMidiDeviceInfo * midi_device_info(std::string const) const;
386
387                 /* processing */
388                 float  _dsp_load;
389                 ARDOUR::DSPLoadCalculator  _dsp_load_calc;
390                 samplecnt_t _processed_samples;
391                 pthread_t _main_thread;
392
393                 /* DLL, track main process callback timing */
394                 double _t0, _t1;
395
396                 /* process threads */
397                 static void* alsa_process_thread (void *);
398                 std::vector<pthread_t> _threads;
399
400                 struct ThreadData {
401                         AlsaAudioBackend* engine;
402                         boost::function<void ()> f;
403                         size_t stacksize;
404
405                         ThreadData (AlsaAudioBackend* e, boost::function<void ()> fp, size_t stacksz)
406                                 : engine (e) , f (fp) , stacksize (stacksz) {}
407                 };
408
409                 /* port engine */
410                 PortHandle add_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
411                 int register_system_audio_ports ();
412                 int register_system_midi_ports (const std::string device = "");
413                 void unregister_ports (bool system_only = false);
414                 void update_system_port_latecies ();
415
416                 std::vector<AlsaPort *> _system_inputs;
417                 std::vector<AlsaPort *> _system_outputs;
418                 std::vector<AlsaPort *> _system_midi_in;
419                 std::vector<AlsaPort *> _system_midi_out;
420
421                 struct SortByPortName
422                 {
423                         bool operator ()(const AlsaPort* lhs, const AlsaPort* rhs) const
424                         {
425                                 return PBD::naturally_less (lhs->name ().c_str (), rhs->name ().c_str ());
426                         }
427                 };
428
429                 typedef std::map<std::string, AlsaPort *> PortMap; // fast lookup in _ports
430                 typedef std::set<AlsaPort *, SortByPortName> PortIndex; // fast lookup in _ports
431                 PortMap _portmap;
432                 PortIndex _ports;
433
434                 std::vector<AlsaMidiOut *> _rmidi_out;
435                 std::vector<AlsaMidiIn  *> _rmidi_in;
436
437                 unsigned _midi_ins;
438                 unsigned _midi_outs;
439
440                 struct PortConnectData {
441                         std::string a;
442                         std::string b;
443                         bool c;
444
445                         PortConnectData (const std::string& a, const std::string& b, bool c)
446                                 : a (a) , b (b) , c (c) {}
447                 };
448
449                 std::vector<PortConnectData *> _port_connection_queue;
450                 pthread_mutex_t _port_callback_mutex;
451                 bool _port_change_flag;
452
453                 void port_connect_callback (const std::string& a, const std::string& b, bool conn) {
454                         pthread_mutex_lock (&_port_callback_mutex);
455                         _port_connection_queue.push_back(new PortConnectData(a, b, conn));
456                         pthread_mutex_unlock (&_port_callback_mutex);
457                 }
458
459                 void port_connect_add_remove_callback () {
460                         pthread_mutex_lock (&_port_callback_mutex);
461                         _port_change_flag = true;
462                         pthread_mutex_unlock (&_port_callback_mutex);
463                 }
464
465                 bool valid_port (PortHandle port) const {
466                         return std::find (_ports.begin(), _ports.end(), static_cast<AlsaPort*>(port)) != _ports.end ();
467                 }
468
469                 AlsaPort* find_port (const std::string& port_name) const {
470                         PortMap::const_iterator it = _portmap.find (port_name);
471                         if (it == _portmap.end()) {
472                                 return NULL;
473                         }
474                         return (*it).second;
475                 }
476
477                 void update_systemic_audio_latencies ();
478                 void update_systemic_midi_latencies ();
479
480                 /* additional re-sampled I/O */
481                 bool add_slave (const char*  slave_device,
482                                 unsigned int slave_rate,
483                                 unsigned int slave_spp,
484                                 unsigned int duplex = 3);
485
486                 class AudioSlave : public AlsaDeviceReservation, public AlsaAudioSlave {
487                         public:
488                                 AudioSlave (
489                                                 const char*  device,
490                                                 unsigned int duplex,
491                                                 unsigned int master_rate,
492                                                 unsigned int master_samples_per_period,
493                                                 unsigned int slave_rate,
494                                                 unsigned int slave_samples_per_period,
495                                                 unsigned int periods_per_cycle);
496
497                                 ~AudioSlave ();
498
499                                 bool active; // set in sync with process-cb
500                                 bool halt;
501                                 bool dead;
502
503                                 std::vector<AlsaPort *> inputs;
504                                 std::vector<AlsaPort *> outputs;
505
506                                 PBD::Signal0<void> UpdateLatency;
507                                 PBD::ScopedConnection latency_connection;
508
509                         protected:
510                                 void update_latencies (uint32_t, uint32_t);
511
512                         private:
513                                 PBD::ScopedConnection _halted_connection;
514                                 void halted ();
515                 };
516
517                 typedef std::vector<AudioSlave*> AudioSlaves;
518                 AudioSlaves _slaves;
519
520 }; // class AlsaAudioBackend
521
522 } // namespace
523
524 #endif /* __libbackend_alsa_audiobackend_h__ */