keep portmap & portindex in sync when renaming ports
[ardour.git] / libs / backends / dummy / dummy_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_dummy_audiobackend_h__
21 #define __libbackend_dummy_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 "ardour/types.h"
34 #include "ardour/audio_backend.h"
35 #include "ardour/dsp_load_calculator.h"
36
37 namespace ARDOUR {
38
39 class DummyAudioBackend;
40
41 namespace DummyMidiData {
42         typedef struct _MIDISequence {
43                 float   beat_time;
44                 uint8_t size;
45                 uint8_t event[3];
46         } MIDISequence;
47 };
48
49
50 class DummyMidiEvent {
51         public:
52                 DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size);
53                 DummyMidiEvent (const DummyMidiEvent& other);
54                 ~DummyMidiEvent ();
55                 size_t size () const { return _size; };
56                 pframes_t timestamp () const { return _timestamp; };
57                 const unsigned char* const_data () const { return _data; };
58                 unsigned char* data () { return _data; };
59                 bool operator< (const DummyMidiEvent &other) const { return timestamp () < other.timestamp (); };
60         private:
61                 size_t _size;
62                 pframes_t _timestamp;
63                 uint8_t *_data;
64 };
65
66 typedef std::vector<boost::shared_ptr<DummyMidiEvent> > DummyMidiBuffer;
67
68 class DummyPort {
69         protected:
70                 DummyPort (DummyAudioBackend &b, const std::string&, PortFlags);
71         public:
72                 virtual ~DummyPort ();
73
74                 const std::string& name () const { return _name; }
75                 const std::string& pretty_name () const { return _pretty_name; }
76                 PortFlags flags () const { return _flags; }
77
78                 int set_name (const std::string &name) { _name = name; return 0; }
79                 int set_pretty_name (const std::string &name) { _pretty_name = name; return 0; }
80
81                 virtual DataType type () const = 0;
82
83                 bool is_input ()     const { return flags () & IsInput; }
84                 bool is_output ()    const { return flags () & IsOutput; }
85                 bool is_physical ()  const { return flags () & IsPhysical; }
86                 bool is_terminal ()  const { return flags () & IsTerminal; }
87                 bool is_connected () const { return _connections.size () != 0; }
88                 bool is_connected (const DummyPort *port) const;
89                 bool is_physically_connected () const;
90
91                 const std::set<DummyPort *>& get_connections () const { return _connections; }
92
93                 int connect (DummyPort *port);
94                 int disconnect (DummyPort *port);
95                 void disconnect_all ();
96
97                 virtual void* get_buffer (pframes_t nframes) = 0;
98                 void next_period () { _gen_cycle = false; }
99
100                 const LatencyRange latency_range (bool for_playback) const
101                 {
102                         return for_playback ? _playback_latency_range : _capture_latency_range;
103                 }
104
105                 void set_latency_range (const LatencyRange &latency_range, bool for_playback)
106                 {
107                         if (for_playback)
108                         {
109                                 _playback_latency_range = latency_range;
110                         }
111                         else
112                         {
113                                 _capture_latency_range = latency_range;
114                         }
115                 }
116
117         private:
118                 DummyAudioBackend &_dummy_backend;
119                 std::string _name;
120                 std::string _pretty_name;
121                 const PortFlags _flags;
122                 LatencyRange _capture_latency_range;
123                 LatencyRange _playback_latency_range;
124                 std::set<DummyPort*> _connections;
125
126                 void _connect (DummyPort* , bool);
127                 void _disconnect (DummyPort* , bool);
128
129         protected:
130                 // random number generator
131                 void setup_random_number_generator ();
132                 inline float    randf ();
133                 inline uint32_t randi ();
134                 uint32_t _rseed;
135
136                 // signal generator
137                 volatile bool _gen_cycle;
138                 Glib::Threads::Mutex generator_lock;
139
140 }; // class DummyPort
141
142 class DummyAudioPort : public DummyPort {
143         public:
144                 DummyAudioPort (DummyAudioBackend &b, const std::string&, PortFlags);
145                 ~DummyAudioPort ();
146
147                 DataType type () const { return DataType::AUDIO; };
148
149                 Sample* buffer () { return _buffer; }
150                 const Sample* const_buffer () const { return _buffer; }
151                 void* get_buffer (pframes_t nframes);
152
153                 enum GeneratorType {
154                         Silence,
155                         UniformWhiteNoise,
156                         GaussianWhiteNoise,
157                         PinkNoise,
158                         PonyNoise,
159                         SineWave,
160                         SquareWave,
161                         KronekerDelta,
162                         SineSweep,
163                         SineSweepSwell,
164                         SquareSweep,
165                         SquareSweepSwell,
166                         Loopback,
167                 };
168                 void setup_generator (GeneratorType const, float const);
169                 void fill_wavetable (const float* d, size_t n_samples) { assert(_wavetable != 0);  memcpy(_wavetable, d, n_samples * sizeof(float)); }
170                 void midi_to_wavetable (DummyMidiBuffer const * const src, size_t n_samples);
171
172         private:
173                 Sample _buffer[8192];
174
175                 // signal generator ('fake' physical inputs)
176                 void generate (const pframes_t n_samples);
177                 GeneratorType _gen_type;
178
179                 // generator buffers
180                 // pink-noise filters
181                 float _b0, _b1, _b2, _b3, _b4, _b5, _b6;
182                 // generated sinf() samples
183                 Sample * _wavetable;
184                 uint32_t _gen_period;
185                 uint32_t _gen_offset;
186                 uint32_t _gen_perio2;
187                 uint32_t _gen_count2;
188
189                 // gaussian noise generator
190                 float grandf ();
191                 bool _pass;
192                 float _rn1;
193
194 }; // class DummyAudioPort
195
196 class DummyMidiPort : public DummyPort {
197         public:
198                 DummyMidiPort (DummyAudioBackend &b, const std::string&, PortFlags);
199                 ~DummyMidiPort ();
200
201                 DataType type () const { return DataType::MIDI; };
202
203                 void* get_buffer (pframes_t nframes);
204                 const DummyMidiBuffer * const_buffer () const { return &_buffer; }
205
206                 void setup_generator (int, float const);
207                 void set_loopback (DummyMidiBuffer const * const src);
208
209         private:
210                 DummyMidiBuffer _buffer;
211                 DummyMidiBuffer _loopback;
212
213                 // midi event generator ('fake' physical inputs)
214                 void midi_generate (const pframes_t n_samples);
215                 float   _midi_seq_spb; // samples per beat
216                 int32_t _midi_seq_time;
217                 uint32_t _midi_seq_pos;
218                 DummyMidiData::MIDISequence const * _midi_seq_dat;
219 }; // class DummyMidiPort
220
221 class DummyAudioBackend : public AudioBackend {
222         friend class DummyPort;
223         public:
224                  DummyAudioBackend (AudioEngine& e, AudioBackendInfo& info);
225                 ~DummyAudioBackend ();
226
227                 bool is_running () const { return _running; }
228
229                 /* AUDIOBACKEND API */
230
231                 std::string name () const;
232                 bool is_realtime () const;
233
234                 bool requires_driver_selection() const { return true; }
235                 std::string driver_name () const;
236                 std::vector<std::string> enumerate_drivers () const;
237                 int set_driver (const std::string&);
238
239                 std::vector<DeviceStatus> enumerate_devices () const;
240                 std::vector<float> available_sample_rates (const std::string& device) const;
241                 std::vector<uint32_t> available_buffer_sizes (const std::string& device) const;
242                 uint32_t available_input_channel_count (const std::string& device) const;
243                 uint32_t available_output_channel_count (const std::string& device) const;
244
245                 bool can_change_sample_rate_when_running () const;
246                 bool can_change_buffer_size_when_running () const;
247
248                 int set_device_name (const std::string&);
249                 int set_sample_rate (float);
250                 int set_buffer_size (uint32_t);
251                 int set_interleaved (bool yn);
252                 int set_input_channels (uint32_t);
253                 int set_output_channels (uint32_t);
254                 int set_systemic_input_latency (uint32_t);
255                 int set_systemic_output_latency (uint32_t);
256                 int set_systemic_midi_input_latency (std::string const, uint32_t) { return 0; }
257                 int set_systemic_midi_output_latency (std::string const, uint32_t) { return 0; }
258
259                 int reset_device () { return 0; };
260
261                 /* Retrieving parameters */
262                 std::string  device_name () const;
263                 float        sample_rate () const;
264                 uint32_t     buffer_size () const;
265                 bool         interleaved () const;
266                 uint32_t     input_channels () const;
267                 uint32_t     output_channels () const;
268                 uint32_t     systemic_input_latency () const;
269                 uint32_t     systemic_output_latency () const;
270                 uint32_t     systemic_midi_input_latency (std::string const) const { return 0; }
271                 uint32_t     systemic_midi_output_latency (std::string const) const { return 0; }
272
273                 /* External control app */
274                 std::string control_app_name () const { return std::string (); }
275                 void launch_control_app () {}
276
277                 /* MIDI */
278                 std::vector<std::string> enumerate_midi_options () const;
279                 int set_midi_option (const std::string&);
280                 std::string midi_option () const;
281
282                 std::vector<DeviceStatus> enumerate_midi_devices () const {
283                         return std::vector<AudioBackend::DeviceStatus> ();
284                 }
285                 int set_midi_device_enabled (std::string const, bool) {
286                         return 0;
287                 }
288                 bool midi_device_enabled (std::string const) const {
289                         return true;
290                 }
291                 bool can_set_systemic_midi_latencies () const {
292                         return false;
293                 }
294
295                 /* State Control */
296         protected:
297                 int _start (bool for_latency_measurement);
298         public:
299                 int stop ();
300                 int freewheel (bool);
301                 float dsp_load () const;
302                 size_t raw_buffer_size (DataType t);
303
304                 /* Process time */
305                 framepos_t sample_time ();
306                 framepos_t sample_time_at_cycle_start ();
307                 pframes_t samples_since_cycle_start ();
308
309                 int create_process_thread (boost::function<void()> func);
310                 int join_process_threads ();
311                 bool in_process_thread ();
312                 uint32_t process_thread_count ();
313
314                 void update_latencies ();
315
316                 /* PORTENGINE API */
317
318                 void* private_handle () const;
319                 const std::string& my_name () const;
320                 bool available () const;
321                 uint32_t port_name_size () const;
322
323                 int         set_port_name (PortHandle, const std::string&);
324                 std::string get_port_name (PortHandle) const;
325                 PortHandle  get_port_by_name (const std::string&) const;
326
327                 int get_port_property (PortHandle, const std::string& key, std::string& value, std::string& type) const;
328                 int set_port_property (PortHandle, const std::string& key, const std::string& value, const std::string& type);
329
330                 int get_ports (const std::string& port_name_pattern, DataType type, PortFlags flags, std::vector<std::string>&) const;
331
332                 DataType port_data_type (PortHandle) const;
333
334                 PortHandle register_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
335                 void unregister_port (PortHandle);
336
337                 int  connect (const std::string& src, const std::string& dst);
338                 int  disconnect (const std::string& src, const std::string& dst);
339                 int  connect (PortHandle, const std::string&);
340                 int  disconnect (PortHandle, const std::string&);
341                 int  disconnect_all (PortHandle);
342
343                 bool connected (PortHandle, bool process_callback_safe);
344                 bool connected_to (PortHandle, const std::string&, bool process_callback_safe);
345                 bool physically_connected (PortHandle, bool process_callback_safe);
346                 int  get_connections (PortHandle, std::vector<std::string>&, bool process_callback_safe);
347
348                 /* MIDI */
349                 int midi_event_get (pframes_t& timestamp, size_t& size, uint8_t** buf, void* port_buffer, uint32_t event_index);
350                 int midi_event_put (void* port_buffer, pframes_t timestamp, const uint8_t* buffer, size_t size);
351                 uint32_t get_midi_event_count (void* port_buffer);
352                 void     midi_clear (void* port_buffer);
353
354                 /* Monitoring */
355
356                 bool can_monitor_input () const;
357                 int  request_input_monitoring (PortHandle, bool);
358                 int  ensure_input_monitoring (PortHandle, bool);
359                 bool monitoring_input (PortHandle);
360
361                 /* Latency management */
362
363                 void         set_latency_range (PortHandle, bool for_playback, LatencyRange);
364                 LatencyRange get_latency_range (PortHandle, bool for_playback);
365
366                 /* Discovering physical ports */
367
368                 bool      port_is_physical (PortHandle) const;
369                 void      get_physical_outputs (DataType type, std::vector<std::string>&);
370                 void      get_physical_inputs (DataType type, std::vector<std::string>&);
371                 ChanCount n_physical_outputs () const;
372                 ChanCount n_physical_inputs () const;
373
374                 /* Getting access to the data buffer for a port */
375
376                 void* get_buffer (PortHandle, pframes_t);
377
378                 void* main_process_thread ();
379
380                 static size_t max_buffer_size() {return _max_buffer_size;}
381
382         private:
383                 enum MidiPortMode {
384                         MidiNoEvents,
385                         MidiGenerator,
386                         MidiLoopback,
387                         MidiToAudio,
388                 };
389
390                 struct DriverSpeed {
391                         std::string name;
392                         float speedup;
393                         DriverSpeed (const std::string& n, float s) : name (n), speedup (s) {}
394                 };
395
396                 std::string _instance_name;
397                 static std::vector<std::string> _midi_options;
398                 static std::vector<AudioBackend::DeviceStatus> _device_status;
399                 static std::vector<DummyAudioBackend::DriverSpeed> _driver_speed;
400
401                 bool  _running;
402                 bool  _freewheel;
403                 bool  _freewheeling;
404                 float _speedup;
405
406                 std::string _device;
407
408                 float  _samplerate;
409                 size_t _samples_per_period;
410                 float  _dsp_load;
411                 DSPLoadCalculator _dsp_load_calc;
412                 static size_t _max_buffer_size;
413
414                 uint32_t _n_inputs;
415                 uint32_t _n_outputs;
416
417                 uint32_t _n_midi_inputs;
418                 uint32_t _n_midi_outputs;
419                 MidiPortMode _midi_mode;
420
421                 uint32_t _systemic_input_latency;
422                 uint32_t _systemic_output_latency;
423
424                 framecnt_t _processed_samples;
425
426                 pthread_t _main_thread;
427
428                 /* process threads */
429                 static void* dummy_process_thread (void *);
430                 std::vector<pthread_t> _threads;
431
432                 struct ThreadData {
433                         DummyAudioBackend* engine;
434                         boost::function<void ()> f;
435                         size_t stacksize;
436
437                         ThreadData (DummyAudioBackend* e, boost::function<void ()> fp, size_t stacksz)
438                                 : engine (e) , f (fp) , stacksize (stacksz) {}
439                 };
440
441                 /* port engine */
442                 PortHandle add_port (const std::string& shortname, ARDOUR::DataType, ARDOUR::PortFlags);
443                 int register_system_ports ();
444                 void unregister_ports (bool system_only = false);
445
446                 std::vector<DummyAudioPort *> _system_inputs;
447                 std::vector<DummyAudioPort *> _system_outputs;
448                 std::vector<DummyMidiPort *> _system_midi_in;
449                 std::vector<DummyMidiPort *> _system_midi_out;
450
451                 typedef std::map<std::string, DummyPort *> PortMap; // fast lookup in _ports
452                 typedef std::set<DummyPort *> PortIndex; // fast lookup in _ports
453                 PortMap _portmap;
454                 PortIndex _ports;
455
456                 struct PortConnectData {
457                         std::string a;
458                         std::string b;
459                         bool c;
460
461                         PortConnectData (const std::string& a, const std::string& b, bool c)
462                                 : a (a) , b (b) , c (c) {}
463                 };
464
465                 std::vector<PortConnectData *> _port_connection_queue;
466                 pthread_mutex_t _port_callback_mutex;
467                 bool _port_change_flag;
468
469                 void port_connect_callback (const std::string& a, const std::string& b, bool conn) {
470                         pthread_mutex_lock (&_port_callback_mutex);
471                         _port_connection_queue.push_back(new PortConnectData(a, b, conn));
472                         pthread_mutex_unlock (&_port_callback_mutex);
473                 }
474
475                 void port_connect_add_remove_callback () {
476                         pthread_mutex_lock (&_port_callback_mutex);
477                         _port_change_flag = true;
478                         pthread_mutex_unlock (&_port_callback_mutex);
479                 }
480
481                 bool valid_port (PortHandle port) const {
482                         return _ports.find (static_cast<DummyPort*>(port)) != _ports.end ();
483                 }
484
485                 DummyPort* find_port (const std::string& port_name) const {
486                         PortMap::const_iterator it = _portmap.find (port_name);
487                         if (it == _portmap.end()) {
488                                 return NULL;
489                         }
490                         return (*it).second;
491                 }
492
493 }; // class DummyAudioBackend
494
495 } // namespace
496
497 #endif /* __libbackend_dummy_audiobackend_h__ */