0f697806eb6fe1b18d7dcd5246209228e12a9ee4
[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
27 #include <glibmm/thread.h>
28
29 #include "ardour/ardour.h"
30 #include "ardour/session.h"
31 #include "ardour/timestamps.h"
32 #include "ardour/audio_diskstream.h"
33 #include "ardour/audioengine.h"
34 #include "ardour/slave.h"
35 #include "ardour/auditioner.h"
36 #include "ardour/cycles.h"
37 #include "ardour/cycle_timer.h"
38
39 #include "midi++/manager.h"
40
41 #include "i18n.h"
42
43 using namespace ARDOUR;
44 using namespace PBD;
45 using namespace std;
46
47 /** Called by the audio engine when there is work to be done with JACK.
48  * @param nframes Number of frames to process.
49  */
50 void
51 Session::process (nframes_t nframes)
52 {
53         // This is no more the appropriate place to call cycle
54         // start. cycle_start needs to be called at the Route::roll()
55         // where the signals which we want to mixdown have been calculated.
56         //
57         MIDI::Manager::instance()->cycle_start(nframes);
58
59         _silent = false;
60
61         if (non_realtime_work_pending()) {
62                 if (!transport_work_requested ()) {
63                         post_transport ();
64                 } 
65         } 
66         
67         (this->*process_function) (nframes);
68         
69         // the ticker is for sending time information like MidiClock
70         nframes_t transport_frames = transport_frame();
71         BBT_Time  transport_bbt;
72         bbt_time(transport_frames, transport_bbt);
73         SMPTE::Time transport_smpte;
74         smpte_time(transport_frames, transport_smpte);
75         tick (transport_frames, transport_bbt, transport_smpte); /* EMIT SIGNAL */
76         
77         SendFeedback (); /* EMIT SIGNAL */
78         
79         MIDI::Manager::instance()->cycle_end();
80 }
81
82 void
83 Session::prepare_diskstreams ()
84 {
85         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
86         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
87                 (*i)->prepare ();
88         }
89 }
90
91 int
92 Session::no_roll (nframes_t nframes, nframes_t offset)
93 {
94         nframes_t end_frame = _transport_frame + nframes; // FIXME: varispeed + no_roll ??
95         int ret = 0;
96         bool declick = get_transport_declick_required();
97         boost::shared_ptr<RouteList> r = routes.reader ();
98
99         if (_click_io) {
100                 _click_io->silence (nframes, offset);
101         }
102
103         if (g_atomic_int_get (&processing_prohibited)) {
104                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
105                         (*i)->silence (nframes, offset);
106                 }
107                 return 0;
108         }
109
110         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
111                 
112                 if ((*i)->is_hidden()) {
113                         continue;
114                 }
115                 
116                 (*i)->set_pending_declick (declick);
117                 
118                 if ((*i)->no_roll (nframes, _transport_frame, end_frame, offset, non_realtime_work_pending(), 
119                                    actively_recording(), declick)) {
120                         error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
121                         ret = -1;
122                         break;
123                 }
124         }
125
126         return ret;
127 }
128
129 int
130 Session::process_routes (nframes_t nframes, nframes_t offset)
131 {
132         bool record_active;
133         int  declick = get_transport_declick_required();
134         bool rec_monitors = get_rec_monitors_input();
135         boost::shared_ptr<RouteList> r = routes.reader ();
136
137         if (transport_sub_state & StopPendingCapture) {
138                 /* force a declick out */
139                 declick = -1;
140         }
141
142         record_active = actively_recording(); // || (get_record_enabled() && get_punch_in());
143
144         const nframes_t start_frame = _transport_frame;
145         const nframes_t end_frame = _transport_frame + (nframes_t)floor(nframes * _transport_speed);
146
147         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
148
149                 int ret;
150
151                 if ((*i)->is_hidden()) {
152                         continue;
153                 }
154
155                 (*i)->set_pending_declick (declick);
156
157                 if ((ret = (*i)->roll (nframes, start_frame, end_frame, offset, declick, record_active, rec_monitors)) < 0) {
158
159                         /* we have to do this here. Route::roll() for an AudioTrack will have called AudioDiskstream::process(),
160                            and the DS will expect AudioDiskstream::commit() to be called. but we're aborting from that
161                            call path, so make sure we release any outstanding locks here before we return failure.
162                         */
163
164                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
165                         for (DiskstreamList::iterator ids = dsl->begin(); ids != dsl->end(); ++ids) {
166                                 (*ids)->recover ();
167                         }
168
169                         stop_transport ();
170                         return -1;
171                 } 
172         }
173
174         return 0;
175 }
176
177 int
178 Session::silent_process_routes (nframes_t nframes, nframes_t offset)
179 {
180         bool record_active = actively_recording();
181         int  declick = get_transport_declick_required();
182         bool rec_monitors = get_rec_monitors_input();
183         boost::shared_ptr<RouteList> r = routes.reader ();
184
185         if (transport_sub_state & StopPendingCapture) {
186                 /* force a declick out */
187                 declick = -1;
188         }
189         
190         const nframes_t start_frame = _transport_frame;
191         const nframes_t end_frame = _transport_frame + lrintf(nframes * _transport_speed);
192
193         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
194
195                 int ret;
196
197                 if ((*i)->is_hidden()) {
198                         continue;
199                 }
200
201                 if ((ret = (*i)->silent_roll (nframes, start_frame, end_frame, offset, record_active, rec_monitors)) < 0) {
202                         
203                         /* we have to do this here. Route::roll() for an AudioTrack will have called AudioDiskstream::process(),
204                            and the DS will expect AudioDiskstream::commit() to be called. but we're aborting from that
205                            call path, so make sure we release any outstanding locks here before we return failure.
206                         */
207
208                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
209                         for (DiskstreamList::iterator ids = dsl->begin(); ids != dsl->end(); ++ids) {
210                                 (*ids)->recover ();
211                         }
212
213                         stop_transport ();
214                         return -1;
215                 } 
216         }
217
218         return 0;
219 }
220
221 void
222 Session::commit_diskstreams (nframes_t nframes, bool &needs_butler)
223 {
224         int dret;
225         float pworst = 1.0f;
226         float cworst = 1.0f;
227
228         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
229         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
230
231                 if ((*i)->hidden()) {
232                         continue;
233                 }
234                 
235                 /* force all diskstreams not handled by a Route to call do their stuff.
236                    Note: the diskstreams that were handled by a route will just return zero
237                    from this call, because they know they were processed. So in fact, this
238                    also runs commit() for every diskstream.
239                  */
240
241                 if ((dret = (*i)->process (_transport_frame, nframes, 0, actively_recording(), get_rec_monitors_input())) == 0) {
242                         if ((*i)->commit (nframes)) {
243                                 needs_butler = true;
244                         }
245
246                 } else if (dret < 0) {
247                         (*i)->recover();
248                 }
249                 
250                 pworst = min (pworst, (*i)->playback_buffer_load());
251                 cworst = min (cworst, (*i)->capture_buffer_load());
252         }
253
254         uint32_t pmin = g_atomic_int_get (&_playback_load);
255         uint32_t pminold = g_atomic_int_get (&_playback_load_min);
256         uint32_t cmin = g_atomic_int_get (&_capture_load);
257         uint32_t cminold = g_atomic_int_get (&_capture_load_min);
258
259         g_atomic_int_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
260         g_atomic_int_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
261         g_atomic_int_set (&_playback_load_min, min (pmin, pminold));
262         g_atomic_int_set (&_capture_load_min, min (cmin, cminold));
263
264         if (actively_recording()) {
265                 set_dirty();
266         }
267 }
268
269 /** Process callback used when the auditioner is not active */
270 void
271 Session::process_with_events (nframes_t nframes)
272 {
273         Event*         ev;
274         nframes_t      this_nframes;
275         nframes_t      end_frame;
276         nframes_t      offset;
277         bool           session_needs_butler = false;
278         nframes_t      stop_limit;
279         long           frames_moved;
280         
281         /* make sure the auditioner is silent */
282
283         if (auditioner) {
284                 auditioner->silence (nframes, 0);
285         }
286
287         /* handle any pending events */
288
289         while (pending_events.read (&ev, 1) == 1) {
290                 merge_event (ev);
291         }
292
293         /* if we are not in the middle of a state change,
294            and there are immediate events queued up,
295            process them. 
296         */
297
298         while (!non_realtime_work_pending() && !immediate_events.empty()) {
299                 Event *ev = immediate_events.front ();
300                 immediate_events.pop_front ();
301                 process_event (ev);
302         }
303
304         /* Events caused a transport change, send an MTC Full Frame (SMPTE) message.
305          * This is sent whether rolling or not, to give slaves an idea of ardour time
306          * on locates (and allow slow slaves to position and prepare for rolling)
307          */
308         if (_send_smpte_update) {
309                 send_full_time_code(nframes);
310         }
311
312         if (!process_can_proceed()) {
313                 _silent = true;
314                 return;
315         }
316
317         if (events.empty() || next_event == events.end()) {
318                 process_without_events (nframes);
319                 return;
320         }
321
322         /// TODO: Figure out what happens to phi and phase, if transport speed momentarily becomes
323         /// 1.0 eg. during the adjustments of a slave. If that is a bug, then AudioDiskstream::process
324         /// is very likely broken too
325         if (_transport_speed == 1.0) {
326                 frames_moved = (long) nframes;
327         } else {                
328                 frames_moved = (long) AudioDiskstream::
329                         calculate_varispeed_playback_distance(nframes, phase, phi, target_phi); 
330         }
331
332         end_frame = _transport_frame + (nframes_t)frames_moved;
333
334         {
335                 Event* this_event;
336                 Events::iterator the_next_one;
337                 
338                 if (!process_can_proceed()) {
339                         _silent = true;
340                         return;
341                 }
342                 
343                 if (!_exporting && _slave) {
344                         if (!follow_slave (nframes, 0)) {
345                                 return;
346                         }
347                 } 
348
349                 if (_transport_speed == 0) {
350                         no_roll (nframes, 0);
351                         return;
352                 }
353         
354                 if (!_exporting) {
355                         send_midi_time_code_for_cycle (nframes);
356                 }
357
358                 if (actively_recording()) {
359                         stop_limit = max_frames;
360                 } else {
361
362                         if (Config->get_stop_at_session_end()) {
363                                 stop_limit = current_end_frame();
364                         } else {
365                                 stop_limit = max_frames;
366                         }
367                 }
368
369                 if (maybe_stop (stop_limit)) {
370                         no_roll (nframes, 0);
371                         return;
372                 } 
373
374                 this_event = *next_event;
375                 the_next_one = next_event;
376                 ++the_next_one;
377
378                 offset = 0;
379
380                 /* yes folks, here it is, the actual loop where we really truly
381                    process some audio */
382                 while (nframes) {
383
384                         this_nframes = nframes; /* real (jack) time relative */
385
386                         /* running an event, position transport precisely to its time */
387                         if (this_event && this_event->action_frame <= end_frame && this_event->action_frame >= _transport_frame) {
388                                 /* this isn't quite right for reverse play */
389                                 frames_moved = (long) (this_event->action_frame - _transport_frame);
390                                 this_nframes = (nframes_t) abs( floor(frames_moved / _transport_speed) );
391                         } 
392
393                         if (this_nframes) {
394                                 
395                                 click (_transport_frame, nframes, offset);
396                                 
397                                 /* now process frames between now and the first event in this block */
398                                 prepare_diskstreams ();
399
400                                 if (process_routes (this_nframes, offset)) {
401                                         no_roll (nframes, 0);
402                                         return;
403                                 }
404                                 
405                                 commit_diskstreams (this_nframes, session_needs_butler);
406
407                                 nframes -= this_nframes;
408                                 offset += this_nframes;
409                                 
410                                 if (frames_moved < 0) {
411                                         decrement_transport_position (-frames_moved);
412                                 } else {
413                                         increment_transport_position (frames_moved);
414                                 }
415
416                                 maybe_stop (stop_limit);
417                                 check_declick_out ();
418                         }
419
420                         /* now handle this event and all others scheduled for the same time */
421                         
422                         while (this_event && this_event->action_frame == _transport_frame) {
423                                 process_event (this_event);
424
425                                 if (the_next_one == events.end()) {
426                                         this_event = 0;
427                                 } else {
428                                         this_event = *the_next_one;
429                                         ++the_next_one;
430                                 }
431                         } 
432
433                         /* if an event left our state changing, do the right thing */
434
435                         if (non_realtime_work_pending()) {
436                                 no_roll (nframes, offset);
437                                 break;
438                         }
439
440                         /* this is necessary to handle the case of seamless looping */
441                         end_frame = _transport_frame + (nframes_t) floor (nframes * _transport_speed);
442                         
443                 }
444
445                 set_next_event ();
446
447         } /* implicit release of route lock */
448
449         if (session_needs_butler)
450                 summon_butler ();
451 }
452
453 void
454 Session::reset_slave_state ()
455 {
456         average_slave_delta = 1800;
457         delta_accumulator_cnt = 0;
458         have_first_delta_accumulator = false;
459         slave_state = Stopped;
460 }
461
462 bool
463 Session::transport_locked () const
464 {
465         Slave* sl = _slave;
466
467         if (!locate_pending() && ((Config->get_slave_source() == None) || (sl && sl->ok() && sl->locked()))) {
468                 return true;
469         }
470
471         return false;
472 }
473
474 bool
475 Session::follow_slave (nframes_t nframes, nframes_t offset)
476 {
477         double slave_speed;
478         nframes_t slave_transport_frame;
479         nframes_t this_delta;
480         int dir;
481         bool starting;
482
483         if (!_slave->ok()) {
484                 stop_transport ();
485                 Config->set_slave_source (None);
486                 goto noroll;
487         }
488         
489         _slave->speed_and_position (slave_speed, slave_transport_frame);
490
491         if (!_slave->locked()) {
492                 goto noroll;
493         }
494
495         if (slave_transport_frame > _transport_frame) {
496                 this_delta = slave_transport_frame - _transport_frame;
497                 dir = 1;
498         } else {
499                 this_delta = _transport_frame - slave_transport_frame;
500                 dir = -1;
501         }
502
503         if ((starting = _slave->starting())) {
504                 slave_speed = 0.0f;
505         }
506
507         if (_slave->is_always_synced() || Config->get_timecode_source_is_synced()) {
508
509                 /* if the TC source is synced, then we assume that its 
510                    speed is binary: 0.0 or 1.0
511                 */
512
513                 if (slave_speed != 0.0f) {
514                         slave_speed = 1.0f;
515                 } 
516
517         } else {
518
519                 /* TC source is able to drift relative to us (slave)
520                    so we need to keep track of the drift and adjust
521                    our speed to remain locked.
522                 */
523
524                 calculate_moving_average_of_slave_delta(dir, this_delta);
525         }
526         
527         track_slave_state(slave_speed, slave_transport_frame, this_delta, starting);
528
529         if (slave_state == Running && !_slave->is_always_synced() && !Config->get_timecode_source_is_synced()) {
530
531                 if (_transport_speed != 0.0f) {
532                         
533                         /* 
534                            note that average_dir is +1 or -1 
535                         */
536                         
537                         float delta;
538
539                         #ifdef USE_MOVING_AVERAGE_OF_SLAVE
540                                 if (average_slave_delta == 0) {
541                                         delta = this_delta;
542                                         delta *= dir;
543                                 } else {
544                                         delta = average_slave_delta;
545                                         delta *= average_dir;
546                                 }
547                         #else
548                                 delta = this_delta;
549                                 delta *= dir;
550                         #endif
551
552                         float adjusted_speed = slave_speed + (delta /  float(_current_frame_rate));
553                         
554                         if (_slave->give_slave_full_control_over_transport_speed()) {
555                                 request_transport_speed(slave_speed);
556                         } else {
557                                 request_transport_speed(adjusted_speed);
558                                 #ifdef DEBUG_SLAVES
559                                 cerr << "adjust using " << delta
560                                          << " towards " << adjusted_speed
561                                          << " ratio = " << adjusted_speed / slave_speed
562                                          << " current = " << _transport_speed
563                                          << " slave @ " << slave_speed
564                                          << endl;
565                                 #endif
566                         }
567                         
568                         if (abs(average_slave_delta) > (long) _slave->resolution()) {
569                                 cerr << "average slave delta greater than slave resolution, going to silent motion\n";
570                                 goto silent_motion;
571                         }
572                 }
573         } 
574         
575         #ifdef DEBUG_SLAVES
576         if (slave_speed != 0.0)
577         cerr << "delta = " << (int) (dir * this_delta)
578                  << " speed = " << slave_speed 
579                  << " ts = " << _transport_speed 
580                  << " M@ "<< slave_transport_frame << " S@ " << _transport_frame 
581                  << " avgdelta = " << average_slave_delta 
582                  << endl;
583         #endif  
584
585         if (!starting && !non_realtime_work_pending()) {
586                 /* speed is set, we're locked, and good to go */
587                 return true;
588         }
589
590   silent_motion:
591         #ifdef DEBUG_SLAVES     
592         cerr << "reached silent_motion:" <<endl;
593         #endif
594         
595         follow_slave_silently(nframes, offset, slave_speed);
596         
597   noroll:
598         /* don't move at all */
599         #ifdef DEBUG_SLAVES     
600         cerr << "reached no_roll:" <<endl;
601         #endif
602         no_roll (nframes, 0);
603         return false;
604 }
605
606 void
607 Session::calculate_moving_average_of_slave_delta(int dir, nframes_t this_delta)
608 {
609         if (delta_accumulator_cnt >= delta_accumulator_size) {
610                 have_first_delta_accumulator = true;
611                 delta_accumulator_cnt = 0;
612         }
613
614         if (delta_accumulator_cnt != 0 || this_delta < _current_frame_rate) {
615                 delta_accumulator[delta_accumulator_cnt++] = long(dir) * long(this_delta);
616         }
617         
618         if (have_first_delta_accumulator) {
619                 average_slave_delta = 0L;
620                 for (int i = 0; i < delta_accumulator_size; ++i) {
621                         average_slave_delta += delta_accumulator[i];
622                 }
623                 average_slave_delta /= long(delta_accumulator_size);
624                 if (average_slave_delta < 0L) {
625                         average_dir = -1;
626                         average_slave_delta = abs(average_slave_delta);
627                 } else {
628                         average_dir = 1;
629                 }
630         }
631 }
632
633 void
634 Session::track_slave_state(
635                 float slave_speed, 
636                 nframes_t slave_transport_frame, 
637                 nframes_t this_delta,
638                 bool starting)
639 {
640         if (slave_speed != 0.0f) {
641
642                 /* slave is running */
643
644                 switch (slave_state) {
645                 case Stopped:
646                         if (_slave->requires_seekahead()) {
647                                 slave_wait_end = slave_transport_frame + _current_frame_rate;
648                                 locate (slave_wait_end, false, false);
649                                 slave_state = Waiting;
650                                 starting = true;
651
652                         } else {
653
654                                 slave_state = Running;
655
656                                 Location* al = _locations.auto_loop_location();
657
658                                 if (al && play_loop && (slave_transport_frame < al->start() || slave_transport_frame > al->end())) {
659                                         // cancel looping
660                                         request_play_loop(false);
661                                 }
662
663                                 if (slave_transport_frame != _transport_frame) {
664                                         locate (slave_transport_frame, false, false);
665                                 }
666                         }
667                         break;
668
669                 case Waiting:
670                         break;
671
672                 default:
673                         break;
674
675                 }
676
677                 if (slave_state == Waiting) {
678
679                 #ifdef DEBUG_SLAVES
680                         cerr << "waiting at " << slave_transport_frame << endl;
681                 #endif                  
682                         if (slave_transport_frame >= slave_wait_end) {
683 #ifdef DEBUG_SLAVES
684                                 cerr << "\tstart at " << _transport_frame << endl;
685 #endif
686                                 slave_state = Running;
687
688                                 bool ok = true;
689                                 nframes_t frame_delta = slave_transport_frame - _transport_frame;
690
691                                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
692                                 
693                                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
694                                         if (!(*i)->can_internal_playback_seek (frame_delta)) {
695                                                 ok = false;
696                                                 break;
697                                         }
698                                 }
699
700                                 if (ok) {
701                                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
702                                                 (*i)->internal_playback_seek (frame_delta);
703                                         }
704                                         _transport_frame += frame_delta;
705                                        
706                                 } else {
707                                         cerr << "cannot micro-seek\n";
708                                         /* XXX what? */
709                                 }
710
711                                 memset (delta_accumulator, 0, sizeof (long) * delta_accumulator_size);
712                                 average_slave_delta = 0L;
713                                 this_delta = 0;
714                         }
715                 }
716                 
717                 if (slave_state == Running && _transport_speed == 0.0f) {
718                         
719         #ifdef DEBUG_SLAVES
720                         cerr << "slave starts transport\n";
721         #endif
722                         start_transport ();
723                 } 
724
725         } else { // slave_speed is 0
726
727                 /* slave has stopped */
728
729                 if (_transport_speed != 0.0f) {
730
731          #ifdef DEBUG_SLAVES
732                         cerr << "slave stops transport: " << slave_speed << " frame: " << slave_transport_frame 
733                              << " tf = " << _transport_frame << endl;
734          #endif
735                         
736                         stop_transport();
737                 }
738
739                 if (slave_transport_frame != _transport_frame) {
740         #ifdef DEBUG_SLAVES                     
741                         cerr << "slave stopped, move to " << slave_transport_frame << endl;
742         #endif
743                         force_locate (slave_transport_frame, false);
744                 }
745
746                 slave_state = Stopped;
747         }
748 }
749
750 void
751 Session::follow_slave_silently(nframes_t nframes, nframes_t offset, float slave_speed)
752 {
753         if (slave_speed && _transport_speed) {
754
755                 /* something isn't right, but we should move with the master
756                    for now.
757                 */
758
759                 bool need_butler;
760                 
761                 prepare_diskstreams ();
762                 silent_process_routes (nframes, offset);
763                 commit_diskstreams (nframes, need_butler);
764
765                 if (need_butler) {
766                         summon_butler ();
767                 }
768                 
769                 int32_t frames_moved = (int32_t) floor (_transport_speed * nframes);
770                 
771                 if (frames_moved < 0) {
772                         decrement_transport_position (-frames_moved);
773                 } else {
774                         increment_transport_position (frames_moved);
775                 }
776                 
777                 nframes_t stop_limit;
778                 
779                 if (actively_recording()) {
780                         stop_limit = max_frames;
781                 } else {
782                         if (Config->get_stop_at_session_end()) {
783                                 stop_limit = current_end_frame();
784                         } else {
785                                 stop_limit = max_frames;
786                         }
787                 }
788
789                 maybe_stop (stop_limit);
790         }
791 }
792
793 void
794 Session::process_without_events (nframes_t nframes)
795 {
796         bool session_needs_butler = false;
797         nframes_t stop_limit;
798         long frames_moved;
799         nframes_t offset = 0;
800
801         if (!process_can_proceed()) {
802                 _silent = true;
803                 return;
804         }
805
806         if (!_exporting && _slave) {
807                 if (!follow_slave (nframes, 0)) {
808                         return;
809                 }
810         } 
811
812         if (_transport_speed == 0) {
813                 no_roll (nframes, 0);
814                 return;
815         }
816                 
817         if (!_exporting) {
818                 send_midi_time_code_for_cycle (nframes);
819         }
820
821         if (actively_recording()) {
822                 stop_limit = max_frames;
823         } else {
824                 if (Config->get_stop_at_session_end()) {
825                         stop_limit = current_end_frame();
826                 } else {
827                         stop_limit = max_frames;
828                 }
829         }
830                 
831         if (maybe_stop (stop_limit)) {
832                 no_roll (nframes, 0);
833                 return;
834         } 
835
836         if (maybe_sync_start (nframes, offset)) {
837                 return;
838         }
839
840         click (_transport_frame, nframes, offset);
841
842         prepare_diskstreams ();
843         
844         /// TODO: Figure out what happens to phi and phase, if transport speed momentarily becomes
845         /// 1.0 eg. during the adjustments of a slave. If that is a bug, then AudioDiskstream::process
846         /// is very likely broken too
847         if (_transport_speed == 1.0) {
848                 frames_moved = (long) nframes;
849         } else {                
850                 frames_moved = (long) AudioDiskstream::
851                         calculate_varispeed_playback_distance(nframes, phase, phi, target_phi); 
852         }
853
854         if (process_routes (nframes, offset)) {
855                 no_roll (nframes, offset);
856                 return;
857         }
858
859         commit_diskstreams (nframes, session_needs_butler);
860
861         if (frames_moved < 0) {
862                 decrement_transport_position (-frames_moved);
863         } else {
864                 increment_transport_position (frames_moved);
865         }
866
867         maybe_stop (stop_limit);
868         check_declick_out ();
869
870         if (session_needs_butler)
871                 summon_butler ();
872 }
873
874 /** Process callback used when the auditioner is active.
875  * @param nframes number of frames to process.
876  */
877 void
878 Session::process_audition (nframes_t nframes)
879 {
880         Event* ev;
881         boost::shared_ptr<RouteList> r = routes.reader ();
882
883         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
884                 if (!(*i)->is_hidden()) {
885                         (*i)->silence (nframes, 0);
886                 }
887         }
888
889         /* run the auditioner, and if it says we need butler service, ask for it */
890         
891         if (auditioner->play_audition (nframes) > 0) {
892                 summon_butler ();
893         } 
894
895         /* handle pending events */
896
897         while (pending_events.read (&ev, 1) == 1) {
898                 merge_event (ev);
899         }
900
901         /* if we are not in the middle of a state change,
902            and there are immediate events queued up,
903            process them. 
904         */
905
906         while (!non_realtime_work_pending() && !immediate_events.empty()) {
907                 Event *ev = immediate_events.front ();
908                 immediate_events.pop_front ();
909                 process_event (ev);
910         }
911
912         if (!auditioner->active()) {
913                 /* auditioner no longer active, so go back to the normal process callback */
914                 process_function = &Session::process_with_events;
915         }
916 }
917
918 bool
919 Session::maybe_sync_start (nframes_t& nframes, nframes_t& offset)
920 {
921         nframes_t sync_offset;
922
923         if (!waiting_for_sync_offset) {
924                 return false;
925         }
926
927         if (_engine.get_sync_offset (sync_offset) && sync_offset < nframes) {
928
929                 /* generate silence up to the sync point, then
930                    adjust nframes + offset to reflect whatever
931                    is left to do.
932                 */
933
934                 no_roll (sync_offset, 0);
935                 nframes -= sync_offset;
936                 offset += sync_offset;
937                 waiting_for_sync_offset = false;
938                 
939                 if (nframes == 0) {
940                         return true; // done, nothing left to process
941                 }
942                 
943         } else {
944
945                 /* sync offset point is not within this process()
946                    cycle, so just generate silence. and don't bother 
947                    with any fancy stuff here, just the minimal silence.
948                 */
949
950                 g_atomic_int_inc (&processing_prohibited);
951                 no_roll (nframes, 0);
952                 g_atomic_int_dec_and_test (&processing_prohibited);
953
954                 if (Config->get_locate_while_waiting_for_sync()) {
955                         if (micro_locate (nframes)) {
956                                 /* XXX ERROR !!! XXX */
957                         }
958                 }
959
960                 return true; // done, nothing left to process
961         }
962
963         return false;
964 }
965