Merge branch 'master' into windows
[ardour.git] / libs / ardour / graph.cc
1 /*
2   Copyright (C) 2010 Paul Davis
3   Author: Torben Hohn
4
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.
9
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.
14
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.
18
19 */
20 #include <stdio.h>
21 #include <cmath>
22
23 #include "pbd/compose.h"
24 #include "pbd/debug_rt_alloc.h"
25 #include "pbd/pthread_utils.h"
26
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"
34
35 #include <jack/thread.h>
36
37 #include "i18n.h"
38
39 using namespace ARDOUR;
40 using namespace PBD;
41 using namespace std;
42
43 #ifdef DEBUG_RT_ALLOC
44 static Graph* graph = 0;
45
46 extern "C" {
47
48 int alloc_allowed ()
49 {
50         return !graph->in_process_thread ();
51 }
52
53 }
54 #endif
55
56 Graph::Graph (Session & session)
57         : SessionHandleRef (session)
58         , _quit_threads (false)
59         , _execution_sem ("graph_execution", 0)
60         , _callback_start_sem ("graph_start", 0)
61         , _callback_done_sem ("graph_done", 0)
62         , _cleanup_sem ("graph_cleanup", 0)
63 {
64         pthread_mutex_init( &_trigger_mutex, NULL);
65
66         /* XXX: rather hacky `fix' to stop _trigger_queue.push_back() allocating
67            memory in the RT thread.
68         */
69         _trigger_queue.reserve (8192);
70
71         _execution_tokens = 0;
72
73         _current_chain = 0;
74         _pending_chain = 0;
75         _setup_chain   = 1;
76         _quit_threads = false;
77         _graph_empty = true;
78
79         reset_thread_list ();
80
81 #ifdef DEBUG_RT_ALLOC
82         graph = this;
83         pbd_alloc_allowed = &::alloc_allowed;
84 #endif
85 }
86
87 /** Set up threads for running the graph */
88 void
89 Graph::reset_thread_list ()
90 {
91         uint32_t num_threads = how_many_dsp_threads ();
92
93         /* For now, we shouldn't be using the graph code if we only have 1 DSP thread */
94         assert (num_threads > 1);
95
96         /* don't bother doing anything here if we already have the right
97            number of threads.
98         */
99
100         if (AudioEngine::instance()->process_thread_count() == num_threads) {
101                 return;
102         }
103
104         Glib::Threads::Mutex::Lock lm (_session.engine().process_lock());
105
106         if (AudioEngine::instance()->process_thread_count() != 0) {
107                 drop_threads ();
108         }
109
110         if (AudioEngine::instance()->create_process_thread (boost::bind (&Graph::main_thread, this)) != 0) {
111                 throw failed_constructor ();
112         }
113
114         for (uint32_t i = 1; i < num_threads; ++i) {
115                 if (AudioEngine::instance()->create_process_thread (boost::bind (&Graph::helper_thread, this))) {
116                         throw failed_constructor ();
117                 }
118         }
119 }
120
121 void
122 Graph::session_going_away()
123 {
124         drop_threads ();
125
126         // now drop all references on the nodes.
127         _nodes_rt[0].clear();
128         _nodes_rt[1].clear();
129         _init_trigger_list[0].clear();
130         _init_trigger_list[1].clear();
131         _trigger_queue.clear();
132 }
133
134 void
135 Graph::drop_threads ()
136 {
137         _quit_threads = true;
138
139         uint32_t thread_count = AudioEngine::instance()->process_thread_count ();
140
141         for (unsigned int i=0; i < thread_count; i++) {
142                 _execution_sem.signal ();
143         }
144
145         _callback_start_sem.signal ();
146
147         AudioEngine::instance()->join_process_threads ();
148
149         _execution_tokens = 0;
150
151         _quit_threads = false;
152 }
153
154 void
155 Graph::clear_other_chain ()
156 {
157         Glib::Threads::Mutex::Lock ls (_swap_mutex);
158
159         while (1) {
160                 if (_setup_chain != _pending_chain) {
161
162                         for (node_list_t::iterator ni=_nodes_rt[_setup_chain].begin(); ni!=_nodes_rt[_setup_chain].end(); ni++) {
163                                 (*ni)->_activation_set[_setup_chain].clear();
164                         }
165
166                         _nodes_rt[_setup_chain].clear ();
167                         _init_trigger_list[_setup_chain].clear ();
168                         break;
169                 }
170                 /* setup chain == pending chain - we have
171                    to wait till this is no longer true.
172                 */
173                 _cleanup_cond.wait (_swap_mutex);
174         }
175 }
176
177 void
178 Graph::prep()
179 {
180         node_list_t::iterator i;
181         int chain;
182
183         if (_swap_mutex.trylock()) {
184                 // we got the swap mutex.
185                 if (_current_chain != _pending_chain)
186                 {
187                         // printf ("chain swap ! %d -> %d\n", _current_chain, _pending_chain);
188                         _setup_chain = _current_chain;
189                         _current_chain = _pending_chain;
190                         _cleanup_cond.signal ();
191                 }
192                 _swap_mutex.unlock ();
193         }
194
195         chain = _current_chain;
196
197         _graph_empty = true;
198         for (i=_nodes_rt[chain].begin(); i!=_nodes_rt[chain].end(); i++) {
199                 (*i)->prep( chain);
200                 _graph_empty = false;
201         }
202         _finished_refcount = _init_finished_refcount[chain];
203
204         /* Trigger the initial nodes for processing, which are the ones at the `input' end */
205         pthread_mutex_lock (&_trigger_mutex);
206         for (i=_init_trigger_list[chain].begin(); i!=_init_trigger_list[chain].end(); i++) {
207                 /* don't use ::trigger here, as we have already locked the mutex */
208                 _trigger_queue.push_back (i->get ());
209         }
210         pthread_mutex_unlock (&_trigger_mutex);
211 }
212
213 void
214 Graph::trigger (GraphNode* n)
215 {
216         pthread_mutex_lock (&_trigger_mutex);
217         _trigger_queue.push_back (n);
218         pthread_mutex_unlock (&_trigger_mutex);
219 }
220
221 /** Called when a node at the `output' end of the chain (ie one that has no-one to feed)
222  *  is finished.
223  */
224 void
225 Graph::dec_ref()
226 {
227         if (g_atomic_int_dec_and_test (&_finished_refcount)) {
228
229                 /* We have run all the nodes that are at the `output' end of
230                    the graph, so there is nothing more to do this time around.
231                 */
232
233                 restart_cycle ();
234         }
235 }
236
237 void
238 Graph::restart_cycle()
239 {
240         // we are through. wakeup our caller.
241
242   again:
243         _callback_done_sem.signal ();
244
245         /* Block until the a process callback triggers us */
246         _callback_start_sem.wait();
247
248         if (_quit_threads) {
249                 return;
250         }
251
252         prep ();
253
254         if (_graph_empty) {
255                 goto again;
256         }
257
258         // returning will restart the cycle.
259         // starting with waking up the others.
260 }
261
262 /** Rechain our stuff using a list of routes (which can be in any order) and
263  *  a directed graph of their interconnections, which is guaranteed to be
264  *  acyclic.
265  */
266
267 void
268 Graph::rechain (boost::shared_ptr<RouteList> routelist, GraphEdges const & edges)
269 {
270         Glib::Threads::Mutex::Lock ls (_swap_mutex);
271
272         int chain = _setup_chain;
273         DEBUG_TRACE (DEBUG::Graph, string_compose ("============== setup %1\n", chain));
274
275         /* This will become the number of nodes that do not feed any other node;
276            once we have processed this number of those nodes, we have finished.
277         */
278         _init_finished_refcount[chain] = 0;
279
280         /* This will become a list of nodes that are not fed by another node, ie
281            those at the `input' end.
282         */
283         _init_trigger_list[chain].clear();
284
285         _nodes_rt[chain].clear();
286
287         /* Clear things out, and make _nodes_rt[chain] a copy of routelist */
288         for (RouteList::iterator ri=routelist->begin(); ri!=routelist->end(); ri++) {
289                 (*ri)->_init_refcount[chain] = 0;
290                 (*ri)->_activation_set[chain].clear();
291                 _nodes_rt[chain].push_back (*ri);
292         }
293
294         // now add refs for the connections.
295
296         for (node_list_t::iterator ni = _nodes_rt[chain].begin(); ni != _nodes_rt[chain].end(); ni++) {
297
298                 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*ni);
299
300                 /* The routes that are directly fed by r */
301                 set<GraphVertex> fed_from_r = edges.from (r);
302
303                 /* Hence whether r has an output */
304                 bool const has_output = !fed_from_r.empty ();
305
306                 /* Set up r's activation set */
307                 for (set<GraphVertex>::iterator i = fed_from_r.begin(); i != fed_from_r.end(); ++i) {
308                         r->_activation_set[chain].insert (*i);
309                 }
310
311                 /* r has an input if there are some incoming edges to r in the graph */
312                 bool const has_input = !edges.has_none_to (r);
313
314                 /* Increment the refcount of any route that we directly feed */
315                 for (node_set_t::iterator ai = r->_activation_set[chain].begin(); ai != r->_activation_set[chain].end(); ai++) {
316                         (*ai)->_init_refcount[chain] += 1;
317                 }
318
319                 if (!has_input) {
320                         /* no input, so this node needs to be triggered initially to get things going */
321                         _init_trigger_list[chain].push_back (*ni);
322                 }
323
324                 if (!has_output) {
325                         /* no output, so this is one of the nodes that we can count off to decide
326                            if we've finished
327                         */
328                         _init_finished_refcount[chain] += 1;
329                 }
330         }
331
332         _pending_chain = chain;
333         dump(chain);
334 }
335
336 /** Called by both the main thread and all helpers.
337  *  @return true to quit, false to carry on.
338  */
339 bool
340 Graph::run_one()
341 {
342         GraphNode* to_run;
343
344         pthread_mutex_lock (&_trigger_mutex);
345         if (_trigger_queue.size()) {
346                 to_run = _trigger_queue.back();
347                 _trigger_queue.pop_back();
348         } else {
349                 to_run = 0;
350         }
351
352         /* the number of threads that are asleep */
353         int et = _execution_tokens;
354         /* the number of nodes that need to be run */
355         int ts = _trigger_queue.size();
356
357         /* hence how many threads to wake up */
358         int wakeup = min (et, ts);
359         /* update the number of threads that will still be sleeping */
360         _execution_tokens -= wakeup;
361
362         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 signals %2\n", pthread_name(), wakeup));
363
364         for (int i = 0; i < wakeup; i++) {
365                 _execution_sem.signal ();
366         }
367
368         while (to_run == 0) {
369                 _execution_tokens += 1;
370                 pthread_mutex_unlock (&_trigger_mutex);
371                 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 goes to sleep\n", pthread_name()));
372                 _execution_sem.wait ();
373                 if (_quit_threads) {
374                         return true;
375                 }
376                 DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 is awake\n", pthread_name()));
377                 pthread_mutex_lock (&_trigger_mutex);
378                 if (_trigger_queue.size()) {
379                         to_run = _trigger_queue.back();
380                         _trigger_queue.pop_back();
381                 }
382         }
383         pthread_mutex_unlock (&_trigger_mutex);
384
385         to_run->process();
386         to_run->finish (_current_chain);
387
388         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 has finished run_one()\n", pthread_name()));
389
390         return false;
391 }
392
393 void
394 Graph::helper_thread()
395 {
396         suspend_rt_malloc_checks ();
397         ProcessThread* pt = new ProcessThread ();
398         resume_rt_malloc_checks ();
399
400         pt->get_buffers();
401
402         while(1) {
403                 if (run_one()) {
404                         break;
405                 }
406         }
407
408         pt->drop_buffers();
409 }
410
411 /** Here's the main graph thread */
412 void
413 Graph::main_thread()
414 {
415         suspend_rt_malloc_checks ();
416         ProcessThread* pt = new ProcessThread ();
417         resume_rt_malloc_checks ();
418
419         pt->get_buffers();
420
421   again:
422         _callback_start_sem.wait ();
423         
424         DEBUG_TRACE(DEBUG::ProcessThreads, "main thread is awake\n");
425
426         if (_quit_threads) {
427                 return;
428         }
429
430         prep ();
431
432         if (_graph_empty && !_quit_threads) {
433                 _callback_done_sem.signal ();
434                 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread sees graph done, goes back to sleep\n");
435                 goto again;
436         }
437
438         /* This loop will run forever */
439         while (1) {
440                 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread runs one graph node\n");
441                 if (run_one()) {
442                         break;
443                 }
444         }
445
446         pt->drop_buffers();
447 }
448
449 void
450 Graph::dump (int chain)
451 {
452 #ifndef NDEBUG
453         node_list_t::iterator ni;
454         node_set_t::iterator ai;
455
456         chain = _pending_chain;
457
458         DEBUG_TRACE (DEBUG::Graph, "--------------------------------------------Graph dump:\n");
459         for (ni=_nodes_rt[chain].begin(); ni!=_nodes_rt[chain].end(); ni++) {
460                 boost::shared_ptr<Route> rp = boost::dynamic_pointer_cast<Route>( *ni);
461                 DEBUG_TRACE (DEBUG::Graph, string_compose ("GraphNode: %1  refcount: %2\n", rp->name().c_str(), (*ni)->_init_refcount[chain]));
462                 for (ai=(*ni)->_activation_set[chain].begin(); ai!=(*ni)->_activation_set[chain].end(); ai++) {
463                         DEBUG_TRACE (DEBUG::Graph, string_compose ("  triggers: %1\n", boost::dynamic_pointer_cast<Route>(*ai)->name().c_str()));
464                 }
465         }
466
467         DEBUG_TRACE (DEBUG::Graph, "------------- trigger list:\n");
468         for (ni=_init_trigger_list[chain].begin(); ni!=_init_trigger_list[chain].end(); ni++) {
469                 DEBUG_TRACE (DEBUG::Graph, string_compose ("GraphNode: %1  refcount: %2\n", boost::dynamic_pointer_cast<Route>(*ni)->name().c_str(), (*ni)->_init_refcount[chain]));
470         }
471
472         DEBUG_TRACE (DEBUG::Graph, string_compose ("final activation refcount: %1\n", _init_finished_refcount[chain]));
473 #endif
474 }
475
476 int
477 Graph::silent_process_routes (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool& need_butler)
478 {
479         _process_nframes = nframes;
480         _process_start_frame = start_frame;
481         _process_end_frame = end_frame;
482
483         _process_silent = true;
484         _process_noroll = false;
485         _process_retval = 0;
486         _process_need_butler = false;
487
488         if (!_graph_empty) {
489                 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for silent process\n");
490                 _callback_start_sem.signal ();
491                 _callback_done_sem.wait ();
492         }
493
494         need_butler = _process_need_butler;
495
496         return _process_retval;
497 }
498
499 int
500 Graph::process_routes (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
501 {
502         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("graph execution from %1 to %2 = %3\n", start_frame, end_frame, nframes));
503
504         _process_nframes = nframes;
505         _process_start_frame = start_frame;
506         _process_end_frame = end_frame;
507         _process_declick = declick;
508
509         _process_silent = false;
510         _process_noroll = false;
511         _process_retval = 0;
512         _process_need_butler = false;
513
514         DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for non-silent process\n");
515         _callback_start_sem.signal ();
516         _callback_done_sem.wait ();
517
518         DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
519
520         need_butler = _process_need_butler;
521
522         return _process_retval;
523 }
524
525 int
526 Graph::routes_no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame,
527                        bool non_rt_pending, int declick)
528 {
529         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("no-roll graph execution from %1 to %2 = %3\n", start_frame, end_frame, nframes));
530
531         _process_nframes = nframes;
532         _process_start_frame = start_frame;
533         _process_end_frame = end_frame;
534         _process_declick = declick;
535         _process_non_rt_pending = non_rt_pending;
536
537         _process_silent = false;
538         _process_noroll = true;
539         _process_retval = 0;
540         _process_need_butler = false;
541
542         DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for no-roll process\n");
543         _callback_start_sem.signal ();
544         _callback_done_sem.wait ();
545
546         return _process_retval;
547 }
548 void
549 Graph::process_one_route (Route* route)
550 {
551         bool need_butler = false;
552         int retval;
553
554         assert (route);
555
556         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 runs route %2\n", pthread_name(), route->name()));
557
558         if (_process_silent) {
559                 retval = route->silent_roll (_process_nframes, _process_start_frame, _process_end_frame, need_butler);
560         } else if (_process_noroll) {
561                 route->set_pending_declick (_process_declick);
562                 retval = route->no_roll (_process_nframes, _process_start_frame, _process_end_frame, _process_non_rt_pending);
563         } else {
564                 route->set_pending_declick (_process_declick);
565                 retval = route->roll (_process_nframes, _process_start_frame, _process_end_frame, _process_declick, need_butler);
566         }
567
568         if (retval) {
569                 _process_retval = retval;
570         }
571
572         if (need_butler) {
573                 _process_need_butler = true;
574         }
575 }
576
577 bool
578 Graph::in_process_thread () const
579 {
580         return AudioEngine::instance()->in_process_thread ();
581 }