new approach to handling Transport Masters when engine is restarted
[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;
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                         if (micro_locate (nframes)) {
734                                 /* XXX ERROR !!! XXX */
735                         }
736                 }
737
738                 return true; // done, nothing left to process
739         }
740
741         return false;
742 }
743
744 void
745 Session::queue_event (SessionEvent* ev)
746 {
747         if (_state_of_the_state & Deletion) {
748                 return;
749         } else if (_state_of_the_state & Loading) {
750                 merge_event (ev);
751         } else {
752                 Glib::Threads::Mutex::Lock lm (rb_write_lock);
753                 pending_events.write (&ev, 1);
754         }
755 }
756
757 void
758 Session::set_next_event ()
759 {
760         if (events.empty()) {
761                 next_event = events.end();
762                 return;
763         }
764
765         if (next_event == events.end()) {
766                 next_event = events.begin();
767         }
768
769         if ((*next_event)->action_sample > _transport_sample) {
770                 next_event = events.begin();
771         }
772
773         for (; next_event != events.end(); ++next_event) {
774                 if ((*next_event)->action_sample >= _transport_sample) {
775                         break;
776                 }
777         }
778 }
779
780 void
781 Session::process_event (SessionEvent* ev)
782 {
783         bool remove = true;
784         bool del = true;
785
786         /* if we're in the middle of a state change (i.e. waiting
787            for the butler thread to complete the non-realtime
788            part of the change), we'll just have to queue this
789            event for a time when the change is complete.
790         */
791
792         if (non_realtime_work_pending()) {
793
794                 /* except locates, which we have the capability to handle */
795
796                 if (ev->type != SessionEvent::Locate) {
797                         immediate_events.insert (immediate_events.end(), ev);
798                         _remove_event (ev);
799                         return;
800                 }
801         }
802
803         DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Processing event: %1 @ %2\n", enum_2_string (ev->type), _transport_sample));
804
805         switch (ev->type) {
806         case SessionEvent::SetLoop:
807                 set_play_loop (ev->yes_or_no, ev->speed);
808                 break;
809
810         case SessionEvent::AutoLoop:
811                 if (play_loop) {
812                         /* roll after locate, do not flush, set "with loop"
813                            true only if we are seamless looping
814                         */
815                         start_locate (ev->target_sample, true, false, Config->get_seamless_loop());
816                 }
817                 remove = false;
818                 del = false;
819                 break;
820
821         case SessionEvent::Locate:
822                 if (ev->yes_or_no) { /* force locate */
823                         /* args: do not roll after locate, do flush, not with loop */
824                         locate (ev->target_sample, false, true, false);
825                 } else {
826                         /* args: do not roll after locate, do flush, not with loop */
827                         start_locate (ev->target_sample, false, true, false);
828                 }
829                 _send_timecode_update = true;
830                 break;
831
832         case SessionEvent::LocateRoll:
833                 if (ev->yes_or_no) {
834                         /* args: roll after locate, do flush, not with loop */
835                         locate (ev->target_sample, true, true, false);
836                 } else {
837                         /* args: roll after locate, do flush, not with loop */
838                         start_locate (ev->target_sample, true, true, false);
839                 }
840                 _send_timecode_update = true;
841                 break;
842
843         case SessionEvent::Skip:
844                 if (Config->get_skip_playback()) {
845                         start_locate (ev->target_sample, true, true, false);
846                         _send_timecode_update = true;
847                 }
848                 remove = false;
849                 del = false;
850                 break;
851
852         case SessionEvent::LocateRollLocate:
853                 // locate is handled by ::request_roll_at_and_return()
854                 _requested_return_sample = ev->target_sample;
855                 request_locate (ev->target2_sample, true);
856                 break;
857
858
859         case SessionEvent::SetTransportSpeed:
860                 set_transport_speed (ev->speed, ev->target_sample, ev->yes_or_no, ev->second_yes_or_no, ev->third_yes_or_no);
861                 break;
862
863         case SessionEvent::SetTransportMaster:
864                 cerr << "Process TMM current request\n";
865                 TransportMasterManager::instance().set_current (ev->transport_master);
866                 break;
867
868         case SessionEvent::PunchIn:
869                 // cerr << "PunchIN at " << transport_sample() << endl;
870                 if (config.get_punch_in() && record_status() == Enabled) {
871                         enable_record ();
872                 }
873                 remove = false;
874                 del = false;
875                 break;
876
877         case SessionEvent::PunchOut:
878                 // cerr << "PunchOUT at " << transport_sample() << endl;
879                 if (config.get_punch_out()) {
880                         step_back_from_record ();
881                 }
882                 remove = false;
883                 del = false;
884                 break;
885
886         case SessionEvent::StopOnce:
887                 if (!non_realtime_work_pending()) {
888                         _clear_event_type (SessionEvent::StopOnce);
889                         stop_transport (ev->yes_or_no);
890                 }
891                 remove = false;
892                 del = false;
893                 break;
894
895         case SessionEvent::RangeStop:
896                 if (!non_realtime_work_pending()) {
897                         stop_transport (ev->yes_or_no);
898                 }
899                 remove = false;
900                 del = false;
901                 break;
902
903         case SessionEvent::RangeLocate:
904                 /* args: roll after locate, do flush, not with loop */
905                 start_locate (ev->target_sample, true, true, false);
906                 remove = false;
907                 del = false;
908                 break;
909
910         case SessionEvent::Overwrite:
911                 overwrite_some_buffers (static_cast<Track*>(ev->ptr));
912                 break;
913
914         case SessionEvent::Audition:
915                 set_audition (ev->region);
916                 // drop reference to region
917                 ev->region.reset ();
918                 break;
919
920         case SessionEvent::SetPlayAudioRange:
921                 set_play_range (ev->audio_range, (ev->speed == 1.0f));
922                 break;
923
924         case SessionEvent::CancelPlayAudioRange:
925                 unset_play_range();
926                 break;
927
928         case SessionEvent::RealTimeOperation:
929                 process_rtop (ev);
930                 del = false; // other side of RT request needs to clean up
931                 break;
932
933         case SessionEvent::AdjustPlaybackBuffering:
934                 schedule_playback_buffering_adjustment ();
935                 break;
936
937         case SessionEvent::AdjustCaptureBuffering:
938                 schedule_capture_buffering_adjustment ();
939                 break;
940
941         case SessionEvent::SetTimecodeTransmission:
942                 g_atomic_int_set (&_suspend_timecode_transmission, ev->yes_or_no ? 0 : 1);
943                 break;
944
945         default:
946           fatal << string_compose(_("Programming error: illegal event type in process_event (%1)"), ev->type) << endmsg;
947                 abort(); /*NOTREACHED*/
948                 break;
949         };
950
951         if (remove) {
952                 del = del && !_remove_event (ev);
953         }
954
955         if (del) {
956                 delete ev;
957         }
958 }
959
960 samplepos_t
961 Session::compute_stop_limit () const
962 {
963         if (!Config->get_stop_at_session_end ()) {
964                 return max_samplepos;
965         }
966
967         if (config.get_external_sync()) {
968                 return max_samplepos;
969         }
970
971         bool const punching_in = (config.get_punch_in () && _locations->auto_punch_location());
972         bool const punching_out = (config.get_punch_out () && _locations->auto_punch_location());
973
974         if (actively_recording ()) {
975                 /* permanently recording */
976                 return max_samplepos;
977         } else if (punching_in && !punching_out) {
978                 /* punching in but never out */
979                 return max_samplepos;
980         } else if (punching_in && punching_out && _locations->auto_punch_location()->end() > current_end_sample()) {
981                 /* punching in and punching out after session end */
982                 return max_samplepos;
983         }
984
985         return current_end_sample ();
986 }
987
988
989
990 /* dedicated thread for signal emission.
991  *
992  * while sending cross-thread signals from the process thread
993  * is fine in general, PBD::Signal's use of boost::function and
994  * boost:bind can produce a vast overhead which is not
995  * acceptable for low latency.
996  *
997  * This works around the issue by moving the boost overhead
998  * out of the RT thread. The overall load is probably higher but
999  * the realtime thread remains unaffected.
1000  */
1001
1002 void
1003 Session::emit_route_signals ()
1004 {
1005         // TODO use RAII to allow using these signals in other places
1006         BatchUpdateStart(); /* EMIT SIGNAL */
1007         boost::shared_ptr<RouteList> r = routes.reader ();
1008         for (RouteList::const_iterator ci = r->begin(); ci != r->end(); ++ci) {
1009                 (*ci)->emit_pending_signals ();
1010         }
1011         BatchUpdateEnd(); /* EMIT SIGNAL */
1012 }
1013
1014 void
1015 Session::emit_thread_start ()
1016 {
1017         if (_rt_thread_active) {
1018                 return;
1019         }
1020         _rt_thread_active = true;
1021
1022         if (pthread_create (&_rt_emit_thread, NULL, emit_thread, this)) {
1023                 _rt_thread_active = false;
1024         }
1025 }
1026
1027 void
1028 Session::emit_thread_terminate ()
1029 {
1030         if (!_rt_thread_active) {
1031                 return;
1032         }
1033         _rt_thread_active = false;
1034
1035         if (pthread_mutex_lock (&_rt_emit_mutex) == 0) {
1036                 pthread_cond_signal (&_rt_emit_cond);
1037                 pthread_mutex_unlock (&_rt_emit_mutex);
1038         }
1039
1040         void *status;
1041         pthread_join (_rt_emit_thread, &status);
1042 }
1043
1044 void *
1045 Session::emit_thread (void *arg)
1046 {
1047         Session *s = static_cast<Session *>(arg);
1048         s->emit_thread_run ();
1049         pthread_exit (0);
1050         return 0;
1051 }
1052
1053 void
1054 Session::emit_thread_run ()
1055 {
1056         pthread_mutex_lock (&_rt_emit_mutex);
1057         while (_rt_thread_active) {
1058                 emit_route_signals();
1059                 pthread_cond_wait (&_rt_emit_cond, &_rt_emit_mutex);
1060         }
1061         pthread_mutex_unlock (&_rt_emit_mutex);
1062 }
1063
1064 bool
1065 Session::follow_transport_master (pframes_t nframes)
1066 {
1067         TransportMasterManager& tmm (TransportMasterManager::instance());
1068
1069         double slave_speed;
1070         samplepos_t slave_transport_sample;
1071         sampleoffset_t delta;
1072
1073         if (tmm.master_invalid_this_cycle()) {
1074                 DEBUG_TRACE (DEBUG::Slave, "session told not to use the transport master this cycle\n");
1075                 goto noroll;
1076         }
1077
1078         slave_speed = tmm.get_current_speed_in_process_context();
1079         slave_transport_sample = tmm.get_current_position_in_process_context ();
1080         delta = _transport_sample - slave_transport_sample;
1081
1082         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()));
1083
1084         track_transport_master (slave_speed, slave_transport_sample);
1085
1086         if (transport_master_tracking_state == Running) {
1087
1088                 if (!actively_recording() && abs (delta) > tmm.current()->resolution()) {
1089                         DEBUG_TRACE (DEBUG::Slave, string_compose ("average slave delta %1 greater than slave resolution %2\n", delta, tmm.current()->resolution()));
1090                         if (micro_locate (-delta) != 0) {
1091                                 DEBUG_TRACE (DEBUG::Slave, "micro-locate didn't work, set no disk output true\n");
1092
1093                                 /* run routes as normal, but no disk output */
1094                                 DiskReader::set_no_disk_output (true);
1095                         }
1096                         return true;
1097                 }
1098
1099                 if (transport_master_tracking_state == Running) {
1100                         /* speed is set, we're locked, and good to go */
1101                         DiskReader::set_no_disk_output (false);
1102                         return true;
1103                 }
1104         }
1105
1106   noroll:
1107         /* don't move at all */
1108         DEBUG_TRACE (DEBUG::Slave, "no roll\n")
1109         no_roll (nframes);
1110         return false;
1111 }
1112
1113 void
1114 Session::track_transport_master (float slave_speed, samplepos_t slave_transport_sample)
1115 {
1116         boost::shared_ptr<TransportMaster> master (TransportMasterManager::instance().current());
1117
1118         assert (master);
1119
1120         DEBUG_TRACE (DEBUG::Slave, string_compose ("session has master tracking state as %1\n", transport_master_tracking_state));
1121
1122         if (slave_speed != 0.0f) {
1123
1124                 /* slave is running */
1125
1126                 switch (transport_master_tracking_state) {
1127                 case Stopped:
1128                         if (master->requires_seekahead()) {
1129                                 master_wait_end = slave_transport_sample + master->seekahead_distance ();
1130                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, but running, requires seekahead to %1\n", master_wait_end));
1131                                 /* we can call locate() here because we are in process context */
1132                                 if (micro_locate (master_wait_end - _transport_sample) != 0) {
1133                                         locate (master_wait_end, false, false);
1134                                 }
1135                                 transport_master_tracking_state = Waiting;
1136
1137                         } else {
1138
1139                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped -> running at %1\n", slave_transport_sample));
1140
1141                                 if (slave_transport_sample != _transport_sample) {
1142                                         DEBUG_TRACE (DEBUG::Slave, string_compose ("require locate to run. eng: %1 -> sl: %2\n", _transport_sample, slave_transport_sample));
1143                                         if (micro_locate (slave_transport_sample - _transport_sample) != 0) {
1144                                                 locate (slave_transport_sample, false, false);
1145                                         }
1146                                 }
1147                                 transport_master_tracking_state = Running;
1148                         }
1149                         break;
1150
1151                 case Waiting:
1152                 default:
1153                         break;
1154                 }
1155
1156                 if (transport_master_tracking_state == Waiting) {
1157
1158                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave waiting at %1\n", slave_transport_sample));
1159
1160                         if (slave_transport_sample >= master_wait_end) {
1161
1162                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave start at %1 vs %2\n", slave_transport_sample, _transport_sample));
1163
1164                                 transport_master_tracking_state = Running;
1165
1166                                 /* now perform a "micro-seek" within the disk buffers to realign ourselves
1167                                    precisely with the master.
1168                                 */
1169
1170                                 if (micro_locate (slave_transport_sample - _transport_sample) != 0) {
1171                                         cerr << "cannot micro-seek\n";
1172                                         /* XXX what? */
1173                                 }
1174                         }
1175                 }
1176
1177                 if (transport_master_tracking_state == Running && _transport_speed == 0.0f) {
1178                         DEBUG_TRACE (DEBUG::Slave, "slave starts transport\n");
1179                         start_transport ();
1180                 }
1181
1182         } else { // slave_speed is 0
1183
1184                 /* slave has stopped */
1185
1186                 if (_transport_speed != 0.0f) {
1187                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stops transport: %1 sample %2 tf %3\n", slave_speed, slave_transport_sample, _transport_sample));
1188                         stop_transport ();
1189                 }
1190
1191                 if (slave_transport_sample != _transport_sample) {
1192                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, move to %1\n", slave_transport_sample));
1193                         force_locate (slave_transport_sample, false);
1194                 }
1195
1196                 reset_slave_state();
1197         }
1198 }
1199
1200 void
1201 Session::reset_slave_state ()
1202 {
1203         transport_master_tracking_state = Stopped;
1204         DiskReader::set_no_disk_output (false);
1205 }