globally change all use of "frame" to refer to audio into "sample".
[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 "pbd/i18n.h"
36
37 using namespace ARDOUR;
38 using namespace PBD;
39 using namespace std;
40
41 #ifdef DEBUG_RT_ALLOC
42 static Graph* graph = 0;
43
44 extern "C" {
45
46 int alloc_allowed ()
47 {
48         return !graph->in_process_thread ();
49 }
50
51 }
52 #endif
53
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)
60 {
61         pthread_mutex_init( &_trigger_mutex, NULL);
62
63         /* XXX: rather hacky `fix' to stop _trigger_queue.push_back() allocating
64          * memory in the RT thread.
65          */
66         _trigger_queue.reserve (8192);
67
68         _execution_tokens = 0;
69
70         _current_chain = 0;
71         _pending_chain = 0;
72         _setup_chain   = 1;
73         _graph_empty = true;
74
75
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));
79
80         reset_thread_list ();
81
82 #ifdef DEBUG_RT_ALLOC
83         graph = this;
84         pbd_alloc_allowed = &::alloc_allowed;
85 #endif
86 }
87
88 void
89 Graph::engine_stopped ()
90 {
91 #ifndef NDEBUG
92         cerr << "Graph::engine_stopped. n_thread: " << AudioEngine::instance()->process_thread_count() << endl;
93 #endif
94         if (AudioEngine::instance()->process_thread_count() != 0) {
95                 drop_threads ();
96         }
97 }
98
99 /** Set up threads for running the graph */
100 void
101 Graph::reset_thread_list ()
102 {
103         uint32_t num_threads = how_many_dsp_threads ();
104
105         /* For now, we shouldn't be using the graph code if we only have 1 DSP thread */
106         assert (num_threads > 1);
107
108         /* don't bother doing anything here if we already have the right
109          * number of threads.
110          */
111
112         if (AudioEngine::instance()->process_thread_count() == num_threads) {
113                 return;
114         }
115
116         Glib::Threads::Mutex::Lock lm (_session.engine().process_lock());
117
118         if (AudioEngine::instance()->process_thread_count() != 0) {
119                 drop_threads ();
120         }
121
122         _threads_active = true;
123
124         if (AudioEngine::instance()->create_process_thread (boost::bind (&Graph::main_thread, this)) != 0) {
125                 throw failed_constructor ();
126         }
127
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 ();
131                 }
132         }
133 }
134
135 void
136 Graph::session_going_away()
137 {
138         drop_threads ();
139
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();
146 }
147
148 void
149 Graph::drop_threads ()
150 {
151         Glib::Threads::Mutex::Lock ls (_swap_mutex);
152         _threads_active = false;
153
154         uint32_t thread_count = AudioEngine::instance()->process_thread_count ();
155
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);
160         }
161
162         pthread_mutex_lock (&_trigger_mutex);
163         _callback_start_sem.signal ();
164         pthread_mutex_unlock (&_trigger_mutex);
165
166         AudioEngine::instance()->join_process_threads ();
167
168         /* signal main process thread if it's waiting for an already terminated thread */
169         _callback_done_sem.signal ();
170         _execution_tokens = 0;
171
172         /* reset semaphores.
173          * This is somewhat ugly, yet if a thread is killed (e.g jackd terminates
174          * abnormally), some semaphores are still unlocked.
175          */
176 #ifndef NDEBUG
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;
181 #else
182         _execution_sem.reset ();
183         _callback_start_sem.reset ();
184         _callback_done_sem.reset ();
185 #endif
186 }
187
188 void
189 Graph::clear_other_chain ()
190 {
191         Glib::Threads::Mutex::Lock ls (_swap_mutex);
192
193         while (1) {
194                 if (_setup_chain != _pending_chain) {
195
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();
198                         }
199
200                         _nodes_rt[_setup_chain].clear ();
201                         _init_trigger_list[_setup_chain].clear ();
202                         break;
203                 }
204                 /* setup chain == pending chain - we have
205                  * to wait till this is no longer true.
206                  */
207                 _cleanup_cond.wait (_swap_mutex);
208         }
209 }
210
211 void
212 Graph::prep()
213 {
214         node_list_t::iterator i;
215         int chain;
216
217         if (_swap_mutex.trylock()) {
218                 // we got the swap mutex.
219                 if (_current_chain != _pending_chain)
220                 {
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 ();
225                 }
226                 _swap_mutex.unlock ();
227         }
228
229         chain = _current_chain;
230
231         _graph_empty = true;
232         for (i=_nodes_rt[chain].begin(); i!=_nodes_rt[chain].end(); i++) {
233                 (*i)->prep( chain);
234                 _graph_empty = false;
235         }
236         _finished_refcount = _init_finished_refcount[chain];
237
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 ());
243         }
244         pthread_mutex_unlock (&_trigger_mutex);
245 }
246
247 void
248 Graph::trigger (GraphNode* n)
249 {
250         pthread_mutex_lock (&_trigger_mutex);
251         _trigger_queue.push_back (n);
252         pthread_mutex_unlock (&_trigger_mutex);
253 }
254
255 /** Called when a node at the `output' end of the chain (ie one that has no-one to feed)
256  *  is finished.
257  */
258 void
259 Graph::dec_ref()
260 {
261         if (g_atomic_int_dec_and_test (const_cast<gint*> (&_finished_refcount))) {
262
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.
265                  */
266
267                 restart_cycle ();
268         }
269 }
270
271 void
272 Graph::restart_cycle()
273 {
274         // we are through. wakeup our caller.
275         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 cycle done.\n", pthread_name()));
276
277 again:
278         _callback_done_sem.signal ();
279
280         /* Block until the a process callback triggers us */
281         _callback_start_sem.wait();
282
283         if (!_threads_active) {
284                 return;
285         }
286
287         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 prepare new cycle.\n", pthread_name()));
288         prep ();
289
290         if (_graph_empty && _threads_active) {
291                 goto again;
292         }
293
294         // returning will restart the cycle.
295         // starting with waking up the others.
296 }
297
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
300  *  acyclic.
301  */
302 void
303 Graph::rechain (boost::shared_ptr<RouteList> routelist, GraphEdges const & edges)
304 {
305         Glib::Threads::Mutex::Lock ls (_swap_mutex);
306
307         int chain = _setup_chain;
308         DEBUG_TRACE (DEBUG::Graph, string_compose ("============== setup %1\n", chain));
309
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.
312          */
313         _init_finished_refcount[chain] = 0;
314
315         /* This will become a list of nodes that are not fed by another node, ie
316          * those at the `input' end.
317          */
318         _init_trigger_list[chain].clear();
319
320         _nodes_rt[chain].clear();
321
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);
327         }
328
329         // now add refs for the connections.
330
331         for (node_list_t::iterator ni = _nodes_rt[chain].begin(); ni != _nodes_rt[chain].end(); ni++) {
332
333                 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*ni);
334
335                 /* The routes that are directly fed by r */
336                 set<GraphVertex> fed_from_r = edges.from (r);
337
338                 /* Hence whether r has an output */
339                 bool const has_output = !fed_from_r.empty ();
340
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);
344                 }
345
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);
348
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;
352                 }
353
354                 if (!has_input) {
355                         /* no input, so this node needs to be triggered initially to get things going */
356                         _init_trigger_list[chain].push_back (*ni);
357                 }
358
359                 if (!has_output) {
360                         /* no output, so this is one of the nodes that we can count off to decide
361                          * if we've finished
362                          */
363                         _init_finished_refcount[chain] += 1;
364                 }
365         }
366
367         _pending_chain = chain;
368         dump(chain);
369 }
370
371 /** Called by both the main thread and all helpers.
372  *  @return true to quit, false to carry on.
373  */
374 bool
375 Graph::run_one()
376 {
377         GraphNode* to_run;
378
379         pthread_mutex_lock (&_trigger_mutex);
380         if (_trigger_queue.size()) {
381                 to_run = _trigger_queue.back();
382                 _trigger_queue.pop_back();
383         } else {
384                 to_run = 0;
385         }
386
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();
391
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;
396
397         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 signals %2\n", pthread_name(), wakeup));
398
399         for (int i = 0; i < wakeup; i++) {
400                 _execution_sem.signal ();
401         }
402
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) {
409                         return true;
410                 }
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();
416                 }
417         }
418         pthread_mutex_unlock (&_trigger_mutex);
419
420         to_run->process();
421         to_run->finish (_current_chain);
422
423         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 has finished run_one()\n", pthread_name()));
424
425         return !_threads_active;
426 }
427
428 void
429 Graph::helper_thread()
430 {
431         suspend_rt_malloc_checks ();
432         ProcessThread* pt = new ProcessThread ();
433         resume_rt_malloc_checks ();
434
435         pt->get_buffers();
436
437         while(1) {
438                 if (run_one()) {
439                         break;
440                 }
441         }
442
443         pt->drop_buffers();
444         delete pt;
445 }
446
447 /** Here's the main graph thread */
448 void
449 Graph::main_thread()
450 {
451         suspend_rt_malloc_checks ();
452         ProcessThread* pt = new ProcessThread ();
453         resume_rt_malloc_checks ();
454
455         pt->get_buffers();
456
457 again:
458         _callback_start_sem.wait ();
459
460         DEBUG_TRACE(DEBUG::ProcessThreads, "main thread is awake\n");
461
462         if (!_threads_active) {
463                 pt->drop_buffers();
464                 delete (pt);
465                 return;
466         }
467
468         prep ();
469
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");
473                 goto again;
474         }
475
476         /* This loop will run forever */
477         while (1) {
478                 DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("main thread (%1) runs one graph node\n", pthread_name ()));
479                 if (run_one()) {
480                         break;
481                 }
482         }
483
484         pt->drop_buffers();
485         delete (pt);
486 }
487
488 void
489 Graph::dump (int chain)
490 {
491 #ifndef NDEBUG
492         node_list_t::iterator ni;
493         node_set_t::iterator ai;
494
495         chain = _pending_chain;
496
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()));
503                 }
504         }
505
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]));
509         }
510
511         DEBUG_TRACE (DEBUG::Graph, string_compose ("final activation refcount: %1\n", _init_finished_refcount[chain]));
512 #endif
513 }
514
515 int
516 Graph::process_routes (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, int declick, bool& need_butler)
517 {
518         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("graph execution from %1 to %2 = %3\n", start_sample, end_sample, nframes));
519
520         if (!_threads_active) return 0;
521
522         _process_nframes = nframes;
523         _process_start_sample = start_sample;
524         _process_end_sample = end_sample;
525         _process_declick = declick;
526
527         _process_noroll = false;
528         _process_retval = 0;
529         _process_need_butler = false;
530
531         DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for non-silent process\n");
532         _callback_start_sem.signal ();
533         _callback_done_sem.wait ();
534         DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
535
536         need_butler = _process_need_butler;
537
538         return _process_retval;
539 }
540
541 int
542 Graph::routes_no_roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample,
543                        bool non_rt_pending, int declick)
544 {
545         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("no-roll graph execution from %1 to %2 = %3\n", start_sample, end_sample, nframes));
546
547         if (!_threads_active) return 0;
548
549         _process_nframes = nframes;
550         _process_start_sample = start_sample;
551         _process_end_sample = end_sample;
552         _process_declick = declick;
553         _process_non_rt_pending = non_rt_pending;
554
555         _process_noroll = true;
556         _process_retval = 0;
557         _process_need_butler = false;
558
559         DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for no-roll process\n");
560         _callback_start_sem.signal ();
561         _callback_done_sem.wait ();
562         DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
563
564         return _process_retval;
565 }
566 void
567 Graph::process_one_route (Route* route)
568 {
569         bool need_butler = false;
570         int retval;
571
572         assert (route);
573
574         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 runs route %2\n", pthread_name(), route->name()));
575
576         if (_process_noroll) {
577                 route->set_pending_declick (_process_declick);
578                 retval = route->no_roll (_process_nframes, _process_start_sample, _process_end_sample, _process_non_rt_pending);
579         } else {
580                 route->set_pending_declick (_process_declick);
581                 retval = route->roll (_process_nframes, _process_start_sample, _process_end_sample, _process_declick, need_butler);
582         }
583
584         if (retval) {
585                 _process_retval = retval;
586         }
587
588         if (need_butler) {
589                 _process_need_butler = true;
590         }
591 }
592
593 bool
594 Graph::in_process_thread () const
595 {
596         return AudioEngine::instance()->in_process_thread ();
597 }