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