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 = 1; 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.
275 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 cycle done.\n", pthread_name()));
278 _callback_done_sem.signal ();
280 /* Block until the a process callback triggers us */
281 _callback_start_sem.wait();
283 if (!_threads_active) {
287 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 prepare new cycle.\n", pthread_name()));
290 if (_graph_empty && _threads_active) {
294 // returning will restart the cycle.
295 // starting with waking up the others.
298 /** Rechain our stuff using a list of routes (which can be in any order) and
299 * a directed graph of their interconnections, which is guaranteed to be
303 Graph::rechain (boost::shared_ptr<RouteList> routelist, GraphEdges const & edges)
305 Glib::Threads::Mutex::Lock ls (_swap_mutex);
307 int chain = _setup_chain;
308 DEBUG_TRACE (DEBUG::Graph, string_compose ("============== setup %1\n", chain));
310 /* This will become the number of nodes that do not feed any other node;
311 * once we have processed this number of those nodes, we have finished.
313 _init_finished_refcount[chain] = 0;
315 /* This will become a list of nodes that are not fed by another node, ie
316 * those at the `input' end.
318 _init_trigger_list[chain].clear();
320 _nodes_rt[chain].clear();
322 /* Clear things out, and make _nodes_rt[chain] a copy of routelist */
323 for (RouteList::iterator ri=routelist->begin(); ri!=routelist->end(); ri++) {
324 (*ri)->_init_refcount[chain] = 0;
325 (*ri)->_activation_set[chain].clear();
326 _nodes_rt[chain].push_back (*ri);
329 // now add refs for the connections.
331 for (node_list_t::iterator ni = _nodes_rt[chain].begin(); ni != _nodes_rt[chain].end(); ni++) {
333 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*ni);
335 /* The routes that are directly fed by r */
336 set<GraphVertex> fed_from_r = edges.from (r);
338 /* Hence whether r has an output */
339 bool const has_output = !fed_from_r.empty ();
341 /* Set up r's activation set */
342 for (set<GraphVertex>::iterator i = fed_from_r.begin(); i != fed_from_r.end(); ++i) {
343 r->_activation_set[chain].insert (*i);
346 /* r has an input if there are some incoming edges to r in the graph */
347 bool const has_input = !edges.has_none_to (r);
349 /* Increment the refcount of any route that we directly feed */
350 for (node_set_t::iterator ai = r->_activation_set[chain].begin(); ai != r->_activation_set[chain].end(); ai++) {
351 (*ai)->_init_refcount[chain] += 1;
355 /* no input, so this node needs to be triggered initially to get things going */
356 _init_trigger_list[chain].push_back (*ni);
360 /* no output, so this is one of the nodes that we can count off to decide
363 _init_finished_refcount[chain] += 1;
367 _pending_chain = chain;
371 /** Called by both the main thread and all helpers.
372 * @return true to quit, false to carry on.
379 pthread_mutex_lock (&_trigger_mutex);
380 if (_trigger_queue.size()) {
381 to_run = _trigger_queue.back();
382 _trigger_queue.pop_back();
387 /* the number of threads that are asleep */
388 int et = _execution_tokens;
389 /* the number of nodes that need to be run */
390 int ts = _trigger_queue.size();
392 /* hence how many threads to wake up */
393 int wakeup = min (et, ts);
394 /* update the number of threads that will still be sleeping */
395 _execution_tokens -= wakeup;
397 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 signals %2\n", pthread_name(), wakeup));
399 for (int i = 0; i < wakeup; i++) {
400 _execution_sem.signal ();
403 while (to_run == 0) {
404 _execution_tokens += 1;
405 pthread_mutex_unlock (&_trigger_mutex);
406 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 goes to sleep\n", pthread_name()));
407 _execution_sem.wait ();
408 if (!_threads_active) {
411 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 is awake\n", pthread_name()));
412 pthread_mutex_lock (&_trigger_mutex);
413 if (_trigger_queue.size()) {
414 to_run = _trigger_queue.back();
415 _trigger_queue.pop_back();
418 pthread_mutex_unlock (&_trigger_mutex);
421 to_run->finish (_current_chain);
423 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 has finished run_one()\n", pthread_name()));
425 return !_threads_active;
429 Graph::helper_thread()
431 suspend_rt_malloc_checks ();
432 ProcessThread* pt = new ProcessThread ();
433 resume_rt_malloc_checks ();
447 /** Here's the main graph thread */
451 suspend_rt_malloc_checks ();
452 ProcessThread* pt = new ProcessThread ();
453 resume_rt_malloc_checks ();
458 _callback_start_sem.wait ();
460 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread is awake\n");
462 if (!_threads_active) {
470 if (_graph_empty && _threads_active) {
471 _callback_done_sem.signal ();
472 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread sees graph done, goes back to sleep\n");
476 /* This loop will run forever */
478 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("main thread (%1) runs one graph node\n", pthread_name ()));
489 Graph::dump (int chain)
492 node_list_t::iterator ni;
493 node_set_t::iterator ai;
495 chain = _pending_chain;
497 DEBUG_TRACE (DEBUG::Graph, "--------------------------------------------Graph dump:\n");
498 for (ni=_nodes_rt[chain].begin(); ni!=_nodes_rt[chain].end(); ni++) {
499 boost::shared_ptr<Route> rp = boost::dynamic_pointer_cast<Route>( *ni);
500 DEBUG_TRACE (DEBUG::Graph, string_compose ("GraphNode: %1 refcount: %2\n", rp->name().c_str(), (*ni)->_init_refcount[chain]));
501 for (ai=(*ni)->_activation_set[chain].begin(); ai!=(*ni)->_activation_set[chain].end(); ai++) {
502 DEBUG_TRACE (DEBUG::Graph, string_compose (" triggers: %1\n", boost::dynamic_pointer_cast<Route>(*ai)->name().c_str()));
506 DEBUG_TRACE (DEBUG::Graph, "------------- trigger list:\n");
507 for (ni=_init_trigger_list[chain].begin(); ni!=_init_trigger_list[chain].end(); ni++) {
508 DEBUG_TRACE (DEBUG::Graph, string_compose ("GraphNode: %1 refcount: %2\n", boost::dynamic_pointer_cast<Route>(*ni)->name().c_str(), (*ni)->_init_refcount[chain]));
511 DEBUG_TRACE (DEBUG::Graph, string_compose ("final activation refcount: %1\n", _init_finished_refcount[chain]));
516 Graph::process_routes (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool& need_butler)
518 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("graph execution from %1 to %2 = %3\n", start_sample, end_sample, nframes));
520 if (!_threads_active) return 0;
522 _process_nframes = nframes;
523 _process_start_sample = start_sample;
524 _process_end_sample = end_sample;
526 _process_noroll = false;
528 _process_need_butler = false;
530 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for non-silent process\n");
531 _callback_start_sem.signal ();
532 _callback_done_sem.wait ();
533 DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
535 need_butler = _process_need_butler;
537 return _process_retval;
541 Graph::routes_no_roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool non_rt_pending)
543 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("no-roll graph execution from %1 to %2 = %3\n", start_sample, end_sample, nframes));
545 if (!_threads_active) return 0;
547 _process_nframes = nframes;
548 _process_start_sample = start_sample;
549 _process_end_sample = end_sample;
550 _process_non_rt_pending = non_rt_pending;
552 _process_noroll = true;
554 _process_need_butler = false;
556 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for no-roll process\n");
557 _callback_start_sem.signal ();
558 _callback_done_sem.wait ();
559 DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
561 return _process_retval;
564 Graph::process_one_route (Route* route)
566 bool need_butler = false;
571 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 runs route %2\n", pthread_name(), route->name()));
573 if (_process_noroll) {
574 retval = route->no_roll (_process_nframes, _process_start_sample, _process_end_sample, _process_non_rt_pending);
576 retval = route->roll (_process_nframes, _process_start_sample, _process_end_sample, need_butler);
580 _process_retval = retval;
584 _process_need_butler = true;
589 Graph::in_process_thread () const
591 return AudioEngine::instance()->in_process_thread ();