7e8c55f2eb8e6d3d5dd7ad216706243da55cbc62
[ardour.git] / libs / backends / coreaudio / coreaudio_backend.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_coreaudio_backend_h__
21 #define __libbackend_coreaudio_backend_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/types.h"
37
38 #include "coreaudio_pcmio.h"
39 #include "coremidi_io.h"
40
41 #define MaxCoreMidiEventSize 128 // matches CoreMidi's MIDIPacket
42
43 namespace ARDOUR {
44
45 class CoreAudioBackend;
46
47 class CoreMidiEvent {
48   public:
49         CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size);
50         CoreMidiEvent (const CoreMidiEvent& other);
51         size_t size () const { return _size; };
52         pframes_t timestamp () const { return _timestamp; };
53         const uint8_t* data () const { return _data; };
54         bool operator< (const CoreMidiEvent &other) const { return timestamp () < other.timestamp (); };
55   private:
56         size_t _size;
57         pframes_t _timestamp;
58         uint8_t _data[MaxCoreMidiEventSize];
59 };
60
61 typedef std::vector<CoreMidiEvent> CoreMidiBuffer;
62
63 class CoreBackendPort {
64   protected:
65         CoreBackendPort (CoreAudioBackend &b, const std::string&, PortFlags);
66   public:
67         virtual ~CoreBackendPort ();
68
69         const std::string& name () const { return _name; }
70         const std::string& pretty_name () const { return _pretty_name; }
71         PortFlags flags () const { return _flags; }
72
73         int set_name (const std::string &name) { _name = name; return 0; }
74         int set_pretty_name (const std::string &name) { _pretty_name = name; return 0; }
75
76         virtual DataType type () const = 0;
77
78         bool is_input ()     const { return flags () & IsInput; }
79         bool is_output ()    const { return flags () & IsOutput; }
80         bool is_physical ()  const { return flags () & IsPhysical; }
81         bool is_terminal ()  const { return flags () & IsTerminal; }
82         bool is_connected () const { return _connections.size () != 0; }
83         bool is_connected (const CoreBackendPort *port) const;
84         bool is_physically_connected () const;
85
86         const std::set<CoreBackendPort *>& get_connections () const { return _connections; }
87
88         int connect (CoreBackendPort *port);
89         int disconnect (CoreBackendPort *port);
90         void disconnect_all ();
91
92         virtual void* get_buffer (pframes_t nframes) = 0;
93
94         const LatencyRange latency_range (bool for_playback) const
95         {
96                 return for_playback ? _playback_latency_range : _capture_latency_range;
97         }
98
99         void set_latency_range (const LatencyRange &latency_range, bool for_playback);
100
101         void update_connected_latency (bool for_playback);
102
103   private:
104         CoreAudioBackend &_osx_backend;
105         std::string _name;
106         std::string _pretty_name;
107         const PortFlags _flags;
108         LatencyRange _capture_latency_range;
109         LatencyRange _playback_latency_range;
110         std::set<CoreBackendPort*> _connections;
111
112         void _connect (CoreBackendPort* , bool);
113         void _disconnect (CoreBackendPort* , bool);
114
115 }; // class CoreBackendPort
116
117 class CoreAudioPort : public CoreBackendPort {
118   public:
119         CoreAudioPort (CoreAudioBackend &b, const std::string&, PortFlags);
120         ~CoreAudioPort ();
121
122         DataType type () const { return DataType::AUDIO; };
123
124         Sample* buffer () { return _buffer; }
125         const Sample* const_buffer () const { return _buffer; }
126         void* get_buffer (pframes_t nframes);
127
128   private:
129         Sample _buffer[8192];
130 }; // class CoreAudioPort
131
132 class CoreMidiPort : public CoreBackendPort {
133   public:
134         CoreMidiPort (CoreAudioBackend &b, const std::string&, PortFlags);
135         ~CoreMidiPort ();
136
137         DataType type () const { return DataType::MIDI; };
138
139         void* get_buffer (pframes_t nframes);
140         const CoreMidiBuffer * const_buffer () const { return & _buffer[_bufperiod]; }
141
142         void next_period() { if (_n_periods > 1) { get_buffer(0); _bufperiod = (_bufperiod + 1) % _n_periods; } }
143         void set_n_periods(int n) { if (n > 0 && n < 3) { _n_periods = n; } }
144
145         void parse_events (const uint64_t time, const uint8_t *data, const size_t size);
146         void clear_events ();
147         void reset_parser ();
148
149   private:
150         CoreMidiBuffer _buffer[2];
151         int _n_periods;
152         int _bufperiod;
153
154         int queue_event (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size);
155         bool process_byte (const uint64_t, const uint8_t);
156
157         void record_byte(uint8_t byte) {
158                 if (_total_bytes < sizeof(_parser_buffer)) {
159                         _parser_buffer[_total_bytes] = byte;
160                 } else {
161                         ++_unbuffered_bytes;
162                 }
163                 ++_total_bytes;
164         }
165
166         void prepare_byte_event(const uint64_t time, const uint8_t byte) {
167                 _parser_buffer[0] = byte;
168                 _event.prepare(time, 1);
169         }
170
171         bool prepare_buffered_event(const uint64_t time) {
172                 const bool result = _unbuffered_bytes == 0;
173                 if (result) {
174                         _event.prepare(time, _total_bytes);
175                 }
176                 _total_bytes = 0;
177                 _unbuffered_bytes = 0;
178                 if (_status_byte >= 0xf0) {
179                         _expected_bytes = 0;
180                         _status_byte = 0;
181                 }
182                 return result;
183         }
184
185         struct ParserEvent {
186                 uint64_t _time;
187                 size_t _size;
188                 bool _pending;
189                 ParserEvent (const uint64_t time, const size_t size)
190                         : _time(time)
191                         , _size(size)
192                         , _pending(false) {}
193
194                 void prepare(const uint64_t time, const size_t size) {
195                         _time = time;
196                         _size = size;
197                         _pending = true;
198                 }
199         } _event;
200
201         bool    _first_time;
202         size_t  _unbuffered_bytes;
203         size_t  _total_bytes;
204         size_t  _expected_bytes;
205         uint8_t _status_byte;
206         uint8_t _parser_buffer[1024];
207
208 }; // class CoreMidiPort
209
210 class CoreAudioBackend : public AudioBackend {
211         friend class CoreBackendPort;
212   public:
213         CoreAudioBackend (AudioEngine& e, AudioBackendInfo& info);
214         ~CoreAudioBackend ();
215
216         /* AUDIOBACKEND API */
217
218         std::string name () const;
219         bool is_realtime () const;
220
221         bool use_separate_input_and_output_devices () const { return true; }
222         std::vector<DeviceStatus> enumerate_devices () const;
223         std::vector<DeviceStatus> enumerate_input_devices () const;
224         std::vector<DeviceStatus> enumerate_output_devices () const;
225
226         std::vector<float> available_sample_rates (const std::string& device) const;
227         std::vector<float> available_sample_rates2 (const std::string&, const std::string&) const;
228         std::vector<uint32_t> available_buffer_sizes (const std::string& device) const;
229         std::vector<uint32_t> available_buffer_sizes2 (const std::string&, const std::string&) const;
230         uint32_t available_input_channel_count (const std::string& device) const;
231         uint32_t available_output_channel_count (const std::string& device) const;
232
233         bool can_change_sample_rate_when_running () const;
234         bool can_change_buffer_size_when_running () const;
235
236         int set_device_name (const std::string&);
237         int set_input_device_name (const std::string&);
238         int set_output_device_name (const std::string&);
239         int set_sample_rate (float);
240         int set_buffer_size (uint32_t);
241         int set_interleaved (bool yn);
242         int set_input_channels (uint32_t);
243         int set_output_channels (uint32_t);
244         int set_systemic_input_latency (uint32_t);
245         int set_systemic_output_latency (uint32_t);
246         int set_systemic_midi_input_latency (std::string const, uint32_t) { return 0; }
247         int set_systemic_midi_output_latency (std::string const, uint32_t) { return 0; }
248
249         int reset_device () { return 0; };
250
251         /* Retrieving parameters */
252         std::string  device_name () const;
253         std::string  input_device_name () const;
254         std::string  output_device_name () const;
255         float        sample_rate () const;
256         uint32_t     buffer_size () const;
257         bool         interleaved () const;
258         uint32_t     input_channels () const;
259         uint32_t     output_channels () const;
260         uint32_t     systemic_input_latency () const;
261         uint32_t     systemic_output_latency () const;
262         uint32_t     systemic_midi_input_latency (std::string const) const { return 0; }
263         uint32_t     systemic_midi_output_latency (std::string const) const { return 0; }
264
265         bool can_set_systemic_midi_latencies () const { return false; /* XXX */}
266
267         /* External control app */
268         std::string control_app_name () const { return std::string ("Apple"); }
269         void launch_control_app ();
270
271         /* MIDI */
272         std::vector<std::string> enumerate_midi_options () const;
273         int set_midi_option (const std::string&);
274         std::string midi_option () const;
275
276         std::vector<DeviceStatus> enumerate_midi_devices () const {
277                 return std::vector<AudioBackend::DeviceStatus> ();
278         }
279         int set_midi_device_enabled (std::string const, bool) {
280                 return true;
281         }
282         bool midi_device_enabled (std::string const) const {
283                 return false;
284         }
285
286         // really private, but needing static access:
287         int process_callback(uint32_t, uint64_t);
288         void error_callback();
289         void xrun_callback();
290         void buffer_size_callback();
291         void sample_rate_callback();
292         void hw_changed_callback();
293
294   protected:
295         /* State Control */
296         int _start (bool for_latency_measurement);
297   public:
298         int stop ();
299         int freewheel (bool);
300         float dsp_load () const;
301         size_t raw_buffer_size (DataType t);
302
303         /* Process time */
304         samplepos_t sample_time ();
305         samplepos_t sample_time_at_cycle_start ();
306         pframes_t samples_since_cycle_start ();
307
308         int create_process_thread (boost::function<void()> func);
309         int join_process_threads ();
310         bool in_process_thread ();
311         uint32_t process_thread_count ();
312
313         void update_latencies ();
314
315         /* PORTENGINE API */
316
317         void* private_handle () const;
318         const std::string& my_name () const;
319         bool available () const;
320         uint32_t port_name_size () const;
321
322         int         set_port_name (PortHandle, const std::string&);
323         std::string get_port_name (PortHandle) const;
324         PortHandle  get_port_by_name (const std::string&) const;
325         int get_port_property (PortHandle, const std::string& key, std::string& value, std::string& type) const;
326         int set_port_property (PortHandle, const std::string& key, const std::string& value, const std::string& type);
327
328         int get_ports (const std::string& port_name_pattern, DataType type, PortFlags flags, std::vector<std::string>&) const;
329
330         DataType port_data_type (PortHandle) const;
331
332         PortHandle register_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
333         void unregister_port (PortHandle);
334
335         int  connect (const std::string& src, const std::string& dst);
336         int  disconnect (const std::string& src, const std::string& dst);
337         int  connect (PortHandle, const std::string&);
338         int  disconnect (PortHandle, const std::string&);
339         int  disconnect_all (PortHandle);
340
341         bool connected (PortHandle, bool process_callback_safe);
342         bool connected_to (PortHandle, const std::string&, bool process_callback_safe);
343         bool physically_connected (PortHandle, bool process_callback_safe);
344         int  get_connections (PortHandle, std::vector<std::string>&, bool process_callback_safe);
345
346         /* MIDI */
347         int midi_event_get (pframes_t& timestamp, size_t& size, uint8_t const** buf, void* port_buffer, uint32_t event_index);
348         int midi_event_put (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size) {
349                 return _midi_event_put (port_buffer, timestamp, buffer, size);
350         }
351
352         uint32_t get_midi_event_count (void* port_buffer);
353         void     midi_clear (void* port_buffer);
354
355         /* Monitoring */
356
357         bool can_monitor_input () const;
358         int  request_input_monitoring (PortHandle, bool);
359         int  ensure_input_monitoring (PortHandle, bool);
360         bool monitoring_input (PortHandle);
361
362         /* Latency management */
363
364         void         set_latency_range (PortHandle, bool for_playback, LatencyRange);
365         LatencyRange get_latency_range (PortHandle, bool for_playback);
366
367         /* Discovering physical ports */
368
369         bool      port_is_physical (PortHandle) const;
370         void      get_physical_outputs (DataType type, std::vector<std::string>&);
371         void      get_physical_inputs (DataType type, std::vector<std::string>&);
372         ChanCount n_physical_outputs () const;
373         ChanCount n_physical_inputs () const;
374
375         /* Getting access to the data buffer for a port */
376
377         void* get_buffer (PortHandle, pframes_t);
378
379         void* freewheel_thread ();
380         void pre_process ();
381         void coremidi_rediscover ();
382
383         static int _midi_event_put (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size);
384
385   private:
386         std::string _instance_name;
387         CoreAudioPCM *_pcmio;
388         CoreMidiIo *_midiio;
389
390         bool  _run; /* keep going or stop, ardour thread */
391         bool  _active_ca; /* is running, process thread */
392         bool  _active_fw; /* is running, process thread */
393         bool  _preinit;
394         bool  _freewheeling;
395         bool  _freewheel;
396         bool  _freewheel_ack;
397         bool  _reinit_thread_callback;
398         bool  _measure_latency;
399
400         uint64_t _last_process_start;
401
402         pthread_mutex_t _process_callback_mutex;
403
404         pthread_mutex_t _freewheel_mutex;
405         pthread_cond_t  _freewheel_signal;
406
407         static std::vector<std::string> _midi_options;
408         static std::vector<AudioBackend::DeviceStatus> _input_audio_device_status;
409         static std::vector<AudioBackend::DeviceStatus> _output_audio_device_status;
410         static std::vector<AudioBackend::DeviceStatus> _duplex_audio_device_status;
411         static std::vector<AudioBackend::DeviceStatus> _midi_device_status;
412
413         mutable std::string _input_audio_device;
414         mutable std::string _output_audio_device;
415         std::string _midi_driver_option;
416
417         /* audio settings */
418         float  _samplerate;
419         size_t _samples_per_period;
420         static size_t _max_buffer_size;
421
422         uint32_t _n_inputs;
423         uint32_t _n_outputs;
424
425         uint32_t _systemic_audio_input_latency;
426         uint32_t _systemic_audio_output_latency;
427
428         /* coreaudio specific  */
429         enum DeviceFilter { All, Input, Output, Duplex };
430         uint32_t name_to_id(std::string, DeviceFilter filter = All) const;
431
432         /* processing */
433         float  _dsp_load;
434         ARDOUR::DSPLoadCalculator  _dsp_load_calc;
435         uint64_t _processed_samples;
436
437         pthread_t _main_thread;
438         pthread_t _freeewheel_thread;
439
440         /* process threads */
441         static void* coreaudio_process_thread (void *);
442         bool coreaudio_set_realtime_policy (pthread_t) const;
443         std::vector<pthread_t> _threads;
444
445         struct ThreadData {
446                 CoreAudioBackend* engine;
447                 boost::function<void ()> f;
448                 size_t stacksize;
449
450                 ThreadData (CoreAudioBackend* e, boost::function<void ()> fp, size_t stacksz)
451                         : engine (e) , f (fp) , stacksize (stacksz) {}
452         };
453
454         /* port engine */
455         PortHandle add_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
456         int register_system_audio_ports ();
457         void unregister_ports (bool system_only = false);
458         void update_system_port_latecies ();
459
460         std::vector<CoreBackendPort *> _system_inputs;
461         std::vector<CoreBackendPort *> _system_outputs;
462         std::vector<CoreBackendPort *> _system_midi_in;
463         std::vector<CoreBackendPort *> _system_midi_out;
464
465         struct SortByPortName
466         {
467                 bool operator ()(const CoreBackendPort* lhs, const CoreBackendPort* rhs) const
468                 {
469                         return PBD::naturally_less (lhs->name ().c_str (), rhs->name ().c_str ());
470                 }
471         };
472
473         typedef std::map<std::string, CoreBackendPort *> PortMap; // fast lookup in _ports
474         typedef std::set<CoreBackendPort *, SortByPortName> PortIndex; // fast lookup in _ports
475         PortMap _portmap;
476         PortIndex _ports;
477
478         struct PortConnectData {
479                 std::string a;
480                 std::string b;
481                 bool c;
482
483                 PortConnectData (const std::string& a, const std::string& b, bool c)
484                         : a (a) , b (b) , c (c) {}
485         };
486
487         std::vector<PortConnectData *> _port_connection_queue;
488         pthread_mutex_t _port_callback_mutex;
489         bool _port_change_flag;
490
491         void port_connect_callback (const std::string& a, const std::string& b, bool conn) {
492                 pthread_mutex_lock (&_port_callback_mutex);
493                 _port_connection_queue.push_back(new PortConnectData(a, b, conn));
494                 pthread_mutex_unlock (&_port_callback_mutex);
495         }
496
497         void port_connect_add_remove_callback () {
498                 pthread_mutex_lock (&_port_callback_mutex);
499                 _port_change_flag = true;
500                 pthread_mutex_unlock (&_port_callback_mutex);
501         }
502
503         bool valid_port (PortHandle port) const {
504                 return std::find (_ports.begin(), _ports.end(), static_cast<CoreBackendPort*>(port)) != _ports.end ();
505         }
506
507         CoreBackendPort* find_port (const std::string& port_name) const {
508                 PortMap::const_iterator it = _portmap.find (port_name);
509                 if (it == _portmap.end()) {
510                         return NULL;
511                 }
512                 return (*it).second;
513         }
514
515         CoreBackendPort * find_port_in (std::vector<CoreBackendPort *> plist, const std::string& port_name) const {
516                 for (std::vector<CoreBackendPort*>::const_iterator it = plist.begin (); it != plist.end (); ++it) {
517                         if ((*it)->name () == port_name) {
518                                 return *it;
519                         }
520                 }
521                 return NULL;
522         }
523
524         void reset_midi_parsers ();
525
526 }; // class CoreAudioBackend
527
528 } // namespace
529
530 #endif /* __libbackend_coreaudio_backend_h__ */