Fix initial sync to LTC with small buffersizes
[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 = 2; 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
276 again:
277         _callback_done_sem.signal ();
278
279         /* Block until the a process callback triggers us */
280         _callback_start_sem.wait();
281
282         if (!_threads_active) {
283                 return;
284         }
285
286         prep ();
287
288         if (_graph_empty && _threads_active) {
289                 goto again;
290         }
291
292         // returning will restart the cycle.
293         // starting with waking up the others.
294 }
295
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
298  *  acyclic.
299  */
300 void
301 Graph::rechain (boost::shared_ptr<RouteList> routelist, GraphEdges const & edges)
302 {
303         Glib::Threads::Mutex::Lock ls (_swap_mutex);
304
305         int chain = _setup_chain;
306         DEBUG_TRACE (DEBUG::Graph, string_compose ("============== setup %1\n", chain));
307
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.
310          */
311         _init_finished_refcount[chain] = 0;
312
313         /* This will become a list of nodes that are not fed by another node, ie
314          * those at the `input' end.
315          */
316         _init_trigger_list[chain].clear();
317
318         _nodes_rt[chain].clear();
319
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);
325         }
326
327         // now add refs for the connections.
328
329         for (node_list_t::iterator ni = _nodes_rt[chain].begin(); ni != _nodes_rt[chain].end(); ni++) {
330
331                 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*ni);
332
333                 /* The routes that are directly fed by r */
334                 set<GraphVertex> fed_from_r = edges.from (r);
335
336                 /* Hence whether r has an output */
337                 bool const has_output = !fed_from_r.empty ();
338
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);
342                 }
343
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);
346
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;
350                 }
351
352                 if (!has_input) {
353                         /* no input, so this node needs to be triggered initially to get things going */
354                         _init_trigger_list[chain].push_back (*ni);
355                 }
356
357                 if (!has_output) {
358                         /* no output, so this is one of the nodes that we can count off to decide
359                          * if we've finished
360                          */
361                         _init_finished_refcount[chain] += 1;
362                 }
363         }
364
365         _pending_chain = chain;
366         dump(chain);
367 }
368
369 /** Called by both the main thread and all helpers.
370  *  @return true to quit, false to carry on.
371  */
372 bool
373 Graph::run_one()
374 {
375         GraphNode* to_run;
376
377         pthread_mutex_lock (&_trigger_mutex);
378         if (_trigger_queue.size()) {
379                 to_run = _trigger_queue.back();
380                 _trigger_queue.pop_back();
381         } else {
382                 to_run = 0;
383         }
384
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();
389
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;
394
395         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 signals %2\n", pthread_name(), wakeup));
396
397         for (int i = 0; i < wakeup; i++) {
398                 _execution_sem.signal ();
399         }
400
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) {
407                         return true;
408                 }
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();
414                 }
415         }
416         pthread_mutex_unlock (&_trigger_mutex);
417
418         to_run->process();
419         to_run->finish (_current_chain);
420
421         DEBUG_TRACE(DEBUG::ProcessThreads, string_compose ("%1 has finished run_one()\n", pthread_name()));
422
423         return !_threads_active;
424 }
425
426 void
427 Graph::helper_thread()
428 {
429         suspend_rt_malloc_checks ();
430         ProcessThread* pt = new ProcessThread ();
431         resume_rt_malloc_checks ();
432
433         pt->get_buffers();
434
435         while(1) {
436                 if (run_one()) {
437                         break;
438                 }
439         }
440
441         pt->drop_buffers();
442         delete pt;
443 }
444
445 /** Here's the main graph thread */
446 void
447 Graph::main_thread()
448 {
449         suspend_rt_malloc_checks ();
450         ProcessThread* pt = new ProcessThread ();
451         resume_rt_malloc_checks ();
452
453         pt->get_buffers();
454
455 again:
456         _callback_start_sem.wait ();
457
458         DEBUG_TRACE(DEBUG::ProcessThreads, "main thread is awake\n");
459
460         if (!_threads_active) {
461                 pt->drop_buffers();
462                 delete (pt);
463                 return;
464         }
465
466         prep ();
467
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");
471                 goto again;
472         }
473
474         /* This loop will run forever */
475         while (1) {
476                 DEBUG_TRACE(DEBUG::ProcessThreads, "main thread runs one graph node\n");
477                 if (run_one()) {
478                         break;
479                 }
480         }
481
482         pt->drop_buffers();
483         delete (pt);
484 }
485
486 void
487 Graph::dump (int chain)
488 {
489 #ifndef NDEBUG
490         node_list_t::iterator ni;
491         node_set_t::iterator ai;
492
493         chain = _pending_chain;
494
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()));
501                 }
502         }
503
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]));
507         }
508
509         DEBUG_TRACE (DEBUG::Graph, string_compose ("final activation refcount: %1\n", _init_finished_refcount[chain]));
510 #endif
511 }
512
513 int
514 Graph::silent_process_routes (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool& need_butler)
515 {
516         if (!_threads_active) return 0;
517
518         _process_nframes = nframes;
519         _process_start_frame = start_frame;
520         _process_end_frame = end_frame;
521
522         _process_silent = true;
523         _process_noroll = false;
524         _process_retval = 0;
525         _process_need_butler = false;
526
527         if (!_graph_empty) {
528                 DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for silent process\n");
529                 _callback_start_sem.signal ();
530                 _callback_done_sem.wait ();
531         }
532
533         need_butler = _process_need_butler;
534
535         return _process_retval;
536 }
537
538 int
539 Graph::process_routes (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
540 {
541         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("graph execution from %1 to %2 = %3\n", start_frame, end_frame, nframes));
542
543         if (!_threads_active) return 0;
544
545         _process_nframes = nframes;
546         _process_start_frame = start_frame;
547         _process_end_frame = end_frame;
548         _process_declick = declick;
549
550         _process_silent = false;
551         _process_noroll = false;
552         _process_retval = 0;
553         _process_need_butler = false;
554
555         DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for non-silent process\n");
556         _callback_start_sem.signal ();
557         _callback_done_sem.wait ();
558
559         DEBUG_TRACE (DEBUG::ProcessThreads, "graph execution complete\n");
560
561         need_butler = _process_need_butler;
562
563         return _process_retval;
564 }
565
566 int
567 Graph::routes_no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame,
568                        bool non_rt_pending, int declick)
569 {
570         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("no-roll graph execution from %1 to %2 = %3\n", start_frame, end_frame, nframes));
571
572         if (!_threads_active) return 0;
573
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;
579
580         _process_silent = false;
581         _process_noroll = true;
582         _process_retval = 0;
583         _process_need_butler = false;
584
585         DEBUG_TRACE(DEBUG::ProcessThreads, "wake graph for no-roll process\n");
586         _callback_start_sem.signal ();
587         _callback_done_sem.wait ();
588
589         return _process_retval;
590 }
591 void
592 Graph::process_one_route (Route* route)
593 {
594         bool need_butler = false;
595         int retval;
596
597         assert (route);
598
599         DEBUG_TRACE (DEBUG::ProcessThreads, string_compose ("%1 runs route %2\n", pthread_name(), route->name()));
600
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);
606         } else {
607                 route->set_pending_declick (_process_declick);
608                 retval = route->roll (_process_nframes, _process_start_frame, _process_end_frame, _process_declick, need_butler);
609         }
610
611         if (retval) {
612                 _process_retval = retval;
613         }
614
615         if (need_butler) {
616                 _process_need_butler = true;
617         }
618 }
619
620 bool
621 Graph::in_process_thread () const
622 {
623         return AudioEngine::instance()->in_process_thread ();
624 }