if using only 1 processor for DSP, do not use the graph code to execute routes -...
[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/thread.h>
29
30 #include "ardour/ardour.h"
31 #include "ardour/audioengine.h"
32 #include "ardour/auditioner.h"
33 #include "ardour/butler.h"
34 #include "ardour/debug.h"
35 #include "ardour/process_thread.h"
36 #include "ardour/session.h"
37 #include "ardour/slave.h"
38 #include "ardour/timestamps.h"
39 #include "ardour/graph.h"
40 #include "ardour/audio_port.h"
41
42 #include "midi++/manager.h"
43 #include "midi++/mmc.h"
44
45 #include "i18n.h"
46
47 using namespace ARDOUR;
48 using namespace PBD;
49 using namespace std;
50
51 /** Called by the audio engine when there is work to be done with JACK.
52  * @param nframes Number of frames to process.
53  */
54 void
55 Session::process (pframes_t nframes)
56 {
57         MIDI::Manager::instance()->cycle_start(nframes);
58
59         _silent = false;
60
61         if (processing_blocked()) {
62                 _silent = true;
63                 return;
64         }
65
66         if (non_realtime_work_pending()) {
67                 if (!_butler->transport_work_requested ()) {
68                         post_transport ();
69                 }
70         }
71
72         _engine.main_thread()->get_buffers ();
73
74         (this->*process_function) (nframes);
75
76         _engine.main_thread()->drop_buffers ();
77
78         // the ticker is for sending time information like MidiClock
79         framepos_t transport_frames = transport_frame();
80         Timecode::BBT_Time transport_bbt;
81         bbt_time(transport_frames, transport_bbt);
82         Timecode::Time transport_timecode;
83         timecode_time(transport_frames, transport_timecode);
84         tick (transport_frames, transport_bbt, transport_timecode); /* EMIT SIGNAL */
85
86         SendFeedback (); /* EMIT SIGNAL */
87
88         MIDI::Manager::instance()->cycle_end();
89 }
90
91 int
92 Session::fail_roll (pframes_t nframes)
93 {
94         return no_roll (nframes);
95 }
96
97 int
98 Session::no_roll (pframes_t nframes)
99 {
100         framepos_t end_frame = _transport_frame + nframes; // FIXME: varispeed + no_roll ??
101         int ret = 0;
102         bool declick = get_transport_declick_required();
103         boost::shared_ptr<RouteList> r = routes.reader ();
104
105         if (_click_io) {
106                 _click_io->silence (nframes);
107         }
108
109         if (Config->get_processor_usage() != 1) {
110                 DEBUG_TRACE(DEBUG::Graph,"calling graph/no-roll\n");
111                 route_graph->routes_no_roll( nframes, _transport_frame, end_frame, non_realtime_work_pending(), actively_recording(), declick);
112         } else {
113                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
114                         
115                         if ((*i)->is_hidden()) {
116                                 continue;
117                         }
118                         
119                         (*i)->set_pending_declick (declick);
120                         
121                         if ((*i)->no_roll (nframes, _transport_frame, end_frame, non_realtime_work_pending(),
122                                            actively_recording(), declick)) {
123                                 error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
124                                 ret = -1;
125                                 break;
126                         }
127                 }
128         }
129
130         return ret;
131 }
132
133 int
134 Session::process_routes (pframes_t nframes, bool& need_butler)
135 {
136         bool record_active;
137         int  declick = get_transport_declick_required();
138         bool rec_monitors = get_rec_monitors_input();
139         boost::shared_ptr<RouteList> r = routes.reader ();
140
141         if (transport_sub_state & StopPendingCapture) {
142                 /* force a declick out */
143                 declick = -1;
144         }
145         
146         record_active = actively_recording(); // || (get_record_enabled() && get_punch_in());
147         
148         const framepos_t start_frame = _transport_frame;
149         const framepos_t end_frame = _transport_frame + floor (nframes * _transport_speed);
150         
151         if (Config->get_processor_usage() != 1) {
152                 DEBUG_TRACE(DEBUG::Graph,"calling graph/process-routes\n");
153                 route_graph->process_routes( nframes, start_frame, end_frame, declick, record_active, rec_monitors, need_butler);
154
155         } else {
156
157                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
158                         
159                         int ret;
160                         
161                         if ((*i)->is_hidden()) {
162                                 continue;
163                         }
164                         
165                         (*i)->set_pending_declick (declick);
166                         
167                         if ((ret = (*i)->roll (nframes, start_frame, end_frame, declick, record_active, rec_monitors, need_butler)) < 0) {
168                                 stop_transport ();
169                                 return -1;
170                         }
171                 }
172         }
173
174         return 0;
175 }
176
177 int
178 Session::silent_process_routes (pframes_t nframes, bool& need_butler)
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 framepos_t start_frame = _transport_frame;
191         const framepos_t end_frame = _transport_frame + lrintf(nframes * _transport_speed);
192
193         if (Config->get_processor_usage() != 1) {
194                 cerr << "GRAPH PROCESS\n";
195                 route_graph->silent_process_routes( nframes, start_frame, end_frame, record_active, rec_monitors, need_butler);
196         } else {
197                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
198                         
199                         int ret;
200                         
201                         if ((*i)->is_hidden()) {
202                                 continue;
203                         }
204                         
205                         if ((ret = (*i)->silent_roll (nframes, start_frame, end_frame, record_active, rec_monitors, need_butler)) < 0) {
206                                 stop_transport ();
207                                 return -1;
208                         }
209                 }
210         }
211
212         return 0;
213 }
214
215 void
216 Session::get_track_statistics ()
217 {
218         float pworst = 1.0f;
219         float cworst = 1.0f;
220
221         boost::shared_ptr<RouteList> rl = routes.reader();
222         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
223
224                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
225
226                 if (!tr || tr->hidden()) {
227                         continue;
228                 }
229
230                 pworst = min (pworst, tr->playback_buffer_load());
231                 cworst = min (cworst, tr->capture_buffer_load());
232         }
233
234         g_atomic_int_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
235         g_atomic_int_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
236
237         if (actively_recording()) {
238                 set_dirty();
239         }
240 }
241
242 /** Process callback used when the auditioner is not active */
243 void
244 Session::process_with_events (pframes_t nframes)
245 {
246         SessionEvent*  ev;
247         pframes_t      this_nframes;
248         framepos_t     end_frame;
249         bool           session_needs_butler = false;
250         framepos_t     stop_limit;
251         framecnt_t     frames_moved;
252
253         /* make sure the auditioner is silent */
254
255         if (auditioner) {
256                 auditioner->silence (nframes);
257         }
258
259         /* handle any pending events */
260
261         while (pending_events.read (&ev, 1) == 1) {
262                 merge_event (ev);
263         }
264
265         /* if we are not in the middle of a state change,
266            and there are immediate events queued up,
267            process them.
268         */
269
270         while (!non_realtime_work_pending() && !immediate_events.empty()) {
271                 SessionEvent *ev = immediate_events.front ();
272                 immediate_events.pop_front ();
273                 process_event (ev);
274         }
275
276         /* Decide on what to do with quarter-frame MTC during this cycle */
277
278         bool const was_sending_qf_mtc = _send_qf_mtc;
279         double const tolerance = Config->get_mtc_qf_speed_tolerance() / 100.0;
280
281         if (_transport_speed != 0) {
282                 _send_qf_mtc = (
283                         Config->get_send_mtc () &&
284                         _transport_speed >= (1 - tolerance) &&
285                         _transport_speed <= (1 + tolerance)
286                         );
287                 
288                 if (_send_qf_mtc && !was_sending_qf_mtc) {
289                         /* we will re-start quarter-frame MTC this cycle, so send a full update to set things up */
290                         _send_timecode_update = true;
291                 }
292                 
293                 if (Config->get_send_mtc() && !_send_qf_mtc && _pframes_since_last_mtc > (frame_rate () / 4)) {
294                         /* we're sending MTC, but we're not sending QF MTC at the moment, and it's been
295                            a quarter of a second since we sent anything at all, so send a full MTC update
296                            this cycle.
297                         */
298                         _send_timecode_update = true;
299                 }
300                 
301                 _pframes_since_last_mtc += nframes;
302         }
303                 
304         /* Events caused a transport change (or we re-started sending
305          * MTC), so send an MTC Full Frame (Timecode) message.  This
306          * is sent whether rolling or not, to give slaves an idea of
307          * ardour time on locates (and allow slow slaves to position
308          * and prepare for rolling)
309          */
310         if (_send_timecode_update) {
311                 send_full_time_code (_transport_frame);
312         }
313
314         if (!process_can_proceed()) {
315                 _silent = true;
316                 return;
317         }
318
319         if (events.empty() || next_event == events.end()) {
320                 process_without_events (nframes);
321                 return;
322         }
323
324         if (_transport_speed == 1.0) {
325                 frames_moved = (framecnt_t) nframes;
326         } else {
327                 interpolation.set_target_speed (fabs(_target_transport_speed));
328                 interpolation.set_speed (fabs(_transport_speed));
329                 frames_moved = (framecnt_t) interpolation.interpolate (0, nframes, 0, 0);
330         }
331
332         end_frame = _transport_frame + frames_moved;
333
334         {
335                 SessionEvent* 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)) {
345                                 return;
346                         }
347                 }
348
349                 if (_transport_speed == 0) {
350                         no_roll (nframes);
351                         return;
352                 }
353
354                 if (!_exporting && !timecode_transmission_suspended()) {
355                         send_midi_time_code_for_cycle (_transport_frame, end_frame, nframes);
356                 }
357
358                 if (actively_recording()) {
359                         stop_limit = max_framepos;
360                 } else {
361
362                         if (Config->get_stop_at_session_end()) {
363                                 stop_limit = current_end_frame();
364                         } else {
365                                 stop_limit = max_framepos;
366                         }
367                 }
368
369                 if (maybe_stop (stop_limit)) {
370                         no_roll (nframes);
371                         return;
372                 }
373
374                 this_event = *next_event;
375                 the_next_one = next_event;
376                 ++the_next_one;
377
378                 /* yes folks, here it is, the actual loop where we really truly
379                    process some audio
380                 */
381
382                 while (nframes) {
383
384                         this_nframes = nframes; /* real (jack) time relative */
385                         frames_moved = (framecnt_t) floor (_transport_speed * nframes); /* transport relative */
386
387                         /* running an event, position transport precisely to its time */
388                         if (this_event && this_event->action_frame <= end_frame && this_event->action_frame >= _transport_frame) {
389                                 /* this isn't quite right for reverse play */
390                                 frames_moved = (framecnt_t) (this_event->action_frame - _transport_frame);
391                                 this_nframes = abs (floor(frames_moved / _transport_speed));
392                         }
393
394                         if (this_nframes) {
395
396                                 click (_transport_frame, this_nframes);
397
398                                 if (process_routes (this_nframes, session_needs_butler)) {
399                                         fail_roll (nframes);
400                                         return;
401                                 }
402
403                                 get_track_statistics ();
404
405                                 nframes -= this_nframes;
406
407                                 if (frames_moved < 0) {
408                                         decrement_transport_position (-frames_moved);
409                                 } else {
410                                         increment_transport_position (frames_moved);
411                                 }
412
413                                 maybe_stop (stop_limit);
414                                 check_declick_out ();
415                         }
416
417                         _engine.split_cycle (this_nframes);
418
419                         /* now handle this event and all others scheduled for the same time */
420
421                         while (this_event && this_event->action_frame == _transport_frame) {
422                                 process_event (this_event);
423
424                                 if (the_next_one == events.end()) {
425                                         this_event = 0;
426                                 } else {
427                                         this_event = *the_next_one;
428                                         ++the_next_one;
429                                 }
430                         }
431
432                         /* if an event left our state changing, do the right thing */
433
434                         if (nframes && non_realtime_work_pending()) {
435                                 no_roll (nframes);
436                                 break;
437                         }
438
439                         /* this is necessary to handle the case of seamless looping */
440                         end_frame = _transport_frame + floor (nframes * _transport_speed);
441
442                 }
443
444                 set_next_event ();
445
446         } /* implicit release of route lock */
447
448         if (session_needs_butler) {
449                 _butler->summon ();
450         }
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_external_sync() || (sl && sl->ok() && sl->locked()))) {
468                 return true;
469         }
470
471         return false;
472 }
473
474 bool
475 Session::follow_slave (pframes_t nframes)
476 {
477         double slave_speed;
478         framepos_t slave_transport_frame;
479         framecnt_t this_delta;
480         int dir;
481
482         if (!_slave->ok()) {
483                 stop_transport ();
484                 config.set_external_sync (false);
485                 goto noroll;
486         }
487
488         _slave->speed_and_position (slave_speed, slave_transport_frame);
489
490         DEBUG_TRACE (DEBUG::Slave, string_compose ("Slave position %1 speed %2\n", slave_transport_frame, slave_speed));
491
492         if (!_slave->locked()) {
493                 DEBUG_TRACE (DEBUG::Slave, "slave not locked\n");
494                 goto noroll;
495         }
496
497         if (slave_transport_frame > _transport_frame) {
498                 this_delta = slave_transport_frame - _transport_frame;
499                 dir = 1;
500         } else {
501                 this_delta = _transport_frame - slave_transport_frame;
502                 dir = -1;
503         }
504
505         if (_slave->starting()) {
506                 slave_speed = 0.0f;
507         }
508
509         if (_slave->is_always_synced() || config.get_timecode_source_is_synced()) {
510
511                 /* if the TC source is synced, then we assume that its
512                    speed is binary: 0.0 or 1.0
513                 */
514
515                 if (slave_speed != 0.0f) {
516                         slave_speed = 1.0f;
517                 }
518
519         } else {
520
521                 /* if we are chasing and the average delta between us and the
522                    master gets too big, we want to switch to silent
523                    motion. so keep track of that here.
524                 */
525
526                 if (_slave_state == Running) {
527                         calculate_moving_average_of_slave_delta(dir, this_delta);
528                 }
529         }
530
531         track_slave_state (slave_speed, slave_transport_frame, this_delta);
532
533         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave state %1 @ %2 speed %3 cur delta %4 avg delta %5\n",
534                                                    _slave_state, slave_transport_frame, slave_speed, this_delta, average_slave_delta));
535                      
536
537         if (_slave_state == Running && !_slave->is_always_synced() && !config.get_timecode_source_is_synced()) {
538
539                 if (_transport_speed != 0.0f) {
540
541                         /*
542                            note that average_dir is +1 or -1
543                         */
544
545                         float delta;
546
547                         if (average_slave_delta == 0) {
548                                 delta = this_delta;
549                                 delta *= dir;
550                         } else {
551                                 delta = average_slave_delta;
552                                 delta *= average_dir;
553                         }
554
555 #ifndef NDEBUG
556                         if (slave_speed != 0.0) {
557                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("delta = %1 speed = %2 ts = %3 M@%4 S@%5 avgdelta %6\n",
558                                                                            (int) (dir * this_delta),
559                                                                            slave_speed,
560                                                                            _transport_speed,
561                                                                            _transport_frame,
562                                                                            slave_transport_frame, 
563                                                                            average_slave_delta));
564                         }
565 #endif
566                         
567                         if (_slave->give_slave_full_control_over_transport_speed()) {
568                                 set_transport_speed (slave_speed, false, false);
569                                 //std::cout << "set speed = " << slave_speed << "\n";
570                         } else {
571                                 float adjusted_speed = slave_speed + (1.5 * (delta /  float(_current_frame_rate)));
572                                 request_transport_speed (adjusted_speed);
573                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("adjust using %1 towards %2 ratio %3 current %4 slave @ %5\n",
574                                                                            delta, adjusted_speed, adjusted_speed/slave_speed, _transport_speed,
575                                                                            slave_speed));
576                         }
577                         
578 #if 1
579                         if ((framecnt_t) abs(average_slave_delta) > _slave->resolution()) {
580                                 cerr << "average slave delta greater than slave resolution (" << _slave->resolution() << "), going to silent motion\n";
581                                 goto silent_motion;
582                         }
583 #endif
584                 }
585         }
586
587
588         if (_slave_state == Running && !non_realtime_work_pending()) {
589                 /* speed is set, we're locked, and good to go */
590                 return true;
591         }
592
593   silent_motion:
594         DEBUG_TRACE (DEBUG::Slave, "silent motion\n")
595         follow_slave_silently (nframes, slave_speed);
596
597   noroll:
598         /* don't move at all */
599         DEBUG_TRACE (DEBUG::Slave, "no roll\n")
600         no_roll (nframes);
601         return false;
602 }
603
604 void
605 Session::calculate_moving_average_of_slave_delta (int dir, framecnt_t this_delta)
606 {
607         if (delta_accumulator_cnt >= delta_accumulator_size) {
608                 have_first_delta_accumulator = true;
609                 delta_accumulator_cnt = 0;
610         }
611
612         if (delta_accumulator_cnt != 0 || this_delta < _current_frame_rate) {
613                 delta_accumulator[delta_accumulator_cnt++] = (framecnt_t) dir *  (framecnt_t) this_delta;
614         }
615
616         if (have_first_delta_accumulator) {
617                 average_slave_delta = 0L;
618                 for (int i = 0; i < delta_accumulator_size; ++i) {
619                         average_slave_delta += delta_accumulator[i];
620                 }
621                 average_slave_delta /= (int32_t) delta_accumulator_size;
622                 if (average_slave_delta < 0L) {
623                         average_dir = -1;
624                         average_slave_delta = abs(average_slave_delta);
625                 } else {
626                         average_dir = 1;
627                 }
628         }
629 }
630
631 void
632 Session::track_slave_state (float slave_speed, framepos_t slave_transport_frame, framecnt_t this_delta)
633 {
634         if (slave_speed != 0.0f) {
635
636                 /* slave is running */
637
638                 switch (_slave_state) {
639                 case Stopped:
640                         if (_slave->requires_seekahead()) {
641                                 slave_wait_end = slave_transport_frame + _slave->seekahead_distance ();
642                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, but running, requires seekahead to %1\n", slave_wait_end));
643                                 /* we can call locate() here because we are in process context */
644                                 locate (slave_wait_end, false, false);
645                                 _slave_state = Waiting;
646
647                         } else {
648
649                                 _slave_state = Running;
650
651                                 Location* al = _locations->auto_loop_location();
652
653                                 if (al && play_loop && (slave_transport_frame < al->start() || slave_transport_frame > al->end())) {
654                                         // cancel looping
655                                         request_play_loop(false);
656                                 }
657
658                                 if (slave_transport_frame != _transport_frame) {
659                                         locate (slave_transport_frame, false, false);
660                                 }
661                         }
662                         break;
663
664                 case Waiting:
665                 default:
666                         break;
667                 }
668
669                 if (_slave_state == Waiting) {
670
671                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave waiting at %1\n", slave_transport_frame));
672
673                         if (slave_transport_frame >= slave_wait_end) {
674
675                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave start at %1 vs %2\n", slave_transport_frame, _transport_frame));
676
677                                 _slave_state = Running;
678
679                                 /* now perform a "micro-seek" within the disk buffers to realign ourselves
680                                    precisely with the master.
681                                 */
682
683
684                                 bool ok = true;
685                                 framecnt_t frame_delta = slave_transport_frame - _transport_frame;
686
687                                 boost::shared_ptr<RouteList> rl = routes.reader();
688                                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
689                                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
690                                         if (tr && !tr->can_internal_playback_seek (frame_delta)) {
691                                                 ok = false;
692                                                 break;
693                                         }
694                                 }
695
696                                 if (ok) {
697                                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
698                                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
699                                                 if (tr) {
700                                                         tr->internal_playback_seek (frame_delta);
701                                                 }
702                                         }
703                                         _transport_frame += frame_delta;
704
705                                 } else {
706                                         cerr << "cannot micro-seek\n";
707                                         /* XXX what? */
708                                 }
709
710                                 memset (delta_accumulator, 0, sizeof (int32_t) * delta_accumulator_size);
711                                 average_slave_delta = 0L;
712                                 this_delta = 0;
713                         }
714                 }
715
716                 if (_slave_state == Running && _transport_speed == 0.0f) {
717                         DEBUG_TRACE (DEBUG::Slave, "slave starts transport\n");
718                         start_transport ();
719                 }
720
721         } else { // slave_speed is 0
722
723                 /* slave has stopped */
724
725                 if (_transport_speed != 0.0f) {
726                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stops transport: %1 frame %2 tf %3\n", slave_speed, slave_transport_frame, _transport_frame));
727                         stop_transport ();
728                 }
729
730                 if (slave_transport_frame != _transport_frame) {
731                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, move to %1\n", slave_transport_frame));
732                         force_locate (slave_transport_frame, false);
733                 }
734
735                 _slave_state = Stopped;
736         }
737 }
738
739 void
740 Session::follow_slave_silently (pframes_t nframes, float slave_speed)
741 {
742         if (slave_speed && _transport_speed) {
743
744                 /* something isn't right, but we should move with the master
745                    for now.
746                 */
747
748                 bool need_butler;
749
750                 silent_process_routes (nframes, need_butler);
751
752                 get_track_statistics ();
753
754                 if (need_butler) {
755                         _butler->summon ();
756                 }
757
758                 int32_t frames_moved = (int32_t) floor (_transport_speed * nframes);
759
760                 if (frames_moved < 0) {
761                         decrement_transport_position (-frames_moved);
762                 } else {
763                         increment_transport_position (frames_moved);
764                 }
765                 
766                 framepos_t stop_limit;
767
768                 if (actively_recording()) {
769                         stop_limit = max_framepos;
770                 } else {
771                         if (Config->get_stop_at_session_end()) {
772                                 stop_limit = current_end_frame();
773                         } else {
774                                 stop_limit = max_framepos;
775                         }
776                 }
777
778                 maybe_stop (stop_limit);
779         }
780 }
781
782 void
783 Session::process_without_events (pframes_t nframes)
784 {
785         bool session_needs_butler = false;
786         framepos_t stop_limit;
787         framecnt_t frames_moved;
788
789         if (!process_can_proceed()) {
790                 _silent = true;
791                 return;
792         }
793
794         if (!_exporting && _slave) {
795                 if (!follow_slave (nframes)) {
796                         return;
797                 }
798         }
799
800         if (_transport_speed == 0) {
801                 fail_roll (nframes);
802                 return;
803         }
804
805         if (_transport_speed == 1.0) {
806                 frames_moved = (framecnt_t) nframes;
807         } else {
808                 interpolation.set_target_speed (fabs(_target_transport_speed));
809                 interpolation.set_speed (fabs(_transport_speed));
810                 frames_moved = (framecnt_t) interpolation.interpolate (0, nframes, 0, 0);
811         }
812         
813         if (!_exporting && !timecode_transmission_suspended()) {
814                 send_midi_time_code_for_cycle (_transport_frame, _transport_frame + frames_moved, nframes);
815         }
816
817         if (actively_recording()) {
818                 stop_limit = max_framepos;
819         } else {
820                 if (Config->get_stop_at_session_end()) {
821                         stop_limit = current_end_frame();
822                 } else {
823                         stop_limit = max_framepos;
824                 }
825         }
826
827         if (maybe_stop (stop_limit)) {
828                 fail_roll (nframes);
829                 return;
830         }
831
832         if (maybe_sync_start (nframes)) {
833                 return;
834         }
835
836         click (_transport_frame, nframes);
837
838         if (process_routes (nframes, session_needs_butler)) {
839                 fail_roll (nframes);
840                 return;
841         }
842
843         get_track_statistics ();
844
845         /* XXX: I'm not sure whether this is correct, but at least it
846            matches process_with_events, so that this new frames_moved
847            is -ve when transport speed is -ve.  This means that the
848            transport position is updated correctly when we are in
849            reverse.  It seems a bit wrong that we're not using the
850            interpolator to compute this.
851         */
852            
853         frames_moved = (framecnt_t) floor (_transport_speed * nframes);
854         
855         if (frames_moved < 0) {
856                 decrement_transport_position (-frames_moved);
857         } else {
858                 increment_transport_position (frames_moved);
859         }
860
861         maybe_stop (stop_limit);
862         check_declick_out ();
863
864         if (session_needs_butler) {
865                 _butler->summon ();
866         }
867 }
868
869 /** Process callback used when the auditioner is active.
870  * @param nframes number of frames to process.
871  */
872 void
873 Session::process_audition (pframes_t nframes)
874 {
875         SessionEvent* ev;
876         boost::shared_ptr<RouteList> r = routes.reader ();
877
878         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
879                 if (!(*i)->is_hidden()) {
880                         (*i)->silence (nframes);
881                 }
882         }
883
884         /* run the auditioner, and if it says we need butler service, ask for it */
885
886         if (auditioner->play_audition (nframes) > 0) {
887                 _butler->summon ();
888         }
889
890         /* if using a monitor section, run it because otherwise we don't hear anything */
891
892         if (auditioner->needs_monitor()) {
893                 _monitor_out->passthru (_transport_frame, _transport_frame + nframes, nframes, false);
894         }
895         
896         /* handle pending events */
897
898         while (pending_events.read (&ev, 1) == 1) {
899                 merge_event (ev);
900         }
901
902         /* if we are not in the middle of a state change,
903            and there are immediate events queued up,
904            process them.
905         */
906
907         while (!non_realtime_work_pending() && !immediate_events.empty()) {
908                 SessionEvent *ev = immediate_events.front ();
909                 immediate_events.pop_front ();
910                 process_event (ev);
911         }
912
913         if (!auditioner->auditioning()) {
914                 /* auditioner no longer active, so go back to the normal process callback */
915                 process_function = &Session::process_with_events;
916         }
917 }
918
919 bool
920 Session::maybe_sync_start (pframes_t & nframes)
921 {
922         pframes_t sync_offset;
923
924         if (!waiting_for_sync_offset) {
925                 return false;
926         }
927
928         if (_engine.get_sync_offset (sync_offset) && sync_offset < nframes) {
929
930                 /* generate silence up to the sync point, then
931                    adjust nframes + offset to reflect whatever
932                    is left to do.
933                 */
934
935                 no_roll (sync_offset);
936                 nframes -= sync_offset;
937                 AudioPort::increment_port_offset (sync_offset);
938                 waiting_for_sync_offset = false;
939
940                 if (nframes == 0) {
941                         return true; // done, nothing left to process
942                 }
943
944         } else {
945
946                 /* sync offset point is not within this process()
947                    cycle, so just generate silence. and don't bother
948                    with any fancy stuff here, just the minimal silence.
949                 */
950
951                 _silent = true;
952
953                 if (Config->get_locate_while_waiting_for_sync()) {
954                         if (micro_locate (nframes)) {
955                                 /* XXX ERROR !!! XXX */
956                         }
957                 }
958
959                 return true; // done, nothing left to process
960         }
961
962         return false;
963 }
964
965 void
966 Session::queue_event (SessionEvent* ev)
967 {
968         if (_state_of_the_state & Deletion) {
969                 return;
970         } else if (_state_of_the_state & Loading) {
971                 merge_event (ev);
972         } else {
973                 pending_events.write (&ev, 1);
974         }
975 }
976
977 void
978 Session::set_next_event ()
979 {
980         if (events.empty()) {
981                 next_event = events.end();
982                 return;
983         }
984
985         if (next_event == events.end()) {
986                 next_event = events.begin();
987         }
988
989         if ((*next_event)->action_frame > _transport_frame) {
990                 next_event = events.begin();
991         }
992
993         for (; next_event != events.end(); ++next_event) {
994                 if ((*next_event)->action_frame >= _transport_frame) {
995                         break;
996                 }
997         }
998 }
999
1000 void
1001 Session::process_event (SessionEvent* ev)
1002 {
1003         bool remove = true;
1004         bool del = true;
1005
1006         /* if we're in the middle of a state change (i.e. waiting
1007            for the butler thread to complete the non-realtime
1008            part of the change), we'll just have to queue this
1009            event for a time when the change is complete.
1010         */
1011
1012         if (non_realtime_work_pending()) {
1013
1014                 /* except locates, which we have the capability to handle */
1015
1016                 if (ev->type != SessionEvent::Locate) {
1017                         immediate_events.insert (immediate_events.end(), ev);
1018                         _remove_event (ev);
1019                         return;
1020                 }
1021         }
1022
1023         DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Processing event: %1 @ %2\n", enum_2_string (ev->type), _transport_frame));
1024
1025         switch (ev->type) {
1026         case SessionEvent::SetLoop:
1027                 set_play_loop (ev->yes_or_no);
1028                 break;
1029
1030         case SessionEvent::AutoLoop:
1031                 if (play_loop) {
1032                         start_locate (ev->target_frame, true, false, Config->get_seamless_loop());
1033                 }
1034                 remove = false;
1035                 del = false;
1036                 break;
1037
1038         case SessionEvent::Locate:
1039                 if (ev->yes_or_no) {
1040                         // cerr << "forced locate to " << ev->target_frame << endl;
1041                         locate (ev->target_frame, false, true, false);
1042                 } else {
1043                         // cerr << "soft locate to " << ev->target_frame << endl;
1044                         start_locate (ev->target_frame, false, true, false);
1045                 }
1046                 _send_timecode_update = true;
1047                 break;
1048
1049         case SessionEvent::LocateRoll:
1050                 if (ev->yes_or_no) {
1051                         // cerr << "forced locate to+roll " << ev->target_frame << endl;
1052                         locate (ev->target_frame, true, true, false);
1053                 } else {
1054                         // cerr << "soft locate to+roll " << ev->target_frame << endl;
1055                         start_locate (ev->target_frame, true, true, false);
1056                 }
1057                 _send_timecode_update = true;
1058                 break;
1059
1060         case SessionEvent::LocateRollLocate:
1061                 // locate is handled by ::request_roll_at_and_return()
1062                 _requested_return_frame = ev->target_frame;
1063                 request_locate (ev->target2_frame, true);
1064                 break;
1065
1066
1067         case SessionEvent::SetTransportSpeed:
1068                 set_transport_speed (ev->speed, ev->yes_or_no, ev->second_yes_or_no);
1069                 break;
1070
1071         case SessionEvent::PunchIn:
1072                 // cerr << "PunchIN at " << transport_frame() << endl;
1073                 if (config.get_punch_in() && record_status() == Enabled) {
1074                         enable_record ();
1075                 }
1076                 remove = false;
1077                 del = false;
1078                 break;
1079
1080         case SessionEvent::PunchOut:
1081                 // cerr << "PunchOUT at " << transport_frame() << endl;
1082                 if (config.get_punch_out()) {
1083                         step_back_from_record ();
1084                 }
1085                 remove = false;
1086                 del = false;
1087                 break;
1088
1089         case SessionEvent::StopOnce:
1090                 if (!non_realtime_work_pending()) {
1091                         stop_transport (ev->yes_or_no);
1092                         _clear_event_type (SessionEvent::StopOnce);
1093                 }
1094                 remove = false;
1095                 del = false;
1096                 break;
1097
1098         case SessionEvent::RangeStop:
1099                 if (!non_realtime_work_pending()) {
1100                         stop_transport (ev->yes_or_no);
1101                 }
1102                 remove = false;
1103                 del = false;
1104                 break;
1105
1106         case SessionEvent::RangeLocate:
1107                 start_locate (ev->target_frame, true, true, false);
1108                 remove = false;
1109                 del = false;
1110                 break;
1111
1112         case SessionEvent::Overwrite:
1113                 overwrite_some_buffers (static_cast<Track*>(ev->ptr));
1114                 break;
1115
1116         case SessionEvent::SetTrackSpeed:
1117                 set_track_speed (static_cast<Track*> (ev->ptr), ev->speed);
1118                 break;
1119
1120         case SessionEvent::SetSyncSource:
1121                 use_sync_source (ev->slave);
1122                 break;
1123
1124         case SessionEvent::Audition:
1125                 set_audition (ev->region);
1126                 // drop reference to region
1127                 ev->region.reset ();
1128                 break;
1129
1130         case SessionEvent::InputConfigurationChange:
1131                 add_post_transport_work (PostTransportInputChange);
1132                 _butler->schedule_transport_work ();
1133                 break;
1134
1135         case SessionEvent::SetPlayAudioRange:
1136                 set_play_range (ev->audio_range, (ev->speed == 1.0f));
1137                 break;
1138
1139         case SessionEvent::RealTimeOperation:
1140                 process_rtop (ev);
1141                 del = false; // other side of RT request needs to clean up
1142                 break;
1143
1144         case SessionEvent::AdjustPlaybackBuffering:
1145                 schedule_playback_buffering_adjustment ();
1146                 break;
1147
1148         case SessionEvent::AdjustCaptureBuffering:
1149                 schedule_capture_buffering_adjustment ();
1150                 break;
1151
1152         case SessionEvent::SetTimecodeTransmission:
1153                 g_atomic_int_set (&_suspend_timecode_transmission, ev->yes_or_no ? 0 : 1);
1154                 break;
1155
1156         default:
1157           fatal << string_compose(_("Programming error: illegal event type in process_event (%1)"), ev->type) << endmsg;
1158                 /*NOTREACHED*/
1159                 break;
1160         };
1161
1162         if (remove) {
1163                 del = del && !_remove_event (ev);
1164         }
1165
1166         if (del) {
1167                 delete ev;
1168         }
1169 }
1170