fix compose mess, and a number of 64 bit printf specs
[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     $Id$
19 */
20
21 #include <cmath>
22 #include <cerrno>
23 #include <algorithm>
24 #include <unistd.h>
25
26 #include <ardour/timestamps.h>
27
28 #include <pbd/error.h>
29 #include <pbd/atomic.h>
30 #include <pbd/lockmonitor.h>
31
32 #include <ardour/ardour.h>
33 #include <ardour/session.h>
34 #include <ardour/diskstream.h>
35 #include <ardour/audioengine.h>
36 #include <ardour/slave.h>
37 #include <ardour/auditioner.h>
38 #include <ardour/cycles.h>
39 #include <ardour/cycle_timer.h>
40
41 #include "i18n.h"
42
43 using namespace ARDOUR;
44 //using namespace sigc;
45 using namespace std;
46
47 void
48 Session::process (jack_nframes_t nframes)
49 {
50         if (synced_to_jack() && waiting_to_start) {
51                 if ( _engine.transport_state() == AudioEngine::TransportRolling) {
52                         actually_start_transport ();
53                 }
54         }
55
56         if (non_realtime_work_pending()) {
57                 if (atomic_read (&butler_should_do_transport_work) == 0) {
58                         post_transport ();
59                 } 
60         } 
61         
62         (this->*process_function) (nframes);
63 }
64
65 void
66 Session::prepare_diskstreams ()
67 {
68         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
69                 (*i)->prepare ();
70         }
71 }
72
73 int
74 Session::no_roll (jack_nframes_t nframes, jack_nframes_t offset)
75 {
76         jack_nframes_t end_frame = _transport_frame + nframes;
77         int ret = 0;
78         bool declick = get_transport_declick_required();
79
80         if (_click_io) {
81                 _click_io->silence (nframes, offset);
82         }
83
84         /* XXX we're supposed to have the route_lock while doing this.
85            this is really bad ...
86         */
87
88         if (atomic_read (&processing_prohibited)) {
89                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
90                         (*i)->silence (nframes, offset);
91                 }
92                 return 0;
93         }
94
95         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
96                 
97                 if ((*i)->hidden()) {
98                         continue;
99                 }
100                 
101                 (*i)->set_pending_declick (declick);
102                 
103                 if ((*i)->no_roll (nframes, _transport_frame, end_frame, offset, non_realtime_work_pending(), 
104                                    actively_recording(), declick)) {
105                         error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
106                         ret = -1;
107                         break;
108                 }
109         }
110
111         return ret;
112 }
113
114 int
115 Session::process_routes (jack_nframes_t nframes, jack_nframes_t offset)
116 {
117         bool record_active;
118         int  declick = get_transport_declick_required();
119         bool rec_monitors = get_rec_monitors_input();
120
121         if (transport_sub_state & StopPendingCapture) {
122                 /* force a declick out */
123                 declick = -1;
124         }
125
126         record_active = actively_recording(); // || (get_record_enabled() && get_punch_in());
127
128         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
129
130                 int ret;
131
132                 if ((*i)->hidden()) {
133                         continue;
134                 }
135
136                 (*i)->set_pending_declick (declick);
137
138                 if ((ret = (*i)->roll (nframes, _transport_frame, _transport_frame + nframes, offset, declick, record_active, rec_monitors)) < 0) {
139
140                         /* we have to do this here. Route::roll() for an AudioTrack will have called DiskStream::process(),
141                            and the DS will expect DiskStream::commit() to be called. but we're aborting from that
142                            call path, so make sure we release any outstanding locks here before we return failure.
143                         */
144
145                         for (DiskStreamList::iterator ids = diskstreams.begin(); ids != diskstreams.end(); ++ids) {
146                                 (*ids)->recover ();
147                         }
148
149                         stop_transport ();
150                         return -1;
151                 } 
152         }
153
154         return 0;
155 }
156
157 int
158 Session::silent_process_routes (jack_nframes_t nframes, jack_nframes_t offset)
159 {
160         bool record_active = actively_recording();
161         int  declick = get_transport_declick_required();
162         bool rec_monitors = get_rec_monitors_input();
163
164         if (transport_sub_state & StopPendingCapture) {
165                 /* force a declick out */
166                 declick = -1;
167         }
168
169         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
170
171                 int ret;
172
173                 if ((*i)->hidden()) {
174                         continue;
175                 }
176
177                 if ((ret = (*i)->silent_roll (nframes, _transport_frame, _transport_frame + nframes, offset, record_active, rec_monitors)) < 0) {
178                         
179                         /* we have to do this here. Route::roll() for an AudioTrack will have called DiskStream::process(),
180                            and the DS will expect DiskStream::commit() to be called. but we're aborting from that
181                            call path, so make sure we release any outstanding locks here before we return failure.
182                         */
183
184                         for (DiskStreamList::iterator ids = diskstreams.begin(); ids != diskstreams.end(); ++ids) {
185                                 (*ids)->recover ();
186                         }
187
188                         stop_transport ();
189                         return -1;
190                 } 
191         }
192
193         return 0;
194 }
195
196 void
197 Session::commit_diskstreams (jack_nframes_t nframes, bool &needs_butler)
198 {
199         int dret;
200         float pworst = 1.0f;
201         float cworst = 1.0f;
202
203         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
204
205                 if ((*i)->hidden()) {
206                         continue;
207                 }
208                 
209                 /* force all diskstreams not handled by a Route to call do their stuff.
210                  */
211
212                 if ((dret = (*i)->process (_transport_frame, nframes, 0, actively_recording(), get_rec_monitors_input())) == 0) {
213                         if ((*i)->commit (nframes)) {
214                                 needs_butler = true;
215                         }
216
217                 } else if (dret < 0) {
218                         (*i)->recover();
219                 }
220                 
221                 pworst = min (pworst, (*i)->playback_buffer_load());
222                 cworst = min (cworst, (*i)->capture_buffer_load());
223         }
224
225         uint32_t pmin = atomic_read (&_playback_load);
226         uint32_t pminold = atomic_read (&_playback_load_min);
227         uint32_t cmin = atomic_read (&_capture_load);
228         uint32_t cminold = atomic_read (&_capture_load_min);
229
230         atomic_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
231         atomic_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
232         atomic_set (&_playback_load_min, min (pmin, pminold));
233         atomic_set (&_capture_load_min, min (cmin, cminold));
234
235         if (actively_recording()) {
236                 set_dirty();
237         }
238 }
239
240 void
241 Session::process_with_events (jack_nframes_t nframes)
242 {
243         Event* ev;
244         jack_nframes_t this_nframes;
245         jack_nframes_t end_frame;
246         jack_nframes_t offset;
247         bool session_needs_butler = false;
248         jack_nframes_t stop_limit;
249         long           frames_moved;
250
251         if (auditioner) {
252                 auditioner->silence (nframes, 0);
253         }
254
255         while (pending_events.read (&ev, 1) == 1) {
256                 merge_event (ev);
257         }
258
259         /* if we are not in the middle of a state change,
260            and there are immediate events queued up,
261            process them. 
262         */
263
264         while (!non_realtime_work_pending() && !immediate_events.empty()) {
265                 Event *ev = immediate_events.front ();
266                 immediate_events.pop_front ();
267                 process_event (ev);
268         }
269
270         if (!process_can_proceed()) {
271                 no_roll (nframes, 0);
272                 return;
273         }
274                 
275         if (events.empty() || next_event == events.end()) {
276                 process_without_events (nframes);
277                 return;
278         }
279
280         end_frame = _transport_frame + nframes;
281
282         {
283                 TentativeLockMonitor rm (route_lock, __LINE__, __FILE__);
284                 Event* this_event;
285                 Events::iterator the_next_one;
286
287                 if (!rm.locked() || (post_transport_work & (PostTransportLocate|PostTransportStop))) {
288                         no_roll (nframes, 0);
289                         return;
290                 }
291                 
292                 if (!_exporting && _slave) {
293                         if (!follow_slave (nframes, 0)) {
294                                 return;
295                         }
296                 } 
297
298                 if (_transport_speed == 0) {
299                         no_roll (nframes, 0);
300                         return;
301                 }
302
303                 if (actively_recording()) {
304                         stop_limit = max_frames;
305                 } else {
306
307                         if (Config->get_stop_at_session_end()) {
308                                 stop_limit = current_end_frame();
309                         } else {
310                                 stop_limit = max_frames;
311                         }
312                 }
313
314                 if (maybe_stop (stop_limit)) {
315                         no_roll (nframes, 0);
316                         return;
317                 } 
318
319                 this_event = *next_event;
320                 the_next_one = next_event;
321                 ++the_next_one;
322
323                 offset = 0;
324
325                 while (nframes) {
326
327                         if (this_event == 0 || this_event->action_frame > end_frame || this_event->action_frame < _transport_frame) {
328
329                                 this_nframes = nframes;
330                                 
331                         } else {
332                                 
333                                 /* compute nframes to next event */
334
335                                 if (this_event->action_frame < end_frame) {
336                                         this_nframes = nframes - (end_frame - this_event->action_frame);
337                                 } else {
338                                         this_nframes = nframes;
339                                 }
340                         }
341
342                         if (this_nframes) {
343                                 
344                                 click (_transport_frame, nframes, offset);
345                                 
346                                 /* now process frames between now and the first event in this block */
347                                 prepare_diskstreams ();
348
349                                 if (process_routes (this_nframes, offset)) {
350                                         no_roll (nframes, 0);
351                                         return;
352                                 }
353                                 
354                                 commit_diskstreams (this_nframes, session_needs_butler);
355
356                                 nframes -= this_nframes;
357                                 offset += this_nframes;
358                                 
359                                 frames_moved = (jack_nframes_t) floor (_transport_speed * this_nframes);
360                         
361                                 if (frames_moved < 0) {
362                                         decrement_transport_position (-frames_moved);
363                                 } else {
364                                         increment_transport_position (frames_moved);
365                                 }
366
367                                 maybe_stop (stop_limit);
368                                 check_declick_out ();
369                         }
370
371                         /* now handle this event and all others scheduled for the same time */
372                         
373                         while (this_event && this_event->action_frame == _transport_frame) {
374                                 process_event (this_event);
375
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
384                         /* if an event left our state changing, do the right thing */
385
386                         if (non_realtime_work_pending()) {
387                                 no_roll (nframes, offset);
388                                 break;
389                         }
390
391                         /* this is necessary to handle the case of seamless looping */
392                         /* not sure if it will work in conjuction with varispeed */
393                         end_frame = _transport_frame + nframes;
394                         
395                 }
396
397                 set_next_event ();
398
399         } /* implicit release of route lock */
400
401
402         if (session_needs_butler) {
403                 summon_butler ();
404         } 
405         
406         if (!_engine.freewheeling() && send_mtc) {
407                 send_midi_time_code_in_another_thread ();
408         }
409
410         return;
411 }               
412
413 void
414 Session::reset_slave_state ()
415 {
416         average_slave_delta = 1800;
417         delta_accumulator_cnt = 0;
418         have_first_delta_accumulator = false;
419         slave_state = Stopped;
420 }
421
422 bool
423 Session::follow_slave (jack_nframes_t nframes, jack_nframes_t offset)
424 {
425         float slave_speed;
426         jack_nframes_t slave_transport_frame;
427         jack_nframes_t this_delta;
428         int dir;
429         bool starting;
430
431         if (!_slave->ok()) {
432                 stop_transport ();
433                 set_slave_source (None, 0);
434                 goto noroll;
435         }
436         
437         _slave->speed_and_position (slave_speed, slave_transport_frame);
438
439         if (!_slave->locked()) {
440                 goto noroll;
441         }
442
443         if (slave_transport_frame > _transport_frame) {
444                 this_delta = slave_transport_frame - _transport_frame;
445                 dir = 1;
446         } else {
447                 this_delta = _transport_frame - slave_transport_frame;
448                 dir = -1;
449         }
450
451         if ((starting = _slave->starting())) {
452                 slave_speed = 0.0f;
453         }
454
455 #if 0
456         cerr << "delta = " << (int) (dir * this_delta)
457              << " speed = " << slave_speed 
458              << " ts = " << _transport_speed 
459              << " M@"<< slave_transport_frame << " S@" << _transport_frame 
460              << " avgdelta = " << average_slave_delta 
461              << endl;
462 #endif  
463
464         if (Config->get_timecode_source_is_synced()) {
465
466                 /* if the TC source is synced, then we assume that its 
467                    speed is binary: 0.0 or 1.0
468                 */
469
470                 if (slave_speed != 0.0f) {
471                         slave_speed = 1.0f;
472                 } 
473
474         } else {
475
476                 /* TC source is able to drift relative to us (slave)
477                    so we need to keep track of the drift and adjust
478                    our speed to remain locked.
479                 */
480
481                 if (delta_accumulator_cnt >= delta_accumulator_size) {
482                         have_first_delta_accumulator = true;
483                         delta_accumulator_cnt = 0;
484                 }
485
486                 if (delta_accumulator_cnt != 0 || this_delta < _current_frame_rate) {
487                         delta_accumulator[delta_accumulator_cnt++] = dir*this_delta;
488                 }
489                 
490                 if (have_first_delta_accumulator) {
491                         average_slave_delta = 0;
492                         for (int i = 0; i < delta_accumulator_size; ++i) {
493                                 average_slave_delta += delta_accumulator[i];
494                         }
495                         average_slave_delta /= delta_accumulator_size;
496                         if (average_slave_delta < 0) {
497                                 average_dir = -1;
498                                 average_slave_delta = -average_slave_delta;
499                         } else {
500                                 average_dir = 1;
501                         }
502                         // cerr << "avgdelta = " << average_slave_delta*average_dir << endl;
503                 }
504         }
505
506         if (slave_speed != 0.0f) {
507
508                 /* slave is running */
509
510                 switch (slave_state) {
511                 case Stopped:
512                         if (_slave->requires_seekahead()) {
513                                 slave_wait_end = slave_transport_frame + _current_frame_rate;
514                                 locate (slave_wait_end, false, false);
515                                 slave_state = Waiting;
516                                 starting = true;
517
518                         } else {
519
520                                 slave_state = Running;
521
522                                 Location* al = _locations.auto_loop_location();
523
524                                 if (al && auto_loop && (slave_transport_frame < al->start() || slave_transport_frame > al->end())) {
525                                         // cancel looping
526                                         request_auto_loop(false);
527                                 }
528
529                                 if (slave_transport_frame != _transport_frame) {
530                                         locate (slave_transport_frame, false, false);
531                                 }
532                         }
533                         break;
534
535                 case Waiting:
536                         break;
537
538                 default:
539                         break;
540
541                 }
542
543                 if (slave_state == Waiting) {
544
545                         // cerr << "waiting at " << slave_transport_frame << endl;
546
547                         if (slave_transport_frame >= slave_wait_end) {
548                                 // cerr << "\tstart at " << _transport_frame << endl;
549                                 slave_state = Running;
550
551                                 bool ok = true;
552                                 jack_nframes_t frame_delta = slave_transport_frame - _transport_frame;
553                                 
554                                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
555                                         if (!(*i)->can_internal_playback_seek (frame_delta)) {
556                                                 ok = false;
557                                                 break;
558                                         }
559                                 }
560
561                                 if (ok) {
562                                         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
563                                                 (*i)->internal_playback_seek (frame_delta);
564                                         }
565                                         _transport_frame += frame_delta;
566                                        
567                                 } else {
568                                         // cerr << "cannot micro-seek\n";
569                                         /* XXX what? */
570                                 }
571
572                                 memset (delta_accumulator, 0, sizeof (jack_nframes_t) * delta_accumulator_size);
573                                 average_slave_delta = 0;
574                                 this_delta = 0;
575                         }
576                 }
577                 
578                 if (slave_state == Running && _transport_speed == 0.0f) {
579                         
580                         // cerr << "slave starts transport\n";
581                         
582                         start_transport ();
583                 } 
584
585         } else {
586
587                 /* slave has stopped */
588
589                 if (_transport_speed != 0.0f) {
590
591                         // cerr << "slave stops transport: " << slave_speed << " frame: " << slave_transport_frame 
592                         // << " tf = " << _transport_frame
593                         // << endl;
594                         
595                         if (_slave_type == JACK) {
596                                 last_stop_frame = _transport_frame;
597                         }
598
599                         stop_transport();
600                 }
601
602                 if (slave_transport_frame != _transport_frame) {
603                         // cerr << "slave stopped, move to " << slave_transport_frame << endl;
604                         force_locate (slave_transport_frame, false);
605                 }
606
607                 slave_state = Stopped;
608         }
609
610         if (slave_state == Running && !Config->get_timecode_source_is_synced()) {
611
612
613                 if (_transport_speed != 0.0f) {
614                         
615                         /* 
616                            note that average_dir is +1 or -1 
617                         */
618                         
619                         const float adjust_seconds = 1.0f;
620                         float delta;
621
622                         //if (average_slave_delta == 0) {
623                                 delta = this_delta;
624                                 delta *= dir;
625 //                      } else {
626 //                              delta = average_slave_delta;
627 //                              delta *= average_dir;
628 //                      }
629
630                         float adjusted_speed = slave_speed +
631                                 (delta / (adjust_seconds * _current_frame_rate));
632                         
633                         // cerr << "adjust using " << delta
634                         // << " towards " << adjusted_speed
635                         // << " ratio = " << adjusted_speed / slave_speed
636                         // << " current = " << _transport_speed
637                         // << " slave @ " << slave_speed
638                         // << endl;
639                         
640                         request_transport_speed (adjusted_speed);
641                         
642 #if 1
643                         if ((jack_nframes_t) average_slave_delta > _slave->resolution()) {
644                                 // cerr << "not locked\n";
645                                 goto silent_motion;
646                         }
647 #endif
648                 }
649         } 
650
651         if (!starting && !non_realtime_work_pending()) {
652                 /* speed is set, we're locked, and good to go */
653                 return true;
654         }
655
656   silent_motion:
657
658         if (slave_speed && _transport_speed) {
659
660                 /* something isn't right, but we should move with the master
661                    for now.
662                 */
663
664                 bool need_butler;
665
666                 prepare_diskstreams ();
667                 silent_process_routes (nframes, offset);
668                 commit_diskstreams (nframes, need_butler);
669
670                 if (need_butler) {
671                         summon_butler ();
672                 }
673                 
674                 jack_nframes_t frames_moved = (long) floor (_transport_speed * nframes);
675                 
676                 if (frames_moved < 0) {
677                         decrement_transport_position (-frames_moved);
678                 } else {
679                         increment_transport_position (frames_moved);
680                 }
681                 
682                 jack_nframes_t stop_limit;
683                 
684                 if (actively_recording()) {
685                         stop_limit = max_frames;
686                 } else {
687                         if (Config->get_stop_at_session_end()) {
688                                 stop_limit = current_end_frame();
689                         } else {
690                                 stop_limit = max_frames;
691                         }
692                 }
693
694                 maybe_stop (stop_limit);
695         }
696
697   noroll:
698         /* don't move at all */
699         no_roll (nframes, 0);
700         return false;
701 }
702
703 void
704 Session::process_without_events (jack_nframes_t nframes)
705 {
706         bool session_needs_butler = false;
707         jack_nframes_t stop_limit;
708         long frames_moved;
709         
710         {
711                 TentativeLockMonitor rm (route_lock, __LINE__, __FILE__);
712
713                 if (!rm.locked() || (post_transport_work & (PostTransportLocate|PostTransportStop))) {
714                         no_roll (nframes, 0);
715                         return;
716                 }
717
718                 if (!_exporting && _slave) {
719                         if (!follow_slave (nframes, 0)) {
720                                 return;
721                         }
722                 } 
723
724                 if (_transport_speed == 0) {
725                         no_roll (nframes, 0);
726                         return;
727                 }
728                 
729                 if (actively_recording()) {
730                         stop_limit = max_frames;
731                 } else {
732                         if (Config->get_stop_at_session_end()) {
733                                 stop_limit = current_end_frame();
734                         } else {
735                                 stop_limit = max_frames;
736                         }
737                 }
738                 
739                 if (maybe_stop (stop_limit)) {
740                         no_roll (nframes, 0);
741                         return;
742                 } 
743
744                 click (_transport_frame, nframes, 0);
745
746                 prepare_diskstreams ();
747         
748                 frames_moved = (long) floor (_transport_speed * nframes);
749
750                 if (process_routes (nframes, 0)) {
751                         no_roll (nframes, 0);
752                         return;
753                 }
754
755                 commit_diskstreams (nframes, session_needs_butler);
756
757                 if (frames_moved < 0) {
758                         decrement_transport_position (-frames_moved);
759                 } else {
760                         increment_transport_position (frames_moved);
761                 }
762                 
763                 maybe_stop (stop_limit);
764                 check_declick_out ();
765
766         } /* implicit release of route lock */
767
768         if (session_needs_butler) {
769                 summon_butler ();
770         } 
771         
772         if (!_engine.freewheeling() && send_mtc) {
773                 send_midi_time_code_in_another_thread ();
774         }
775
776         return;
777 }               
778
779 void
780 Session::process_audition (jack_nframes_t nframes)
781 {
782         TentativeLockMonitor rm (route_lock, __LINE__, __FILE__);
783         Event* ev;
784
785         if (rm.locked()) {
786                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
787                         if (!(*i)->hidden()) {
788                                 (*i)->silence (nframes, 0);
789                         }
790                 }
791         }
792         
793         if (auditioner->play_audition (nframes) > 0) {
794                 summon_butler ();
795         } 
796
797         while (pending_events.read (&ev, 1) == 1) {
798                 merge_event (ev);
799         }
800
801         /* if we are not in the middle of a state change,
802            and there are immediate events queued up,
803            process them. 
804         */
805
806         while (!non_realtime_work_pending() && !immediate_events.empty()) {
807                 Event *ev = immediate_events.front ();
808                 immediate_events.pop_front ();
809                 process_event (ev);
810         }
811
812         if (!auditioner->active()) {
813                 process_function = &Session::process_with_events;
814         }
815 }
816