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