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