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