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