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