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