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