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