fixes from 2.X for latency/capture alignment stuff: don't reverse route list, update...
[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/thread.h>
35
36 #include "pbd/rcu.h"
37 #include "pbd/signals.h"
38
39 #include "ardour/ardour.h"
40 #include <jack/jack.h>
41 #include <jack/transport.h>
42
43 #include "ardour/data_type.h"
44 #include "ardour/session_handle.h"
45 #include "ardour/types.h"
46 #include "ardour/chan_count.h"
47
48 #ifdef HAVE_JACK_SESSION
49 #include <jack/session.h>
50 #endif
51
52 namespace ARDOUR {
53
54 class InternalPort;
55 class MidiPort;
56 class Port;
57 class Session;
58 class ProcessThread;
59
60 class AudioEngine : public SessionHandlePtr
61 {
62 public:
63         typedef std::set<Port*> Ports;
64
65         class disconnected_exception : public std::exception {
66         public:
67                 virtual const char *what() const throw() { return "AudioEngine is disconnected"; }
68         };
69
70         AudioEngine (std::string client_name, std::string session_uuid);
71         virtual ~AudioEngine ();
72
73         jack_client_t* jack() const;
74         bool connected() const { return _jack != 0; }
75
76         bool is_realtime () const;
77
78         ProcessThread* main_thread() const { return _main_thread; }
79
80         std::string client_name() const { return jack_client_name; }
81
82         int reconnect_to_jack ();
83         int disconnect_from_jack();
84
85         bool will_reconnect_at_halt ();
86         void set_reconnect_at_halt (bool);
87
88         int stop (bool forever = false);
89         int start ();
90         bool running() const { return _running; }
91
92         Glib::Mutex& process_lock() { return _process_lock; }
93
94         framecnt_t frame_rate () const;
95         pframes_t frames_per_cycle () const;
96
97         size_t raw_buffer_size(DataType t);
98
99         int usecs_per_cycle () const { return _usecs_per_cycle; }
100
101         bool get_sync_offset (pframes_t & offset) const;
102
103         pframes_t frames_since_cycle_start () {
104                 jack_client_t* _priv_jack = _jack;
105                 if (!_running || !_priv_jack) {
106                         return 0;
107                 }
108                 return jack_frames_since_cycle_start (_priv_jack);
109         }
110
111         pframes_t frame_time () {
112                 jack_client_t* _priv_jack = _jack;
113                 if (!_running || !_priv_jack) {
114                         return 0;
115                 }
116                 return jack_frame_time (_priv_jack);
117         }
118
119         pframes_t frame_time_at_cycle_start () {
120                 jack_client_t* _priv_jack = _jack;
121                 if (!_running || !_priv_jack) {
122                         return 0;
123                 }
124                 return jack_last_frame_time (_priv_jack);
125         }
126
127         pframes_t transport_frame () const {
128                 const jack_client_t* _priv_jack = _jack;
129                 if (!_running || !_priv_jack) {
130                         return 0;
131                 }
132                 return jack_get_current_transport_frame (_priv_jack);
133         }
134
135         int request_buffer_size (pframes_t);
136
137         framecnt_t set_monitor_check_interval (framecnt_t);
138         framecnt_t processed_frames() const { return _processed_frames; }
139
140         float get_cpu_load() {
141                 jack_client_t* _priv_jack = _jack;
142                 if (!_running || !_priv_jack) {
143                         return 0;
144                 }
145                 return jack_cpu_load (_priv_jack);
146         }
147
148         void set_session (Session *);
149         void remove_session (); // not a replacement for SessionHandle::session_going_away()
150
151         class PortRegistrationFailure : public std::exception {
152         public:
153                 PortRegistrationFailure (std::string const & why = "")
154                         : reason (why) {}
155
156                 ~PortRegistrationFailure () throw () {}
157
158                 virtual const char *what() const throw () { return reason.c_str(); }
159
160         private:
161                 std::string reason;
162         };
163
164         class NoBackendAvailable : public std::exception {
165         public:
166                 virtual const char *what() const throw() { return "could not connect to engine backend"; }
167         };
168
169         Port *register_input_port (DataType, const std::string& portname);
170         Port *register_output_port (DataType, const std::string& portname);
171         int   unregister_port (Port &);
172
173         bool port_is_physical (const std::string&) const;
174         void ensure_monitor_input (const std::string&, bool) const;
175
176         void split_cycle (pframes_t offset);
177
178         int connect (const std::string& source, const std::string& destination);
179         int disconnect (const std::string& source, const std::string& destination);
180         int disconnect (Port &);
181
182         const char ** get_ports (const std::string& port_name_pattern, const std::string& type_name_pattern, uint32_t flags);
183
184         bool can_request_hardware_monitoring ();
185
186         ChanCount n_physical_outputs () const;
187         ChanCount n_physical_inputs () const;
188
189         void get_physical_outputs (DataType type, std::vector<std::string>&);
190         void get_physical_inputs (DataType type, std::vector<std::string>&);
191
192         Port *get_port_by_name (const std::string &);
193
194         enum TransportState {
195                 TransportStopped = JackTransportStopped,
196                 TransportRolling = JackTransportRolling,
197                 TransportLooping = JackTransportLooping,
198                 TransportStarting = JackTransportStarting
199         };
200
201         void transport_start ();
202         void transport_stop ();
203         void transport_locate (framepos_t);
204         TransportState transport_state ();
205
206         int  reset_timebase ();
207
208         void update_latencies ();
209
210         /* start/stop freewheeling */
211
212         int freewheel (bool onoff);
213         bool freewheeling() const { return _freewheeling; }
214
215         /* this signal is sent for every process() cycle while freewheeling.
216 _          the regular process() call to session->process() is not made.
217         */
218
219         PBD::Signal1<int, pframes_t> Freewheel;
220
221         PBD::Signal0<void> Xrun;
222
223         /* this signal is if JACK notifies us of a graph order event */
224
225         PBD::Signal0<void> GraphReordered;
226
227 #ifdef HAVE_JACK_SESSION
228         PBD::Signal1<void,jack_session_event_t *> JackSessionEvent;
229 #endif
230
231
232         /* this signal is emitted if the sample rate changes */
233
234         PBD::Signal1<void, framecnt_t> SampleRateChanged;
235
236         /* this signal is sent if JACK ever disconnects us */
237
238         PBD::Signal1<void,const char*> Halted;
239
240         /* these two are emitted when the engine itself is
241            started and stopped
242         */
243
244         PBD::Signal0<void> Running;
245         PBD::Signal0<void> Stopped;
246
247         /** Emitted if a JACK port is registered or unregistered */
248         PBD::Signal0<void> PortRegisteredOrUnregistered;
249
250         /** Emitted if a JACK port is connected or disconnected.
251          *  The Port parameters are the ports being connected / disconnected, or 0 if they are not known to Ardour.
252          *  The bool parameter is true if ports were connected, or false for disconnected.
253          */
254         PBD::Signal3<void, Port *, Port *, bool> PortConnectedOrDisconnected;
255
256         std::string make_port_name_relative (std::string) const;
257         std::string make_port_name_non_relative (std::string) const;
258         bool port_is_mine (const std::string&) const;
259
260         static AudioEngine* instance() { return _instance; }
261         void died ();
262
263         int create_process_thread (boost::function<void()>, pthread_t*, size_t stacksize);
264
265 private:
266         static AudioEngine*       _instance;
267
268         jack_client_t* volatile   _jack; /* could be reset to null by SIGPIPE or another thread */
269         std::string                jack_client_name;
270         Glib::Mutex               _process_lock;
271         Glib::Cond                 session_removed;
272         bool                       session_remove_pending;
273         bool                      _running;
274         bool                      _has_run;
275         mutable framecnt_t        _buffer_size;
276         std::map<DataType,size_t> _raw_buffer_sizes;
277         mutable framecnt_t        _frame_rate;
278         /// number of frames between each check for changes in monitor input
279         framecnt_t                 monitor_check_interval;
280         /// time of the last monitor check in frames
281         framecnt_t                 last_monitor_check;
282         /// the number of frames processed since start() was called
283         framecnt_t                _processed_frames;
284         bool                      _freewheeling;
285         bool                      _freewheel_pending;
286         boost::function<int(framecnt_t)>  freewheel_action;
287         bool                       reconnect_on_halt;
288         int                       _usecs_per_cycle;
289         bool                       port_remove_in_progress;
290
291         SerializedRCUManager<Ports> ports;
292
293         Port* register_port (DataType type, const std::string& portname, bool input);
294
295         int    process_callback (pframes_t nframes);
296         void*  process_thread ();
297         void   remove_all_ports ();
298
299         ChanCount n_physical (unsigned long) const;
300         void get_physical (DataType, unsigned long, std::vector<std::string> &);
301
302         void port_registration_failure (const std::string& portname);
303
304         static int  _xrun_callback (void *arg);
305 #ifdef HAVE_JACK_SESSION
306         static void _session_callback (jack_session_event_t *event, void *arg);
307 #endif
308         static int  _graph_order_callback (void *arg);
309         static int  _process_callback (pframes_t nframes, void *arg);
310         static void* _process_thread (void *arg);
311         static int  _sample_rate_callback (pframes_t nframes, void *arg);
312         static int  _bufsize_callback (pframes_t nframes, void *arg);
313         static void _jack_timebase_callback (jack_transport_state_t, pframes_t, jack_position_t*, int, void*);
314         static int  _jack_sync_callback (jack_transport_state_t, jack_position_t*, void *arg);
315         static void _freewheel_callback (int , void *arg);
316         static void _registration_callback (jack_port_id_t, int, void *);
317         static void _connect_callback (jack_port_id_t, jack_port_id_t, int, void *);
318
319         void jack_timebase_callback (jack_transport_state_t, pframes_t, jack_position_t*, int);
320         int  jack_sync_callback (jack_transport_state_t, jack_position_t*);
321         int  jack_bufsize_callback (pframes_t);
322         int  jack_sample_rate_callback (pframes_t);
323
324         void set_jack_callbacks ();
325
326         static void _latency_callback (jack_latency_callback_mode_t, void*);
327         void jack_latency_callback (jack_latency_callback_mode_t);
328
329         int connect_to_jack (std::string client_name, std::string session_uuid);
330
331         static void halted (void *);
332         static void halted_info (jack_status_t,const char*,void *);
333
334         void meter_thread ();
335         void start_metering_thread ();
336         void stop_metering_thread ();
337
338         Glib::Thread*    m_meter_thread;
339         static gint      m_meter_exit;
340
341         ProcessThread* _main_thread;
342
343         struct ThreadData {
344                 AudioEngine* engine;
345                 boost::function<void()> f;
346                 size_t stacksize;
347
348                 ThreadData (AudioEngine* ae, boost::function<void()> fp, size_t stacksz)
349                 : engine (ae) , f (fp) , stacksize (stacksz) {}
350         };
351
352         static void* _start_process_thread (void*);
353 };
354
355 } // namespace ARDOUR
356
357 #endif /* __ardour_audioengine_h__ */