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