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