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