Add API to query backend realtime thread priority
[ardour.git] / libs / ardour / ardour / audioengine.h
1 /*
2   Copyright (C) 2002-2004 Paul Davis
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifndef __ardour_audioengine_h__
21 #define __ardour_audioengine_h__
22
23 #ifdef WAF_BUILD
24 #include "libardour-config.h"
25 #endif
26
27 #include <iostream>
28 #include <list>
29 #include <set>
30 #include <cmath>
31 #include <exception>
32 #include <string>
33
34 #include <glibmm/threads.h>
35
36 #include "pbd/signals.h"
37 #include "pbd/stacktrace.h"
38
39 #include "ardour/ardour.h"
40 #include "ardour/data_type.h"
41 #include "ardour/session_handle.h"
42 #include "ardour/libardour_visibility.h"
43 #include "ardour/types.h"
44 #include "ardour/chan_count.h"
45 #include "ardour/port_manager.h"
46
47 class MTDM;
48
49 namespace ARDOUR {
50
51 class InternalPort;
52 class MidiPort;
53 class MIDIDM;
54 class Port;
55 class Session;
56 class ProcessThread;
57 class AudioBackend;
58 struct AudioBackendInfo;
59
60 class LIBARDOUR_API AudioEngine : public PortManager, public SessionHandlePtr
61 {
62   public:
63
64         static AudioEngine* create ();
65
66         virtual ~AudioEngine ();
67
68         int discover_backends();
69         std::vector<const AudioBackendInfo*> available_backends() const;
70         std::string current_backend_name () const;
71         boost::shared_ptr<AudioBackend> set_default_backend ();
72         boost::shared_ptr<AudioBackend> set_backend (const std::string&, const std::string& arg1, const std::string& arg2);
73         boost::shared_ptr<AudioBackend> current_backend() const { return _backend; }
74         bool setup_required () const;
75
76         ProcessThread* main_thread() const { return _main_thread; }
77
78         /* START BACKEND PROXY API
79          *
80          * See audio_backend.h for full documentation and semantics. These wrappers
81          * just forward to a backend implementation.
82          */
83
84         int            start (bool for_latency_measurement=false);
85         int            stop (bool for_latency_measurement=false);
86         int            freewheel (bool start_stop);
87         float          get_dsp_load() const ;
88         void           transport_start ();
89         void           transport_stop ();
90         TransportState transport_state ();
91         void           transport_locate (samplepos_t pos);
92         samplepos_t     transport_sample();
93         samplecnt_t     sample_rate () const;
94         pframes_t      samples_per_cycle () const;
95         int            usecs_per_cycle () const;
96         size_t         raw_buffer_size (DataType t);
97         samplepos_t     sample_time ();
98         samplepos_t     sample_time_at_cycle_start ();
99         pframes_t      samples_since_cycle_start ();
100         bool           get_sync_offset (pframes_t& offset) const;
101
102         std::string    get_last_backend_error () const { return _last_backend_error_string; }
103
104         int            create_process_thread (boost::function<void()> func);
105         int            join_process_threads ();
106         bool           in_process_thread ();
107         uint32_t       process_thread_count ();
108
109         /* internal backends
110          * -20 : main thread
111          * -21 : additional I/O threads e.g. MIDI
112          * -22 : client/process threads
113          *
114          * search for
115          * - pbd_realtime_pthread_create
116          * - pbd_set_thread_priority
117          */
118         virtual int    client_real_time_priority () { return -22; }
119
120         int            backend_reset_requested();
121         void           request_backend_reset();
122         void           request_device_list_update();
123         void           launch_device_control_app();
124
125         bool           is_realtime() const;
126         bool           connected() const;
127
128         // for the user which hold state_lock to check if reset operation is pending
129         bool           is_reset_requested() const { return g_atomic_int_get(const_cast<gint*>(&_hw_reset_request_count)); }
130
131         int set_device_name (const std::string&);
132         int set_sample_rate (float);
133         int set_buffer_size (uint32_t);
134         int set_interleaved (bool yn);
135         int set_input_channels (uint32_t);
136         int set_output_channels (uint32_t);
137         int set_systemic_input_latency (uint32_t);
138         int set_systemic_output_latency (uint32_t);
139
140         /* END BACKEND PROXY API */
141
142         bool freewheeling() const { return _freewheeling; }
143         bool running() const { return _running; }
144
145         Glib::Threads::Mutex& process_lock() { return _process_lock; }
146         Glib::Threads::RecMutex& state_lock() { return _state_lock; }
147
148         int request_buffer_size (pframes_t samples) {
149                 return set_buffer_size (samples);
150         }
151
152         samplecnt_t processed_samples() const { return _processed_samples; }
153
154         void set_session (Session *);
155         void remove_session (); // not a replacement for SessionHandle::session_going_away()
156         Session* session() const { return _session; }
157
158         void reconnect_session_routes (bool reconnect_inputs = true, bool reconnect_outputs = true);
159
160         class NoBackendAvailable : public std::exception {
161             public:
162                 virtual const char *what() const throw() { return "could not connect to engine backend"; }
163         };
164
165         void split_cycle (pframes_t offset);
166
167         int  reset_timebase ();
168
169         void update_latencies ();
170
171         /* this signal is sent for every process() cycle while freewheeling.
172            (the regular process() call to session->process() is not made)
173         */
174
175         PBD::Signal1<void, pframes_t> Freewheel;
176
177         PBD::Signal0<void> Xrun;
178
179         /** this signal is emitted if the sample rate changes */
180         PBD::Signal1<void, samplecnt_t> SampleRateChanged;
181
182         /** this signal is emitted if the buffer size changes */
183         PBD::Signal1<void, pframes_t> BufferSizeChanged;
184
185         /** this signal is emitted if the device cannot operate properly */
186         PBD::Signal0<void> DeviceError;
187
188         /* this signal is emitted if the device list changed */
189
190         PBD::Signal0<void> DeviceListChanged;
191
192         /* this signal is sent if the backend ever disconnects us */
193
194         PBD::Signal1<void,const char*> Halted;
195
196         /* these two are emitted when the engine itself is
197            started and stopped
198         */
199
200         PBD::Signal0<void> Running;
201         PBD::Signal0<void> Stopped;
202
203         /* these two are emitted when a device reset is initiated/finished
204          */
205
206         PBD::Signal0<void> DeviceResetStarted;
207         PBD::Signal0<void> DeviceResetFinished;
208
209         static AudioEngine* instance() { return _instance; }
210         static void destroy();
211         void died ();
212
213         /* The backend will cause these at the appropriate time(s)
214          */
215         int  process_callback (pframes_t nframes);
216         int  buffer_size_change (pframes_t nframes);
217         int  sample_rate_change (pframes_t nframes);
218         void freewheel_callback (bool);
219         void timebase_callback (TransportState state, pframes_t nframes, samplepos_t pos, int new_position);
220         int  sync_callback (TransportState state, samplepos_t position);
221         int  port_registration_callback ();
222         void latency_callback (bool for_playback);
223         void halted_callback (const char* reason);
224
225         /* checks if current thread is properly set up for audio processing */
226         static bool thread_initialised_for_audio_processing ();
227
228         /* sets up the process callback thread */
229         static void thread_init_callback (void *);
230
231         /* latency measurement */
232
233         MTDM* mtdm() { return _mtdm; }
234         MIDIDM* mididm() { return _mididm; }
235
236         int  prepare_for_latency_measurement ();
237         int  start_latency_detection (bool);
238         void stop_latency_detection ();
239         void set_latency_input_port (const std::string&);
240         void set_latency_output_port (const std::string&);
241         uint32_t latency_signal_delay () const { return _latency_signal_latency; }
242
243         enum LatencyMeasurement {
244                 MeasureNone,
245                 MeasureAudio,
246                 MeasureMIDI
247         };
248
249         LatencyMeasurement measuring_latency () const { return _measuring_latency; }
250
251         /* These two are used only in builds where SILENCE_AFTER_SECONDS was
252          * set. BecameSilent will be emitted when the audioengine goes silent.
253          * reset_silence_countdown() can be used to reset the silence
254          * countdown, whose duration will be reduced to half of its previous
255          * value.
256          */
257
258         PBD::Signal0<void> BecameSilent;
259         void reset_silence_countdown ();
260
261         void add_pending_port_deletion (Port*);
262
263   private:
264         AudioEngine ();
265
266         static AudioEngine*       _instance;
267
268         Glib::Threads::Mutex       _process_lock;
269         Glib::Threads::RecMutex    _state_lock;
270         Glib::Threads::Cond        session_removed;
271         bool                       session_remove_pending;
272         sampleoffset_t              session_removal_countdown;
273         gain_t                     session_removal_gain;
274         gain_t                     session_removal_gain_step;
275         bool                      _running;
276         bool                      _freewheeling;
277         /// number of samples between each check for changes in monitor input
278         samplecnt_t                 monitor_check_interval;
279         /// time of the last monitor check in samples
280         samplecnt_t                 last_monitor_check;
281         /// the number of samples processed since start() was called
282         samplecnt_t                _processed_samples;
283         Glib::Threads::Thread*     m_meter_thread;
284         ProcessThread*            _main_thread;
285         MTDM*                     _mtdm;
286         MIDIDM*                   _mididm;
287         LatencyMeasurement        _measuring_latency;
288         PortEngine::PortHandle    _latency_input_port;
289         PortEngine::PortHandle    _latency_output_port;
290         samplecnt_t                _latency_flush_samples;
291         std::string               _latency_input_name;
292         std::string               _latency_output_name;
293         samplecnt_t                _latency_signal_latency;
294         bool                      _stopped_for_latency;
295         bool                      _started_for_latency;
296         bool                      _in_destructor;
297
298         std::string               _last_backend_error_string;
299
300         Glib::Threads::Thread*     _hw_reset_event_thread;
301         gint                       _hw_reset_request_count;
302         Glib::Threads::Cond        _hw_reset_condition;
303         Glib::Threads::Mutex       _reset_request_lock;
304         gint                       _stop_hw_reset_processing;
305         Glib::Threads::Thread*     _hw_devicelist_update_thread;
306         gint                       _hw_devicelist_update_count;
307         Glib::Threads::Cond        _hw_devicelist_update_condition;
308         Glib::Threads::Mutex       _devicelist_update_lock;
309         gint                       _stop_hw_devicelist_processing;
310
311         void start_hw_event_processing();
312         void stop_hw_event_processing();
313         void do_reset_backend();
314         void do_devicelist_update();
315
316         typedef std::map<std::string,AudioBackendInfo*> BackendMap;
317         BackendMap _backends;
318         AudioBackendInfo* backend_discover (const std::string&);
319         void drop_backend ();
320
321 #ifdef SILENCE_AFTER
322         samplecnt_t _silence_countdown;
323         uint32_t   _silence_hit_cnt;
324 #endif
325
326 };
327
328 } // namespace ARDOUR
329
330 #endif /* __ardour_audioengine_h__ */