2 Copyright (C) 2010 Paul Davis
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.
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.
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.
23 #include "pbd/compose.h"
24 #include "pbd/debug_rt_alloc.h"
25 #include "pbd/pthread_utils.h"
27 #include "ardour/debug.h"
28 #include "ardour/graph.h"
29 #include "ardour/types.h"
30 #include "ardour/session.h"
31 #include "ardour/route.h"
32 #include "ardour/process_thread.h"
33 #include "ardour/audioengine.h"
37 using namespace ARDOUR;
42 static Graph* graph = 0;
48 return !graph->in_process_thread ();
54 Graph::Graph (Session & session)
55 : SessionHandleRef (session)
56 , _threads_active (false)
57 , _execution_sem ("graph_execution", 0)
58 , _callback_start_sem ("graph_start", 0)
59 , _callback_done_sem ("graph_done", 0)
61 pthread_mutex_init( &_trigger_mutex, NULL);
63 /* XXX: rather hacky `fix' to stop _trigger_queue.push_back() allocating
64 * memory in the RT thread.
66 _trigger_queue.reserve (8192);
68 _execution_tokens = 0;
76 ARDOUR::AudioEngine::instance()->Running.connect_same_thread (engine_connections, boost::bind (&Graph::reset_thread_list, this));
77 ARDOUR::AudioEngine::instance()->Stopped.connect_same_thread (engine_connections, boost::bind (&Graph::engine_stopped, this));
78 ARDOUR::AudioEngine::instance()->Halted.connect_same_thread (engine_connections, boost::bind (&Graph::engine_stopped, this));
84 pbd_alloc_allowed = &::alloc_allowed;
89 Graph::engine_stopped ()
92 cerr << "Graph::engine_stopped. n_thread: " << AudioEngine::instance()->process_thread_count() << endl;
94 if (AudioEngine::instance()->process_thread_count() != 0) {
99 /** Set up threads for running the graph */
101 Graph::reset_thread_list ()
103 uint32_t num_threads = how_many_dsp_threads ();
105 /* For now, we shouldn't be using the graph code if we only have 1 DSP thread */
106 assert (num_threads > 1);
108 /* don't bother doing anything here if we already have the right
112 if (AudioEngine::instance()->process_thread_count() == num_threads) {
116 Glib::Threads::Mutex::Lock lm (_session.engine().process_lock());
118 if (AudioEngine::instance()->process_thread_count() != 0) {
122 _threads_active = true;
124 if (AudioEngine::instance()->create_process_thread (boost::bind (&Graph::main_thread, this)) != 0) {
125 throw failed_constructor ();
128 for (uint32_t i = 2; i < num_threads; ++i) {
129 if (AudioEngine::instance()->create_process_thread (boost::bind (&Graph::helper_thread, this))) {
130 throw failed_constructor ();
136 Graph::session_going_away()
140 // now drop all references on the nodes.
141 _nodes_rt[0].clear();
142 _nodes_rt[1].clear();
143 _init_trigger_list[0].clear();
144 _init_trigger_list[1].clear();
145 _trigger_queue.clear();
149 Graph::drop_threads ()
151 Glib::Threads::Mutex::Lock ls (_swap_mutex);
152 _threads_active = false;
154 uint32_t thread_count = AudioEngine::instance()->process_thread_count ();
156 for (unsigned int i=0; i < thread_count; i++) {
157 pthread_mutex_lock (&_trigger_mutex);
158 _execution_sem.signal ();
159 pthread_mutex_unlock (&_trigger_mutex);
162 pthread_mutex_lock (&_trigger_mutex);
163 _callback_start_sem.signal ();
164 pthread_mutex_unlock (&_trigger_mutex);
166 AudioEngine::instance()->join_process_threads ();
168 /* signal main process thread if it's waiting for an already terminated thread */
169 _callback_done_sem.signal ();
170 _execution_tokens = 0;
173 * This is somewhat ugly, yet if a thread is killed (e.g jackd terminates
174 * abnormally), some semaphores are still unlocked.
177 int d1 = _execution_sem.reset ();
178 int d2 = _callback_start_sem.reset ();
179 int d3 = _callback_done_sem.reset ();
180 cerr << "Graph::drop_threads() sema-counts: " << d1 << ", " << d2<< ", " << d3 << endl;
182 _execution_sem.reset ();
183 _callback_start_sem.reset ();
184 _callback_done_sem.reset ();
189 Graph::clear_other_chain ()
191 Glib::Threads::Mutex::Lock ls (_swap_mutex);
194 if (_setup_chain != _pending_chain) {
196 for (node_list_t::iterator ni=_nodes_rt[_setup_chain].begin(); ni!=_nodes_rt[_setup_chain].end(); ni++) {
197 (*ni)->_activation_set[_setup_chain].clear();
200 _nodes_rt[_setup_chain].clear ();
201 _init_trigger_list[_setup_chain].clear ();
204 /* setup chain == pending chain - we have
205 * to wait till this is no longer true.
207 _cleanup_cond.wait (_swap_mutex);
214 node_list_t::iterator i;
217 if (_swap_mutex.trylock()) {
218 // we got the swap mutex.
219 if (_current_chain != _pending_chain)
221 // printf ("chain swap ! %d -> %d\n", _current_chain, _pending_chain);
222 _setup_chain = _current_chain;
223 _current_chain = _pending_chain;
224 _cleanup_cond.signal ();
226 _swap_mutex.unlock ();
229 chain = _current_chain;
232 for (i=_nodes_rt[chain].begin(); i!=_nodes_rt[chain].end(); i++) {
234 _graph_empty = false;
236 _finished_refcount = _init_finished_refcount[chain];
238 /* Trigger the initial nodes for processing, which are the ones at the `input' end */
239 pthread_mutex_lock (&_trigger_mutex);
240 for (i=_init_trigger_list[chain].begin(); i!=_init_trigger_list[chain].end(); i++) {
241 /* don't use ::trigger here, as we have already locked the mutex */
242 _trigger_queue.push_back (i->get ());
244 pthread_mutex_unlock (&_trigger_mutex);
248 Graph::trigger (GraphNode* n)
250 pthread_mutex_lock (&_trigger_mutex);
251 _trigger_queue.push_back (n);
252 pthread_mutex_unlock (&_trigger_mutex);
255 /** Called when a node at the `output' end of the chain (ie one that has no-one to feed)
261 if (g_atomic_int_dec_and_test (const_cast<gint*> (&_finished_refcount))) {
263 /* We have run all the nodes that are at the `output' end of
264 * the graph, so there is nothing more to do this time around.
272 Graph::restart_cycle()
274 // we are through. wakeup our caller.
277 _callback_done_sem.signal ();
279 /* Block until the a process callback triggers us */
280 _callback_start_sem.wait();
282 if (!_threads_active) {
288 if (_graph_empty && _threads_active) {
292 // returning will restart the cycle.
293 // starting with waking up the others.
296 /** Rechain our stuff using a list of routes (which can be in any order) and
297 * a directed graph of their interconnections, which is guaranteed to be
301 Graph::rechain (boost::shared_ptr<RouteList> routelist, GraphEdges const & edges)
303 Glib::Threads::Mutex::Lock ls (_swap_mutex);
305 int chain = _setup_chain;
306 DEBUG_TRACE (DEBUG::Graph, string_compose ("============== setup %1\n", chain));
308 /* This will become the number of nodes that do not feed any other node;
309 * once we have processed this number of those nodes, we have finished.
311 _init_finished_refcount[chain] = 0;
313 /* This will become a list of nodes that are not fed by another node, ie
314 * those at the `input' end.
316 _init_trigger_list[chain].clear();
318 _nodes_rt[chain].clear();
320 /* Clear things out, and make _nodes_rt[chain] a copy of routelist */
321 for (RouteList::iterator ri=routelist->begin(); ri!=routelist->end(); ri++) {
322 (*ri)->_init_refcount[chain] = 0;
323 (*ri)->_activation_set[chain].clear();
324 _nodes_rt[chain].push_back (*ri);
327 // now add refs for the connections.
329 for (node_list_t::iterator ni = _nodes_rt[chain].begin(); ni != _nodes_rt[chain].end(); ni++) {
331 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*ni);
333 /* The routes that are directly fed by r */
334 set<GraphVertex> fed_from_r = edges.from (r);
336 /* Hence whether r has an output */
337 bool const has_output = !fed_from_r.empty ();
339 /* Set up r's activation set */
340 for (set<GraphVertex>::iterator i = fed_from_r.begin(); i != fed_from_r.end(); ++i) {
341 r->_activation_set[chain].insert (*i);
344 /* r has an input if there are some incoming edges to r in the graph */
345 bool const has_input = !edges.has_none_to (r);
347 /* Increment the refcount of any route that we directly feed */
348 for (node_set_t::iterator ai = r->_activation_set[chain].begin(); ai != r->_activation_set[chain].end(); ai++) {
349 (*ai)->_init_refcount[chain] += 1;
353 /* no input, so this node needs to be triggered initially to get things going */
354 _init_trigger_list[chain].push_back (*ni);
358 /* no output, so this is one of the nodes that we can count off to decide
361 _init_finished_refcount[chain] += 1;
365 _pending_chain = chain;
369 /** Called by both the main thread and all helpers.
370 * @return true to quit, false to carry on.
377 pthread_mutex_lock (&_trigger_mutex);
378 if (_trigger_queue.size()) {
379 to_run = _trigger_queue.back();
380 _trigger_queue.pop_back();
385 /* the number of threads that are asleep */
386 int et = _execution_tokens;
387 /* the number of nodes that need to be run */
388 int ts = _trigger_queue.size();
390 /* hence how many threads to wake up */
391 int wakeup = min (et, ts);
392 /* update the number of threads that will still be sleeping */
393 _execution_tokens -= wakeup;
395 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 signals %2\n", pthread_name(), wakeup));
397 for (int i = 0; i < wakeup; i++) {
398 _execution_sem.signal ();
401 while (to_run == 0) {
402 _execution_tokens += 1;
403 pthread_mutex_unlock (&_trigger_mutex);
404 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 goes to sleep\n", pthread_name()));
405 _execution_sem.wait ();
406 if (!_threads_active) {
409 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 is awake\n", pthread_name()));
410 pthread_mutex_lock (&_trigger_mutex);
411 if (_trigger_queue.size()) {
412 to_run = _trigger_queue.back();
413 _trigger_queue.pop_back();
416 pthread_mutex_unlock (&_trigger_mutex);
419 to_run->finish (_current_chain);
421 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 has finished run_one()\n", pthread_name()));
423 return !_threads_active;
427 Graph::helper_thread()
429 suspend_rt_malloc_checks ();
430 ProcessThread* pt = new ProcessThread ();
431 resume_rt_malloc_checks ();
445 /** Here's the main graph thread */
449 suspend_rt_malloc_checks ();
450 ProcessThread* pt = new ProcessThread ();
451 resume_rt_malloc_checks ();
456 _callback_start_sem.wait ();
458 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread is awake\n");
460 if (!_threads_active) {
468 if (_graph_empty && _threads_active) {
469 _callback_done_sem.signal ();
470 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread sees graph done, goes back to sleep\n");
474 /* This loop will run forever */
476 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread runs one graph node\n");
487 Graph::dump (int chain)
490 node_list_t::iterator ni;
491 node_set_t::iterator ai;
493 chain = _pending_chain;
495 DEBUG_TRACE (DEBUG::Graph, "--------------------------------------------Graph dump:\n");
496 for (ni=_nodes_rt[chain].begin(); ni!=_nodes_rt[chain].end(); ni++) {
497 boost::shared_ptr<Route> rp = boost::dynamic_pointer_cast<Route>( *ni);
498 DEBUG_TRACE (DEBUG::Graph, string_compose ("GraphNode: %1 refcount: %2\n", rp->name().c_str(), (*ni)->_init_refcount[chain]));
499 for (ai=(*ni)->_activation_set[chain].begin(); ai!=(*ni)->_activation_set[chain].end(); ai++) {
500 DEBUG_TRACE (DEBUG::Graph, string_compose (" triggers: %1\n", boost::dynamic_pointer_cast<Route>(*ai)->name().c_str()));
504 DEBUG_TRACE (DEBUG::Graph, "------------- trigger list:\n");
505 for (ni=_init_trigger_list[chain].begin(); ni!=_init_trigger_list[chain].end(); ni++) {
506 DEBUG_TRACE (DEBUG::Graph, string_compose ("GraphNode: %1 refcount: %2\n", boost::dynamic_pointer_cast<Route>(*ni)->name().c_str(), (*ni)->_init_refcount[chain]));
509 DEBUG_TRACE (DEBUG::Graph, string_compose ("final activation refcount: %1\n", _init_finished_refcount[chain]));
514 Graph::silent_process_routes (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool& need_butler)
516 if (!_threads_active) return 0;
518 _process_nframes = nframes;
519 _process_start_frame = start_frame;
520 _process_end_frame = end_frame;
522 _process_silent = true;
523 _process_noroll = false;
525 _process_need_butler = false;
528 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for silent process\n");
529 _callback_start_sem.signal ();
530 _callback_done_sem.wait ();
533 need_butler = _process_need_butler;
535 return _process_retval;
539 Graph::process_routes (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
541 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("graph execution from %1 to %2 = %3\n", start_frame, end_frame, nframes));
543 if (!_threads_active) return 0;
545 _process_nframes = nframes;
546 _process_start_frame = start_frame;
547 _process_end_frame = end_frame;
548 _process_declick = declick;
550 _process_silent = false;
551 _process_noroll = false;
553 _process_need_butler = false;
555 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for non-silent process\n");
556 _callback_start_sem.signal ();
557 _callback_done_sem.wait ();
559 DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
561 need_butler = _process_need_butler;
563 return _process_retval;
567 Graph::routes_no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame,
568 bool non_rt_pending, int declick)
570 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("no-roll graph execution from %1 to %2 = %3\n", start_frame, end_frame, nframes));
572 if (!_threads_active) return 0;
574 _process_nframes = nframes;
575 _process_start_frame = start_frame;
576 _process_end_frame = end_frame;
577 _process_declick = declick;
578 _process_non_rt_pending = non_rt_pending;
580 _process_silent = false;
581 _process_noroll = true;
583 _process_need_butler = false;
585 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for no-roll process\n");
586 _callback_start_sem.signal ();
587 _callback_done_sem.wait ();
589 return _process_retval;
592 Graph::process_one_route (Route* route)
594 bool need_butler = false;
599 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 runs route %2\n", pthread_name(), route->name()));
601 if (_process_silent) {
602 retval = route->silent_roll (_process_nframes, _process_start_frame, _process_end_frame, need_butler);
603 } else if (_process_noroll) {
604 route->set_pending_declick (_process_declick);
605 retval = route->no_roll (_process_nframes, _process_start_frame, _process_end_frame, _process_non_rt_pending);
607 route->set_pending_declick (_process_declick);
608 retval = route->roll (_process_nframes, _process_start_frame, _process_end_frame, _process_declick, need_butler);
612 _process_retval = retval;
616 _process_need_butler = true;
621 Graph::in_process_thread () const
623 return AudioEngine::instance()->in_process_thread ();