bd8bd8d08b0e127f75c36ef90b81018594873b75
[ardour.git] / libs / ardour / session_process.cc
1 /*
2  * Copyright (C) 1999-2019 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2006-2007 Jesse Chappell <jesse@essej.net>
4  * Copyright (C) 2006-2014 David Robillard <d@drobilla.net>
5  * Copyright (C) 2007-2012 Carl Hetherington <carl@carlh.net>
6  * Copyright (C) 2008-2009 Hans Baier <hansfbaier@googlemail.com>
7  * Copyright (C) 2012-2019 Robin Gareus <robin@gareus.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 #include <cmath>
25 #include <cerrno>
26 #include <algorithm>
27 #include <unistd.h>
28
29 #include <boost/algorithm/string/erase.hpp>
30
31 #include "pbd/i18n.h"
32 #include "pbd/error.h"
33 #include "pbd/enumwriter.h"
34
35 #include <glibmm/threads.h>
36
37 #include "ardour/audioengine.h"
38 #include "ardour/auditioner.h"
39 #include "ardour/butler.h"
40 #include "ardour/cycle_timer.h"
41 #include "ardour/debug.h"
42 #include "ardour/disk_reader.h"
43 #include "ardour/graph.h"
44 #include "ardour/port.h"
45 #include "ardour/process_thread.h"
46 #include "ardour/scene_changer.h"
47 #include "ardour/session.h"
48 #include "ardour/transport_fsm.h"
49 #include "ardour/transport_master.h"
50 #include "ardour/transport_master_manager.h"
51 #include "ardour/ticker.h"
52 #include "ardour/types.h"
53 #include "ardour/vca.h"
54 #include "ardour/vca_manager.h"
55
56 #include "midi++/mmc.h"
57
58 using namespace ARDOUR;
59 using namespace PBD;
60 using namespace std;
61
62 #define TFSM_EVENT(evtype) { _transport_fsm->enqueue (new TransportFSM::Event (evtype)); }
63 #define TFSM_STOP(abort,clear) { _transport_fsm->enqueue (new TransportFSM::Event (TransportFSM::StopTransport,abort,clear)); }
64 #define TFSM_LOCATE(target,roll,flush,loop,force) { _transport_fsm->enqueue (new TransportFSM::Event (TransportFSM::Locate,target,roll,flush,loop,force)); }
65
66
67 /** Called by the audio engine when there is work to be done with JACK.
68  * @param nframes Number of samples to process.
69  */
70
71 void
72 Session::process (pframes_t nframes)
73 {
74         samplepos_t transport_at_start = _transport_sample;
75
76         _silent = false;
77
78         if (processing_blocked()) {
79                 _silent = true;
80                 return;
81         }
82
83         if (non_realtime_work_pending()) {
84                 DEBUG_TRACE (DEBUG::Butler, string_compose ("non-realtime work pending: %1 (%2%3%4)\n", enum_2_string (post_transport_work()), std::hex, post_transport_work(), std::dec));
85                 if (!_butler->transport_work_requested ()) {
86                         DEBUG_TRACE (DEBUG::Butler, string_compose ("done, waiting? %1\n", _transport_fsm->waiting_for_butler()));
87                         butler_completed_transport_work ();
88                 } else {
89                         DEBUG_TRACE (DEBUG::Butler, "doesn't seem to have finished yet (from view of RT thread)\n");
90                 }
91         }
92
93         _engine.main_thread()->get_buffers ();
94
95         (this->*process_function) (nframes);
96
97         /* realtime-safe meter-position and processor-order changes
98          *
99          * ideally this would be done in
100          * Route::process_output_buffers() but various functions
101          * callig it hold a _processor_lock reader-lock
102          */
103         boost::shared_ptr<RouteList> r = routes.reader ();
104         bool one_or_more_routes_declicking = false;
105         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
106                 if ((*i)->apply_processor_changes_rt()) {
107                         _rt_emit_pending = true;
108                 }
109                 if ((*i)->declick_in_progress()) {
110                         one_or_more_routes_declicking = true;
111                 }
112         }
113
114         if (_rt_emit_pending) {
115                 if (!_rt_thread_active) {
116                         emit_route_signals ();
117                 }
118                 if (pthread_mutex_trylock (&_rt_emit_mutex) == 0) {
119                         pthread_cond_signal (&_rt_emit_cond);
120                         pthread_mutex_unlock (&_rt_emit_mutex);
121                         _rt_emit_pending = false;
122                 }
123         }
124
125         /* We are checking two things here:
126          *
127          * 1) whether or not all tracks have finished a declick out.
128          * 2) is the transport FSM waiting to be told this
129          */
130
131         if (!one_or_more_routes_declicking && declick_in_progress()) {
132                 /* end of the declick has been reached by all routes */
133                 TFSM_EVENT (TransportFSM::DeclickDone);
134         }
135
136         _engine.main_thread()->drop_buffers ();
137
138         /* deliver MIDI clock. Note that we need to use the transport sample
139          * position at the start of process(), not the value at the end of
140          * it. We may already have ticked() because of a transport state
141          * change, for example.
142          */
143
144         try {
145                 if (!_silent && !_engine.freewheeling() && Config->get_send_midi_clock() && (transport_speed() == 1.0f || transport_speed() == 0.0f) && midi_clock->has_midi_port()) {
146                         midi_clock->tick (transport_at_start, nframes);
147                 }
148
149                 _scene_changer->run (transport_at_start, transport_at_start + nframes);
150
151         } catch (...) {
152                 /* don't bother with a message */
153         }
154
155         SendFeedback (); /* EMIT SIGNAL */
156 }
157
158 int
159 Session::fail_roll (pframes_t nframes)
160 {
161         return no_roll (nframes);
162 }
163
164 int
165 Session::no_roll (pframes_t nframes)
166 {
167         PT_TIMING_CHECK (4);
168
169         samplepos_t end_sample = _transport_sample + floor (nframes * _transport_speed);
170         int ret = 0;
171         boost::shared_ptr<RouteList> r = routes.reader ();
172
173         if (_click_io) {
174                 _click_io->silence (nframes);
175         }
176
177         ltc_tx_send_time_code_for_cycle (_transport_sample, end_sample, _target_transport_speed, _transport_speed, nframes);
178
179         VCAList v = _vca_manager->vcas ();
180         for (VCAList::const_iterator i = v.begin(); i != v.end(); ++i) {
181                 (*i)->automation_run (_transport_sample, nframes);
182         }
183
184         _global_locate_pending = locate_pending ();
185
186         if (_process_graph) {
187                 DEBUG_TRACE(DEBUG::ProcessThreads,"calling graph/no-roll\n");
188                 _process_graph->routes_no_roll( nframes, _transport_sample, end_sample, non_realtime_work_pending());
189         } else {
190                 PT_TIMING_CHECK (10);
191                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
192
193                         if ((*i)->is_auditioner()) {
194                                 continue;
195                         }
196
197                         if ((*i)->no_roll (nframes, _transport_sample, end_sample, non_realtime_work_pending())) {
198                                 error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
199                                 ret = -1;
200                                 break;
201                         }
202                 }
203                 PT_TIMING_CHECK (11);
204         }
205
206         PT_TIMING_CHECK (5);
207         return ret;
208 }
209
210 /** @param need_butler to be set to true by this method if it needs the butler,
211  *  otherwise it must be left alone.
212  */
213 int
214 Session::process_routes (pframes_t nframes, bool& need_butler)
215 {
216         boost::shared_ptr<RouteList> r = routes.reader ();
217
218         const samplepos_t start_sample = _transport_sample;
219         const samplepos_t end_sample = _transport_sample + floor (nframes * _transport_speed);
220
221         VCAList v = _vca_manager->vcas ();
222         for (VCAList::const_iterator i = v.begin(); i != v.end(); ++i) {
223                 (*i)->automation_run (start_sample, nframes);
224         }
225
226         _global_locate_pending = locate_pending();
227
228         if (_process_graph) {
229                 DEBUG_TRACE(DEBUG::ProcessThreads,"calling graph/process-routes\n");
230                 if (_process_graph->process_routes (nframes, start_sample, end_sample, need_butler) < 0) {
231                         stop_transport ();
232                         return -1;
233                 }
234         } else {
235
236                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
237
238                         int ret;
239
240                         if ((*i)->is_auditioner()) {
241                                 continue;
242                         }
243
244                         bool b = false;
245
246                         if ((ret = (*i)->roll (nframes, start_sample, end_sample, b)) < 0) {
247                                 TFSM_STOP (false, false);
248                                 return -1;
249                         }
250
251                         if (b) {
252                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 rolled and needs butler\n", (*i)->name()));
253                                 need_butler = true;
254                         }
255                 }
256         }
257
258         return 0;
259 }
260
261 void
262 Session::get_track_statistics ()
263 {
264         float pworst = 1.0f;
265         float cworst = 1.0f;
266
267         boost::shared_ptr<RouteList> rl = routes.reader();
268         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
269
270                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
271
272                 if (!tr || tr->is_private_route()) {
273                         continue;
274                 }
275
276                 pworst = min (pworst, tr->playback_buffer_load());
277                 cworst = min (cworst, tr->capture_buffer_load());
278         }
279
280         g_atomic_int_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
281         g_atomic_int_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
282
283         if (actively_recording()) {
284                 set_dirty();
285         }
286 }
287
288 bool
289 Session::compute_audible_delta (samplepos_t& pos_and_delta) const
290 {
291         if (_transport_speed == 0.0 || _count_in_samples > 0 || _remaining_latency_preroll > 0) {
292                 /* cannot compute audible delta, because the session is
293                    generating silence that does not correspond to the timeline,
294                    but is instead filling playback buffers to manage latency
295                    alignment.
296                 */
297                 DEBUG_TRACE (DEBUG::Slave, string_compose ("still adjusting for latency (%1) and/or count-in (%2) or stopped %1\n", _remaining_latency_preroll, _count_in_samples, _transport_speed));
298                 return false;
299         }
300
301         pos_and_delta -= _transport_sample;
302         return true;
303 }
304
305 /** Process callback used when the auditioner is not active */
306 void
307 Session::process_with_events (pframes_t nframes)
308 {
309         PT_TIMING_CHECK (3);
310
311         SessionEvent*  ev;
312         pframes_t      this_nframes;
313         samplepos_t     end_sample;
314         bool           session_needs_butler = false;
315         samplecnt_t     samples_moved;
316
317         /* make sure the auditioner is silent */
318
319         if (auditioner) {
320                 auditioner->silence (nframes);
321         }
322
323         /* handle any pending events */
324
325         while (pending_events.read (&ev, 1) == 1) {
326                 merge_event (ev);
327         }
328
329         /* if we are not in the middle of a state change,
330            and there are immediate events queued up,
331            process them.
332         */
333
334         while (!non_realtime_work_pending() && !immediate_events.empty()) {
335                 SessionEvent *ev = immediate_events.front ();
336                 immediate_events.pop_front ();
337                 process_event (ev);
338         }
339         /* only count-in when going to roll at speed 1.0 */
340         if (_transport_speed != 1.0 && _count_in_samples > 0) {
341                 _count_in_samples = 0;
342         }
343         if (_transport_speed == 0.0) {
344                 _remaining_latency_preroll = 0;
345         }
346
347         assert (_count_in_samples == 0 || _remaining_latency_preroll == 0 || _count_in_samples == _remaining_latency_preroll);
348
349         // DEBUG_TRACE (DEBUG::Transport, string_compose ("Running count in/latency preroll of %1 & %2\n", _count_in_samples, _remaining_latency_preroll));
350
351         while (_count_in_samples > 0 || _remaining_latency_preroll > 0) {
352                 samplecnt_t ns;
353
354                 if (_remaining_latency_preroll > 0) {
355                         ns = std::min ((samplecnt_t)nframes, _remaining_latency_preroll);
356                 } else {
357                         ns = std::min ((samplecnt_t)nframes, _count_in_samples);
358                 }
359
360                 boost::shared_ptr<RouteList> r = routes.reader ();
361                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
362                         samplecnt_t route_offset = (*i)->playback_latency ();
363                         if (_remaining_latency_preroll > route_offset + ns) {
364                                 /* route will no-roll for complete pre-roll cycle */
365                                 continue;
366                         }
367                         if (_remaining_latency_preroll > route_offset) {
368                                 /* route may need partial no-roll and partial roll from
369                                 * (_transport_sample - _remaining_latency_preroll) ..  +ns.
370                                 * shorten and split the cycle.
371                                 */
372                                 ns = std::min (ns, (_remaining_latency_preroll - route_offset));
373                         }
374                 }
375
376                 if (_count_in_samples > 0) {
377                         run_click (_transport_sample - _count_in_samples, ns);
378                         assert (_count_in_samples >= ns);
379                         _count_in_samples -= ns;
380                 }
381
382                 if (_remaining_latency_preroll > 0) {
383                         if (_count_in_samples == 0) {
384                                 click (_transport_sample - _remaining_latency_preroll, ns);
385                         }
386                         if (process_routes (ns, session_needs_butler)) {
387                                 fail_roll (ns);
388                         }
389                 } else {
390                         no_roll (ns);
391                 }
392
393                 if (_remaining_latency_preroll > 0) {
394                         assert (_remaining_latency_preroll >= ns);
395                         _remaining_latency_preroll -= ns;
396                 }
397
398                 nframes -= ns;
399
400                 /* process events.. */
401                 if (!events.empty() && next_event != events.end()) {
402                         SessionEvent* this_event = *next_event;
403                         Events::iterator the_next_one = next_event;
404                         ++the_next_one;
405
406                         while (this_event && this_event->action_sample == _transport_sample) {
407                                 process_event (this_event);
408                                 if (the_next_one == events.end()) {
409                                         this_event = 0;
410                                 } else {
411                                         this_event = *the_next_one;
412                                         ++the_next_one;
413                                 }
414                         }
415                         set_next_event ();
416                 }
417
418                 if (nframes == 0) {
419                         return;
420                 } else {
421                         _engine.split_cycle (ns);
422                 }
423         }
424
425         /* Decide on what to do with quarter-frame MTC during this cycle */
426
427         bool const was_sending_qf_mtc = _send_qf_mtc;
428         double const tolerance = Config->get_mtc_qf_speed_tolerance() / 100.0;
429
430         if (_transport_speed != 0) {
431                 _send_qf_mtc = (
432                         Config->get_send_mtc () &&
433                         _transport_speed >= (1 - tolerance) &&
434                         _transport_speed <= (1 + tolerance)
435                         );
436
437                 if (_send_qf_mtc && !was_sending_qf_mtc) {
438                         /* we will re-start quarter-frame MTC this cycle, so send a full update to set things up */
439                         _send_timecode_update = true;
440                 }
441
442                 if (Config->get_send_mtc() && !_send_qf_mtc && _pframes_since_last_mtc > (sample_rate () / 4)) {
443                         /* we're sending MTC, but we're not sending QF MTC at the moment, and it's been
444                            a quarter of a second since we sent anything at all, so send a full MTC update
445                            this cycle.
446                         */
447                         _send_timecode_update = true;
448                 }
449
450                 _pframes_since_last_mtc += nframes;
451         }
452
453         /* Events caused a transport change (or we re-started sending
454          * MTC), so send an MTC Full Frame (Timecode) message.  This
455          * is sent whether rolling or not, to give slaves an idea of
456          * ardour time on locates (and allow slow slaves to position
457          * and prepare for rolling)
458          */
459         if (_send_timecode_update) {
460                 send_full_time_code (_transport_sample, nframes);
461         }
462
463         if (!process_can_proceed()) {
464                 _silent = true;
465                 return;
466         }
467
468         if (events.empty() || next_event == events.end()) {
469                 try_run_lua (nframes); // also during export ?? ->move to process_without_events()
470                 /* lua scripts may inject events */
471                 while (_n_lua_scripts > 0 && pending_events.read (&ev, 1) == 1) {
472                         merge_event (ev);
473                 }
474                 if (events.empty() || next_event == events.end()) {
475                         process_without_events (nframes);
476                         return;
477                 }
478         }
479
480         assert (_transport_speed == 0 || _transport_speed == 1.0 || _transport_speed == -1.0);
481
482         samples_moved = (samplecnt_t) nframes * _transport_speed;
483         // DEBUG_TRACE (DEBUG::Transport, string_compose ("plan to move transport by %1 (%2 @ %3)\n", samples_moved, nframes, _transport_speed));
484
485         end_sample = _transport_sample + samples_moved;
486
487         {
488                 SessionEvent* this_event;
489                 Events::iterator the_next_one;
490
491                 if (!process_can_proceed()) {
492                         _silent = true;
493                         return;
494                 }
495
496                 if (!_exporting && config.get_external_sync()) {
497                         if (!follow_transport_master (nframes)) {
498                                 ltc_tx_send_time_code_for_cycle (_transport_sample, end_sample, _target_transport_speed, _transport_speed, nframes);
499                                 return;
500                         }
501                 }
502
503                 if (_transport_speed == 0) {
504                         no_roll (nframes);
505                         return;
506                 }
507
508
509                 samplepos_t stop_limit = compute_stop_limit ();
510
511                 if (maybe_stop (stop_limit)) {
512                         if (!_exporting && !timecode_transmission_suspended()) {
513                                 send_midi_time_code_for_cycle (_transport_sample, end_sample, nframes);
514                         }
515                         ltc_tx_send_time_code_for_cycle (_transport_sample, end_sample, _target_transport_speed, _transport_speed, nframes);
516
517                         no_roll (nframes);
518                         return;
519                 }
520
521                 this_event = *next_event;
522                 the_next_one = next_event;
523                 ++the_next_one;
524
525                 /* yes folks, here it is, the actual loop where we really truly
526                    process some audio
527                 */
528
529                 while (nframes) {
530
531                         this_nframes = nframes; /* real (jack) time relative */
532                         samples_moved = (samplecnt_t) floor (_transport_speed * nframes); /* transport relative */
533                         // DEBUG_TRACE (DEBUG::Transport, string_compose ("sub-loop plan to move transport by %1 (%2 @ %3)\n", samples_moved, nframes, _transport_speed));
534
535                         /* running an event, position transport precisely to its time */
536                         if (this_event && this_event->action_sample <= end_sample && this_event->action_sample >= _transport_sample) {
537                                 /* this isn't quite right for reverse play */
538                                 samples_moved = (samplecnt_t) (this_event->action_sample - _transport_sample);
539                                 // DEBUG_TRACE (DEBUG::Transport, string_compose ("sub-loop2 (for %4)plan to move transport by %1 (%2 @ %3)\n", samples_moved, nframes, _transport_speed, enum_2_string (this_event->type)));
540                                 this_nframes = abs (floor(samples_moved / _transport_speed));
541                         }
542
543                         try_run_lua (this_nframes);
544
545                         if (this_nframes) {
546
547                                 if (!_exporting && !timecode_transmission_suspended()) {
548                                         send_midi_time_code_for_cycle (_transport_sample, _transport_sample + samples_moved, this_nframes);
549                                 }
550
551                                 ltc_tx_send_time_code_for_cycle (_transport_sample,  _transport_sample + samples_moved, _target_transport_speed, _transport_speed, this_nframes);
552
553                                 click (_transport_sample, this_nframes);
554
555                                 if (process_routes (this_nframes, session_needs_butler)) {
556                                         fail_roll (nframes);
557                                         return;
558                                 }
559
560                                 get_track_statistics ();
561
562                                 nframes -= this_nframes;
563
564                                 if (samples_moved < 0) {
565                                         decrement_transport_position (-samples_moved);
566                                 } else if (samples_moved) {
567                                         increment_transport_position (samples_moved);
568                                 } else {
569                                         DEBUG_TRACE (DEBUG::Transport, "no transport motion\n");
570                                 }
571
572                                 maybe_stop (stop_limit);
573                         }
574
575                         if (nframes > 0) {
576                                 _engine.split_cycle (this_nframes);
577                         }
578
579                         /* now handle this event and all others scheduled for the same time */
580
581                         while (this_event && this_event->action_sample == _transport_sample) {
582                                 process_event (this_event);
583
584                                 if (the_next_one == events.end()) {
585                                         this_event = 0;
586                                 } else {
587                                         this_event = *the_next_one;
588                                         ++the_next_one;
589                                 }
590                         }
591
592                         /* if an event left our state changing, do the right thing */
593
594                         if (nframes && non_realtime_work_pending()) {
595                                 no_roll (nframes);
596                                 break;
597                         }
598
599                         /* this is necessary to handle the case of seamless looping */
600                         end_sample = _transport_sample + floor (nframes * _transport_speed);
601                 }
602
603                 set_next_event ();
604
605         } /* implicit release of route lock */
606
607         if (session_needs_butler) {
608                 DEBUG_TRACE (DEBUG::Butler, "p-with-events: session needs butler, call it\n");
609                 _butler->summon ();
610         }
611 }
612
613 bool
614 Session::transport_locked () const
615 {
616         if (!locate_pending() && (!config.get_external_sync() || (transport_master()->ok() && transport_master()->locked()))) {
617                 return true;
618         }
619
620         return false;
621 }
622
623 void
624 Session::process_without_events (pframes_t nframes)
625 {
626         bool session_needs_butler = false;
627         samplecnt_t samples_moved;
628
629         if (!process_can_proceed()) {
630                 _silent = true;
631                 return;
632         }
633
634         if (!_exporting && config.get_external_sync()) {
635                 if (!follow_transport_master (nframes)) {
636                         ltc_tx_send_time_code_for_cycle (_transport_sample, _transport_sample, 0, 0 , nframes);
637                         return;
638                 }
639         }
640
641         assert (_transport_speed == 0 || _transport_speed == 1.0 || _transport_speed == -1.0);
642
643         if (_transport_speed == 0) {
644                 no_roll (nframes);
645                 return;
646         } else {
647                 samples_moved = (samplecnt_t) nframes * _transport_speed;
648         }
649
650         if (!_exporting && !timecode_transmission_suspended()) {
651                 send_midi_time_code_for_cycle (_transport_sample, _transport_sample + samples_moved, nframes);
652         }
653
654         ltc_tx_send_time_code_for_cycle (_transport_sample, _transport_sample + samples_moved, _target_transport_speed, _transport_speed, nframes);
655
656         samplepos_t const stop_limit = compute_stop_limit ();
657
658         if (maybe_stop (stop_limit)) {
659                 no_roll (nframes);
660                 return;
661         }
662
663         if (maybe_sync_start (nframes)) {
664                 return;
665         }
666
667         click (_transport_sample, nframes);
668
669         if (process_routes (nframes, session_needs_butler)) {
670                 fail_roll (nframes);
671                 return;
672         }
673
674         get_track_statistics ();
675
676         if (samples_moved < 0) {
677                 decrement_transport_position (-samples_moved);
678                 //DEBUG_TRACE (DEBUG::Transport, string_compose ("DEcrement transport by %1 to %2\n", samples_moved, _transport_sample));
679         } else if (samples_moved) {
680                 increment_transport_position (samples_moved);
681                 //DEBUG_TRACE (DEBUG::Transport, string_compose ("INcrement transport by %1 to %2\n", samples_moved, _transport_sample));
682         } else {
683                 DEBUG_TRACE (DEBUG::Transport, "no transport motion\n");
684         }
685
686         maybe_stop (stop_limit);
687
688         if (session_needs_butler) {
689                 DEBUG_TRACE (DEBUG::Butler, "p-without-events: session needs butler, call it\n");
690                 _butler->summon ();
691         }
692 }
693
694 /** Process callback used when the auditioner is active.
695  * @param nframes number of samples to process.
696  */
697 void
698 Session::process_audition (pframes_t nframes)
699 {
700         SessionEvent* ev;
701         boost::shared_ptr<RouteList> r = routes.reader ();
702
703         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
704                 if (!(*i)->is_auditioner()) {
705                         (*i)->silence (nframes);
706                 }
707         }
708
709         /* run the auditioner, and if it says we need butler service, ask for it */
710
711         if (auditioner->play_audition (nframes) > 0) {
712                 DEBUG_TRACE (DEBUG::Butler, "auditioner needs butler, call it\n");
713                 _butler->summon ();
714         }
715
716         /* if using a monitor section, run it because otherwise we don't hear anything */
717
718         if (_monitor_out && auditioner->needs_monitor()) {
719                 _monitor_out->monitor_run (_transport_sample, _transport_sample + nframes, nframes);
720         }
721
722         /* handle pending events */
723
724         while (pending_events.read (&ev, 1) == 1) {
725                 merge_event (ev);
726         }
727
728         /* if we are not in the middle of a state change,
729            and there are immediate events queued up,
730            process them.
731         */
732
733         while (!non_realtime_work_pending() && !immediate_events.empty()) {
734                 SessionEvent *ev = immediate_events.front ();
735                 immediate_events.pop_front ();
736                 process_event (ev);
737         }
738
739         if (!auditioner->auditioning()) {
740                 /* auditioner no longer active, so go back to the normal process callback */
741                 process_function = &Session::process_with_events;
742         }
743 }
744
745 bool
746 Session::maybe_sync_start (pframes_t & nframes)
747 {
748         pframes_t sync_offset;
749
750         if (!waiting_for_sync_offset) {
751                 return false;
752         }
753
754         if (_engine.get_sync_offset (sync_offset) && sync_offset < nframes) {
755
756                 /* generate silence up to the sync point, then
757                    adjust nframes + offset to reflect whatever
758                    is left to do.
759                 */
760
761                 no_roll (sync_offset);
762                 nframes -= sync_offset;
763                 Port::increment_global_port_buffer_offset (sync_offset);
764                 waiting_for_sync_offset = false;
765
766                 if (nframes == 0) {
767                         return true; // done, nothing left to process
768                 }
769
770         } else {
771
772                 /* sync offset point is not within this process()
773                    cycle, so just generate silence. and don't bother
774                    with any fancy stuff here, just the minimal silence.
775                 */
776
777                 _silent = true;
778
779                 if (Config->get_locate_while_waiting_for_sync()) {
780                         DEBUG_TRACE (DEBUG::Transport, "micro-locate while waiting for sync\n");
781                         if (micro_locate (nframes)) {
782                                 /* XXX ERROR !!! XXX */
783                         }
784                 }
785
786                 return true; // done, nothing left to process
787         }
788
789         return false;
790 }
791
792 void
793 Session::queue_event (SessionEvent* ev)
794 {
795         if (deletion_in_progress ()) {
796                 return;
797         } else if (loading ()) {
798                 merge_event (ev);
799         } else {
800                 Glib::Threads::Mutex::Lock lm (rb_write_lock);
801                 pending_events.write (&ev, 1);
802         }
803 }
804
805 void
806 Session::set_next_event ()
807 {
808         if (events.empty()) {
809                 next_event = events.end();
810                 return;
811         }
812
813         if (next_event == events.end()) {
814                 next_event = events.begin();
815         }
816
817         if ((*next_event)->action_sample > _transport_sample) {
818                 next_event = events.begin();
819         }
820
821         for (; next_event != events.end(); ++next_event) {
822                 if ((*next_event)->action_sample >= _transport_sample) {
823                         break;
824                 }
825         }
826 }
827
828 void
829 Session::process_event (SessionEvent* ev)
830 {
831         bool remove = true;
832         bool del = true;
833
834         /* if we're in the middle of a state change (i.e. waiting
835            for the butler thread to complete the non-realtime
836            part of the change), we'll just have to queue this
837            event for a time when the change is complete.
838         */
839
840         if (non_realtime_work_pending()) {
841
842                 /* except locates, which we have the capability to handle */
843
844                 if (ev->type != SessionEvent::Locate) {
845                         immediate_events.insert (immediate_events.end(), ev);
846                         _remove_event (ev);
847                         return;
848                 }
849         }
850
851         DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Processing event: %1 @ %2\n", enum_2_string (ev->type), _transport_sample));
852
853         switch (ev->type) {
854         case SessionEvent::SetLoop:
855                 set_play_loop (ev->yes_or_no, true);
856                 break;
857
858         case SessionEvent::AutoLoop:
859                 if (play_loop) {
860                         /* roll after locate, do not flush, set "for loop end" true
861                         */
862                         TFSM_LOCATE (ev->target_sample, true, false, true, false);
863                 }
864                 remove = false;
865                 del = false;
866                 break;
867
868         case SessionEvent::Locate:
869                 /* args: do not roll after locate, clear state, not for loop, force */
870                 TFSM_LOCATE (ev->target_sample, false, true, false, ev->yes_or_no);
871                 _send_timecode_update = true;
872                 break;
873
874         case SessionEvent::LocateRoll:
875                 /* args: roll after locate, clear state if not looping, not for loop, force */
876                 TFSM_LOCATE (ev->target_sample, true, !play_loop, false, ev->yes_or_no);
877                 _send_timecode_update = true;
878                 break;
879
880         case SessionEvent::Skip:
881                 if (Config->get_skip_playback()) {
882                         TFSM_LOCATE (ev->target_sample, true, true, false, false);
883                         _send_timecode_update = true;
884                 }
885                 remove = false;
886                 del = false;
887                 break;
888
889         case SessionEvent::LocateRollLocate:
890                 // locate is handled by ::request_roll_at_and_return()
891                 _requested_return_sample = ev->target_sample;
892                 TFSM_LOCATE (ev->target2_sample, true, true, false, false);
893                 _send_timecode_update = true;
894                 break;
895
896
897         case SessionEvent::SetTransportSpeed:
898                 set_transport_speed (ev->speed, ev->target_sample, ev->yes_or_no, ev->second_yes_or_no, ev->third_yes_or_no);
899                 break;
900
901         case SessionEvent::SetTransportMaster:
902                 TransportMasterManager::instance().set_current (ev->transport_master);
903                 break;
904
905         case SessionEvent::PunchIn:
906                 // cerr << "PunchIN at " << transport_sample() << endl;
907                 if (config.get_punch_in() && record_status() == Enabled) {
908                         enable_record ();
909                 }
910                 remove = false;
911                 del = false;
912                 break;
913
914         case SessionEvent::PunchOut:
915                 // cerr << "PunchOUT at " << transport_sample() << endl;
916                 if (config.get_punch_out()) {
917                         step_back_from_record ();
918                 }
919                 remove = false;
920                 del = false;
921                 break;
922
923         case SessionEvent::RangeStop:
924                 TFSM_STOP (ev->yes_or_no, false);
925                 remove = false;
926                 del = false;
927                 break;
928
929         case SessionEvent::RangeLocate:
930                 /* args: roll after locate, do flush, not with loop */
931                 TFSM_LOCATE (ev->target_sample, true, true, false, false);
932                 remove = false;
933                 del = false;
934                 break;
935
936         case SessionEvent::Overwrite:
937                 overwrite_some_buffers (ev->track, ev->overwrite);
938                 break;
939
940         case SessionEvent::Audition:
941                 set_audition (ev->region);
942                 // drop reference to region
943                 ev->region.reset ();
944                 break;
945
946         case SessionEvent::SetPlayAudioRange:
947                 set_play_range (ev->audio_range, (ev->speed == 1.0f));
948                 break;
949
950         case SessionEvent::CancelPlayAudioRange:
951                 unset_play_range();
952                 break;
953
954         case SessionEvent::RealTimeOperation:
955                 process_rtop (ev);
956                 del = false; // other side of RT request needs to clean up
957                 break;
958
959         case SessionEvent::AdjustPlaybackBuffering:
960                 schedule_playback_buffering_adjustment ();
961                 break;
962
963         case SessionEvent::AdjustCaptureBuffering:
964                 schedule_capture_buffering_adjustment ();
965                 break;
966
967         case SessionEvent::SetTimecodeTransmission:
968                 g_atomic_int_set (&_suspend_timecode_transmission, ev->yes_or_no ? 0 : 1);
969                 break;
970
971         default:
972           fatal << string_compose(_("Programming error: illegal event type in process_event (%1)"), ev->type) << endmsg;
973                 abort(); /*NOTREACHED*/
974                 break;
975         };
976
977         if (remove) {
978                 del = del && !_remove_event (ev);
979         }
980
981         if (del) {
982                 delete ev;
983         }
984 }
985
986 samplepos_t
987 Session::compute_stop_limit () const
988 {
989         if (!Config->get_stop_at_session_end ()) {
990                 return max_samplepos;
991         }
992
993         if (config.get_external_sync()) {
994                 return max_samplepos;
995         }
996
997         bool const punching_in = (config.get_punch_in () && _locations->auto_punch_location());
998         bool const punching_out = (config.get_punch_out () && _locations->auto_punch_location());
999
1000         if (actively_recording ()) {
1001                 /* permanently recording */
1002                 return max_samplepos;
1003         } else if (punching_in && !punching_out) {
1004                 /* punching in but never out */
1005                 return max_samplepos;
1006         } else if (punching_in && punching_out && _locations->auto_punch_location()->end() > current_end_sample()) {
1007                 /* punching in and punching out after session end */
1008                 return max_samplepos;
1009         }
1010
1011         return current_end_sample ();
1012 }
1013
1014
1015
1016 /* dedicated thread for signal emission.
1017  *
1018  * while sending cross-thread signals from the process thread
1019  * is fine in general, PBD::Signal's use of boost::function and
1020  * boost:bind can produce a vast overhead which is not
1021  * acceptable for low latency.
1022  *
1023  * This works around the issue by moving the boost overhead
1024  * out of the RT thread. The overall load is probably higher but
1025  * the realtime thread remains unaffected.
1026  */
1027
1028 void
1029 Session::emit_route_signals ()
1030 {
1031         // TODO use RAII to allow using these signals in other places
1032         BatchUpdateStart(); /* EMIT SIGNAL */
1033         boost::shared_ptr<RouteList> r = routes.reader ();
1034         for (RouteList::const_iterator ci = r->begin(); ci != r->end(); ++ci) {
1035                 (*ci)->emit_pending_signals ();
1036         }
1037         BatchUpdateEnd(); /* EMIT SIGNAL */
1038 }
1039
1040 void
1041 Session::emit_thread_start ()
1042 {
1043         if (_rt_thread_active) {
1044                 return;
1045         }
1046         _rt_thread_active = true;
1047
1048         if (pthread_create (&_rt_emit_thread, NULL, emit_thread, this)) {
1049                 _rt_thread_active = false;
1050         }
1051 }
1052
1053 void
1054 Session::emit_thread_terminate ()
1055 {
1056         if (!_rt_thread_active) {
1057                 return;
1058         }
1059         _rt_thread_active = false;
1060
1061         if (pthread_mutex_lock (&_rt_emit_mutex) == 0) {
1062                 pthread_cond_signal (&_rt_emit_cond);
1063                 pthread_mutex_unlock (&_rt_emit_mutex);
1064         }
1065
1066         void *status;
1067         pthread_join (_rt_emit_thread, &status);
1068 }
1069
1070 void *
1071 Session::emit_thread (void *arg)
1072 {
1073         Session *s = static_cast<Session *>(arg);
1074         s->emit_thread_run ();
1075         pthread_exit (0);
1076         return 0;
1077 }
1078
1079 void
1080 Session::emit_thread_run ()
1081 {
1082         pthread_mutex_lock (&_rt_emit_mutex);
1083         while (_rt_thread_active) {
1084                 emit_route_signals();
1085                 pthread_cond_wait (&_rt_emit_cond, &_rt_emit_mutex);
1086         }
1087         pthread_mutex_unlock (&_rt_emit_mutex);
1088 }
1089
1090 bool
1091 Session::follow_transport_master (pframes_t nframes)
1092 {
1093         TransportMasterManager& tmm (TransportMasterManager::instance());
1094
1095         double master_speed;
1096         samplepos_t master_transport_sample;
1097         sampleoffset_t delta;
1098
1099         if (tmm.master_invalid_this_cycle()) {
1100                 DEBUG_TRACE (DEBUG::Slave, "session told not to use the transport master this cycle\n");
1101                 goto noroll;
1102         }
1103
1104         master_speed = tmm.get_current_speed_in_process_context();
1105         master_transport_sample = tmm.get_current_position_in_process_context ();
1106         delta = _transport_sample - master_transport_sample;
1107
1108         DEBUG_TRACE (DEBUG::Slave, string_compose ("session at %1, master at %2, delta: %3 res: %4 TFSM state %5\n", _transport_sample, master_transport_sample, delta, tmm.current()->resolution(), _transport_fsm->current_state()));
1109
1110         if (tmm.current()->type() == Engine) {
1111
1112                 /* JACK Transport. */
1113
1114                 if (master_speed == 0) {
1115
1116                         if (!actively_recording()) {
1117
1118                                 const samplecnt_t wlp = worst_latency_preroll_buffer_size_ceil ();
1119
1120                                 if (delta != wlp) {
1121
1122                                         /* if we're not aligned with the current JACK * time, then jump to it */
1123
1124                                         if (!locate_pending() && !declick_in_progress() && !tmm.current()->starting()) {
1125
1126                                                 const samplepos_t locate_target = master_transport_sample + wlp;
1127                                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("JACK transport: jump to master position %1 by locating to %2\n", master_transport_sample, locate_target));
1128                                                 /* for JACK transport always stop after the locate (2nd argument == false) */
1129                                                 TFSM_LOCATE (locate_target, false, true, false, false);
1130
1131                                         } else {
1132                                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("JACK Transport: locate already in process, sts = %1\n", master_transport_sample));
1133                                         }
1134                                 }
1135                         }
1136
1137                 } else {
1138
1139                         if (_transport_speed) {
1140                                 /* master is rolling, and we're rolling ... with JACK we should always be perfectly in sync, so ... WTF? */
1141                                 if (delta) {
1142                                         if (remaining_latency_preroll() && worst_latency_preroll()) {
1143                                                 /* our transport position is not moving because we're doing latency alignment. Nothing in particular to do */
1144                                         } else {
1145                                                 cerr << "\n\n\n IMPOSSIBLE! OUT OF SYNC WITH JACK TRANSPORT (rlp = " << remaining_latency_preroll() << " wlp " << worst_latency_preroll() << ")\n\n\n";
1146                                         }
1147                                 }
1148                         }
1149                 }
1150
1151         } else {
1152
1153                 /* This is a heuristic rather than a strictly provable rule. The idea
1154                  * is that if we're "far away" from the master, we should locate to its
1155                  * current position, and then varispeed to sync with it.
1156                  *
1157                  * On the other hand, if we're close to it, just varispeed.
1158                  */
1159
1160                 if (!actively_recording() && abs (delta) > (5 * current_block_size)) {
1161
1162                         DiskReader::inc_no_disk_output ();
1163
1164                         if (!locate_pending() && !declick_in_progress()) {
1165                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("request locate to master position %1\n", master_transport_sample));
1166                                 /* note that for non-JACK transport masters, we assume that the transport state (rolling,stopped) after the locate
1167                                  * remains unchanged (2nd argument, "roll-after-locate")
1168                                  */
1169                                 TFSM_LOCATE (master_transport_sample, master_speed != 0, true, false, false);
1170                         }
1171
1172                         return true;
1173                 }
1174         }
1175
1176         if (master_speed != 0.0) {
1177                 if (_transport_speed == 0.0f) {
1178                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave starts transport: %1 sample %2 tf %3\n", master_speed, master_transport_sample, _transport_sample));
1179                         TFSM_EVENT (TransportFSM::StartTransport);
1180                 }
1181
1182         } else if (!tmm.current()->starting()) { /* master stopped, not in "starting" state */
1183
1184                 if (_transport_speed != 0.0f) {
1185                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stops transport: %1 sample %2 tf %3\n", master_speed, master_transport_sample, _transport_sample));
1186                         TFSM_STOP (false, false);
1187                 }
1188         }
1189
1190         /* This is the second part of the "we're not synced yet" code. If we're
1191          * close, but not within the resolution of the master, silence disk
1192          * output but continue to varispeed to get in sync.
1193          */
1194
1195         if ((tmm.current()->type() != Engine) && !actively_recording() && abs (delta) > tmm.current()->resolution()) {
1196                 /* just varispeed to chase the master, and be silent till we're synced */
1197                 DiskReader::inc_no_disk_output ();
1198                 return true;
1199         }
1200
1201         /* speed is set, we're locked, and good to go */
1202         DiskReader::dec_no_disk_output ();
1203         return true;
1204
1205   noroll:
1206         /* don't move at all */
1207         DEBUG_TRACE (DEBUG::Slave, "no roll\n")
1208         no_roll (nframes);
1209         return false;
1210 }
1211
1212 void
1213 Session::reset_slave_state ()
1214 {
1215         DiskReader::dec_no_disk_output ();
1216 }