Slightly unpleasant fix for creation of tracks from
[ardour.git] / libs / ardour / track.cc
1 /*
2     Copyright (C) 2006 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 #include "pbd/error.h"
19
20 #include "ardour/amp.h"
21 #include "ardour/audioplaylist.h"
22 #include "ardour/audioregion.h"
23 #include "ardour/audiosource.h"
24 #include "ardour/debug.h"
25 #include "ardour/delivery.h"
26 #include "ardour/diskstream.h"
27 #include "ardour/io_processor.h"
28 #include "ardour/meter.h"
29 #include "ardour/port.h"
30 #include "ardour/processor.h"
31 #include "ardour/route_group_specialized.h"
32 #include "ardour/session.h"
33 #include "ardour/track.h"
34 #include "ardour/utils.h"
35
36 #include "i18n.h"
37
38 using namespace std;
39 using namespace ARDOUR;
40 using namespace PBD;
41
42 Track::Track (Session& sess, string name, Route::Flag flag, TrackMode mode, DataType default_type)
43         : Route (sess, name, flag, default_type)
44         , _saved_meter_point (_meter_point)
45         , _mode (mode)
46         , _monitoring (MonitorAuto)
47         , _rec_enable_control (new RecEnableControllable(*this))
48 {
49         _freeze_record.state = NoFreeze;
50         _declickable = true;
51 }
52
53 Track::~Track ()
54 {
55         DEBUG_TRACE (DEBUG::Destruction, string_compose ("track %1 destructor\n", _name));
56 }
57
58 int
59 Track::init ()
60 {
61         if (Route::init ()) {
62                 return -1;
63         }
64
65         return 0;
66 }
67
68 XMLNode&
69 Track::get_state ()
70 {
71         return state (true);
72 }
73
74 XMLNode&
75 Track::state (bool full)
76 {
77         XMLNode& root (Route::state (full));
78         root.add_property (X_("monitoring"), enum_2_string (_monitoring));
79         root.add_property (X_("saved-meter-point"), enum_2_string (_saved_meter_point));
80         root.add_child_nocopy (_rec_enable_control->get_state());
81         root.add_child_nocopy (_diskstream->get_state ());
82         return root;
83 }       
84
85 int
86 Track::set_state (const XMLNode& node, int version)
87 {
88         if (Route::set_state (node, version)) {
89                 return -1;
90         }
91
92         XMLNode* child;
93
94         if (version >= 3000) {
95                 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
96                         boost::shared_ptr<Diskstream> ds = diskstream_factory (*child);
97                         ds->do_refill_with_alloc ();
98                         set_diskstream (ds);
99                 }
100         }
101
102         /* set rec-enable control *AFTER* setting up diskstream, because it may
103            want to operate on the diskstream as it sets its own state
104         */
105
106         XMLNodeList nlist = node.children();
107         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
108                 child = *niter;
109
110                 XMLProperty* prop;
111                 if (child->name() == Controllable::xml_node_name && (prop = child->property ("name")) != 0) {
112                         if (prop->value() == X_("recenable")) {
113                                 _rec_enable_control->set_state (*child, version);
114                         }
115                 }
116         }
117         
118         const XMLProperty* prop;
119
120         if ((prop = node.property (X_("monitoring"))) != 0) {
121                 _monitoring = MonitorChoice (string_2_enum (prop->value(), _monitoring));
122         } else {
123                 _monitoring = MonitorAuto;
124         }
125
126         if ((prop = node.property (X_("saved-meter-point"))) != 0) {
127                 _saved_meter_point = MeterPoint (string_2_enum (prop->value(), _saved_meter_point));
128         } else {
129                 _saved_meter_point = _meter_point;
130         }
131
132         return 0;
133 }
134
135 XMLNode&
136 Track::get_template ()
137 {
138         return state (false);
139 }
140
141 void
142 Track::toggle_monitor_input ()
143 {
144         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
145                 i->ensure_monitor_input(!i->monitoring_input());
146         }
147 }
148
149 Track::FreezeRecord::~FreezeRecord ()
150 {
151         for (vector<FreezeRecordProcessorInfo*>::iterator i = processor_info.begin(); i != processor_info.end(); ++i) {
152                 delete *i;
153         }
154 }
155
156 Track::FreezeState
157 Track::freeze_state() const
158 {
159         return _freeze_record.state;
160 }
161
162 Track::RecEnableControllable::RecEnableControllable (Track& s)
163         : Controllable (X_("recenable")), track (s)
164 {
165 }
166
167 void
168 Track::RecEnableControllable::set_value (double val)
169 {
170         bool bval = ((val >= 0.5) ? true: false);
171         track.set_record_enabled (bval, this);
172 }
173
174 double
175 Track::RecEnableControllable::get_value (void) const
176 {
177         if (track.record_enabled()) { return 1.0; }
178         return 0.0;
179 }
180
181 bool
182 Track::record_enabled () const
183 {
184         return _diskstream && _diskstream->record_enabled ();
185 }
186
187 bool
188 Track::can_record()
189 {
190         bool will_record = true;
191         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end() && will_record; ++i) {
192                 if (!i->connected())
193                         will_record = false;
194         }
195
196         return will_record;
197 }
198
199 void
200 Track::set_record_enabled (bool yn, void *src)
201 {
202         if (!_session.writable()) {
203                 return;
204         }
205
206         if (_freeze_record.state == Frozen) {
207                 return;
208         }
209
210         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_recenable()) {
211                 _route_group->apply (&Track::set_record_enabled, yn, _route_group);
212                 return;
213         }
214
215         /* keep track of the meter point as it was before we rec-enabled */
216         if (!_diskstream->record_enabled()) {
217                 _saved_meter_point = _meter_point;
218         }
219
220         _diskstream->set_record_enabled (yn);
221
222         if (_diskstream->record_enabled()) {
223                 if (_meter_point != MeterCustom) {
224                         set_meter_point (MeterInput);
225                 }
226         } else {
227                 set_meter_point (_saved_meter_point);
228         }
229
230         _rec_enable_control->Changed ();
231 }
232
233
234 bool
235 Track::set_name (const string& str)
236 {
237         bool ret;
238
239         if (record_enabled() && _session.actively_recording()) {
240                 /* this messes things up if done while recording */
241                 return false;
242         }
243
244         _diskstream->set_name (str);
245
246         /* save state so that the statefile fully reflects any filename changes */
247
248         if ((ret = Route::set_name (str)) == 0) {
249                 _session.save_state ("");
250         }
251
252         return ret;
253 }
254
255 void
256 Track::set_latency_compensation (framecnt_t longest_session_latency)
257 {
258         Route::set_latency_compensation (longest_session_latency);
259         _diskstream->set_roll_delay (_roll_delay);
260 }
261
262 int
263 Track::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool session_state_changing)
264 {
265         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
266         if (!lm.locked()) {
267                 return 0;
268         }
269
270         bool can_record = _session.actively_recording ();
271
272         if (n_outputs().n_total() == 0) {
273                 return 0;
274         }
275
276         if (!_active) {
277                 silence (nframes);
278                 return 0;
279         }
280
281         if (session_state_changing) {
282                 if (_session.transport_speed() != 0.0f) {
283                         /* we're rolling but some state is changing (e.g. our diskstream contents)
284                            so we cannot use them. Be silent till this is over. Don't declick.
285
286                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
287                         */
288                         passthru_silence (start_frame, end_frame, nframes, 0);
289                         return 0;
290                 }
291                 /* we're really not rolling, so we're either delivery silence or actually
292                    monitoring, both of which are safe to do while session_state_changing is true.
293                 */
294         }
295
296         _diskstream->check_record_status (start_frame, can_record);
297
298         bool be_silent;
299
300         if (_have_internal_generator) {
301                 /* since the instrument has no input streams,
302                    there is no reason to send any signal
303                    into the route.
304                 */
305                 be_silent = true;
306         } else {
307                 be_silent = send_silence ();
308         }
309
310         _amp->apply_gain_automation(false);
311
312         if (be_silent) {
313
314                 /* if we're sending silence, but we want the meters to show levels for the signal,
315                    meter right here.
316                 */
317
318                 if (_have_internal_generator) {
319                         passthru_silence (start_frame, end_frame, nframes, 0);
320                 } else {
321                         if (_meter_point == MeterInput) {
322                                 _input->process_input (_meter, start_frame, end_frame, nframes);
323                         }
324                         passthru_silence (start_frame, end_frame, nframes, 0);
325                 }
326
327         } else {
328
329                 /* we're sending signal, but we may still want to meter the input.
330                  */
331
332                 passthru (start_frame, end_frame, nframes, false);
333         }
334
335         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
336                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
337                 if (d) {
338                         d->flush_buffers (nframes, end_frame - start_frame - 1);
339                 }
340         }
341
342         return 0;
343 }
344
345 int
346 Track::silent_roll (pframes_t nframes, framepos_t /*start_frame*/, framepos_t /*end_frame*/, bool& need_butler)
347 {
348         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
349         if (!lm.locked()) {
350                 return 0;
351         }
352
353         if (n_outputs().n_total() == 0 && _processors.empty()) {
354                 return 0;
355         }
356
357         if (!_active) {
358                 silence (nframes);
359                 return 0;
360         }
361
362         _silent = true;
363         _amp->apply_gain_automation(false);
364
365         silence (nframes);
366
367         framecnt_t playback_distance;
368         int const dret = _diskstream->process (_session.transport_frame(), nframes, playback_distance);
369         need_butler = _diskstream->commit (playback_distance);
370         return dret;
371 }
372
373 void
374 Track::set_diskstream (boost::shared_ptr<Diskstream> ds)
375 {
376         _diskstream = ds;
377
378         ds->PlaylistChanged.connect_same_thread (*this, boost::bind (&Track::diskstream_playlist_changed, this));
379         diskstream_playlist_changed ();
380         ds->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Track::diskstream_record_enable_changed, this));
381         ds->SpeedChanged.connect_same_thread (*this, boost::bind (&Track::diskstream_speed_changed, this));
382         ds->AlignmentStyleChanged.connect_same_thread (*this, boost::bind (&Track::diskstream_alignment_style_changed, this));
383 }
384
385 void
386 Track::diskstream_playlist_changed ()
387 {
388         PlaylistChanged (); /* EMIT SIGNAL */
389 }
390
391 void
392 Track::diskstream_record_enable_changed ()
393 {
394         RecordEnableChanged (); /* EMIT SIGNAL */
395 }
396
397 void
398 Track::diskstream_speed_changed ()
399 {
400         SpeedChanged (); /* EMIT SIGNAL */
401 }
402
403 void
404 Track::diskstream_alignment_style_changed ()
405 {
406         AlignmentStyleChanged (); /* EMIT SIGNAL */
407 }
408
409 boost::shared_ptr<Playlist>
410 Track::playlist ()
411 {
412         return _diskstream->playlist ();
413 }
414
415 void
416 Track::monitor_input (bool m)
417 {
418         _diskstream->monitor_input (m);
419 }
420
421 bool
422 Track::destructive () const
423 {
424         return _diskstream->destructive ();
425 }
426
427 list<boost::shared_ptr<Source> > &
428 Track::last_capture_sources ()
429 {
430         return _diskstream->last_capture_sources ();
431 }
432
433 void
434 Track::set_capture_offset ()
435 {
436         _diskstream->set_capture_offset ();
437 }
438
439 list<boost::shared_ptr<Source> >
440 Track::steal_write_sources()
441 {
442         return _diskstream->steal_write_sources ();
443 }
444
445 void
446 Track::reset_write_sources (bool r, bool force)
447 {
448         _diskstream->reset_write_sources (r, force);
449 }
450
451 float
452 Track::playback_buffer_load () const
453 {
454         return _diskstream->playback_buffer_load ();
455 }
456
457 float
458 Track::capture_buffer_load () const
459 {
460         return _diskstream->capture_buffer_load ();
461 }
462
463 int
464 Track::do_refill ()
465 {
466         return _diskstream->do_refill ();
467 }
468
469 int
470 Track::do_flush (RunContext c, bool force)
471 {
472         return _diskstream->do_flush (c, force);
473 }
474
475 void
476 Track::set_pending_overwrite (bool o)
477 {
478         _diskstream->set_pending_overwrite (o);
479 }
480
481 int
482 Track::seek (framepos_t p, bool complete_refill)
483 {
484         return _diskstream->seek (p, complete_refill);
485 }
486
487 bool
488 Track::hidden () const
489 {
490         return _diskstream->hidden ();
491 }
492
493 int
494 Track::can_internal_playback_seek (framepos_t p)
495 {
496         return _diskstream->can_internal_playback_seek (p);
497 }
498
499 int
500 Track::internal_playback_seek (framepos_t p)
501 {
502         return _diskstream->internal_playback_seek (p);
503 }
504
505 void
506 Track::non_realtime_input_change ()
507 {
508         _diskstream->non_realtime_input_change ();
509 }
510
511 void
512 Track::non_realtime_locate (framepos_t p)
513 {
514         _diskstream->non_realtime_locate (p);
515 }
516
517 void
518 Track::non_realtime_set_speed ()
519 {
520         _diskstream->non_realtime_set_speed ();
521 }
522
523 int
524 Track::overwrite_existing_buffers ()
525 {
526         return _diskstream->overwrite_existing_buffers ();
527 }
528
529 framecnt_t
530 Track::get_captured_frames (uint32_t n) const
531 {
532         return _diskstream->get_captured_frames (n);
533 }
534
535 int
536 Track::set_loop (Location* l)
537 {
538         return _diskstream->set_loop (l);
539 }
540
541 void
542 Track::transport_looped (framepos_t p)
543 {
544         _diskstream->transport_looped (p);
545 }
546
547 bool
548 Track::realtime_set_speed (double s, bool g)
549 {
550         return _diskstream->realtime_set_speed (s, g);
551 }
552
553 void
554 Track::transport_stopped_wallclock (struct tm & n, time_t t, bool g)
555 {
556         _diskstream->transport_stopped_wallclock (n, t, g);
557 }
558
559 bool
560 Track::pending_overwrite () const
561 {
562         return _diskstream->pending_overwrite ();
563 }
564
565 double
566 Track::speed () const
567 {
568         return _diskstream->speed ();
569 }
570
571 void
572 Track::prepare_to_stop (framepos_t p)
573 {
574         _diskstream->prepare_to_stop (p);
575 }
576
577 void
578 Track::set_slaved (bool s)
579 {
580         _diskstream->set_slaved (s);
581 }
582
583 ChanCount
584 Track::n_channels ()
585 {
586         return _diskstream->n_channels ();
587 }
588
589 framepos_t
590 Track::get_capture_start_frame (uint32_t n) const
591 {
592         return _diskstream->get_capture_start_frame (n);
593 }
594
595 AlignStyle
596 Track::alignment_style () const
597 {
598         return _diskstream->alignment_style ();
599 }
600
601 AlignChoice
602 Track::alignment_choice () const
603 {
604         return _diskstream->alignment_choice ();
605 }
606
607 framepos_t
608 Track::current_capture_start () const
609 {
610         return _diskstream->current_capture_start ();
611 }
612
613 framepos_t
614 Track::current_capture_end () const
615 {
616         return _diskstream->current_capture_end ();
617 }
618
619 void
620 Track::playlist_modified ()
621 {
622         _diskstream->playlist_modified ();
623 }
624
625 int
626 Track::use_playlist (boost::shared_ptr<Playlist> p)
627 {
628         return _diskstream->use_playlist (p);
629 }
630
631 int
632 Track::use_copy_playlist ()
633 {
634         return _diskstream->use_copy_playlist ();
635 }
636
637 int
638 Track::use_new_playlist ()
639 {
640         return _diskstream->use_new_playlist ();
641 }
642
643 void
644 Track::set_align_style (AlignStyle s, bool force)
645 {
646         _diskstream->set_align_style (s, force);
647 }
648
649 void
650 Track::set_align_choice (AlignChoice s, bool force)
651 {
652         _diskstream->set_align_choice (s, force);
653 }
654
655 PBD::ID const &
656 Track::diskstream_id () const
657 {
658         return _diskstream->id ();
659 }
660
661 void
662 Track::set_block_size (pframes_t n)
663 {
664         Route::set_block_size (n);
665         _diskstream->set_block_size (n);
666 }
667
668 void
669 Track::adjust_playback_buffering ()
670 {
671         if (_diskstream) {
672                 _diskstream->adjust_playback_buffering ();
673         }
674 }
675
676 void
677 Track::adjust_capture_buffering ()
678 {
679         if (_diskstream) {
680                 _diskstream->adjust_capture_buffering ();
681         }
682 }
683
684 bool
685 Track::send_silence () const
686 {
687         bool send_silence;
688
689         if (Config->get_tape_machine_mode()) {
690
691                 /* ADATs work in a strange way..
692                    they monitor input always when stopped.and auto-input is engaged.
693                 */
694                 
695                 if ((Config->get_monitoring_model() == SoftwareMonitoring)
696                     && ((_monitoring & MonitorInput) || (_diskstream->record_enabled()))) {
697                         send_silence = false;
698                 } else {
699                         send_silence = true;
700                 }
701                 
702                 
703         } else {
704                 
705                 /* Other machines switch to input on stop if the track is record enabled,
706                    regardless of the auto input setting (auto input only changes the
707                    monitoring state when the transport is rolling)
708                 */
709                 
710                 if ((Config->get_monitoring_model() == SoftwareMonitoring)
711                     && ((_monitoring & MonitorInput) || 
712                         (!(_monitoring & MonitorDisk) && (_session.config.get_auto_input () || _diskstream->record_enabled())))){
713
714                         DEBUG_TRACE (DEBUG::Monitor, 
715                                      string_compose ("%1: no roll, use silence = FALSE,  monitoring choice %2 recenable %3 sRA %4 autoinput %5\n",
716                                                      name(), enum_2_string (_monitoring), 
717                                                      _diskstream->record_enabled(), _session.actively_recording(),
718                                                      _session.config.get_auto_input()));
719
720                         send_silence = false;
721                 } else {
722                         DEBUG_TRACE (DEBUG::Monitor, 
723                                      string_compose ("%1: no roll, use silence = TRUE,  monitoring choice %2 recenable %3 sRA %4 autoinput %5\n",
724                                                      name(), enum_2_string (_monitoring), 
725                                                      _diskstream->record_enabled(), _session.actively_recording(),
726                                                      _session.config.get_auto_input()));
727                         send_silence = true;
728                 }
729         }
730
731         return send_silence;
732 }
733
734 MonitorState
735 Track::monitoring_state ()
736 {
737         MonitorState ms = MonitoringSilence;
738
739         if (_session.transport_rolling()) {
740                 
741                 /* roll case */
742                 
743                 if (_monitoring & MonitorInput) { // explicitly requested input monitoring
744                         
745                         ms = MonitoringInput;
746
747                 } else if (_monitoring & MonitorDisk) { // explicitly requested disk monitoring
748                         
749                         ms = MonitoringDisk;
750
751                 } else if (_diskstream->record_enabled() && _session.actively_recording()) { // Track actually recording
752                         
753                         ms = MonitoringInput;
754
755                 } else if (_diskstream->record_enabled() && !_session.actively_recording() && _session.config.get_auto_input()) { // Track armed but not recording, with auto input enabled
756                         
757                         ms = MonitoringInput;
758
759                 } else { // Every other state
760                         
761                         ms = MonitoringDisk; 
762
763                 }
764
765         } else {
766
767                 /* no-roll case */
768
769                 if (send_silence()) {
770                         
771                         ms = MonitoringSilence;
772                 } else {
773                         
774                         ms = MonitoringInput;
775                 }
776         }
777
778         return ms;
779 }
780
781 void
782 Track::maybe_declick (BufferSet& bufs, framecnt_t nframes, int declick)
783 {
784         /* never declick if there is an internal generator - we just want it to
785            keep generating sound without interruption.
786
787            ditto if we are monitoring inputs.
788         */
789
790         if (_have_internal_generator || monitoring_choice() == MonitorInput) {
791                 return;
792         }
793
794         if (!declick) {
795                 declick = _pending_declick;
796         }
797
798         if (declick != 0) {
799                 Amp::declick (bufs, nframes, declick);
800         }
801 }
802
803 framecnt_t
804 Track::check_initial_delay (framecnt_t nframes, framecnt_t& transport_frame)
805 {
806         if (_roll_delay > nframes) {
807
808                 _roll_delay -= nframes;
809                 silence_unlocked (nframes);
810                 /* transport frame is not legal for caller to use */
811                 return 0;
812
813         } else if (_roll_delay > 0) {
814
815                 nframes -= _roll_delay;
816                 silence_unlocked (_roll_delay);
817                 transport_frame += _roll_delay;
818
819                 /* shuffle all the port buffers for things that lead "out" of this Route
820                    to reflect that we just wrote _roll_delay frames of silence.
821                 */
822
823                 Glib::RWLock::ReaderLock lm (_processor_lock);
824                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
825                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
826                         if (iop) {
827                                 iop->increment_port_buffer_offset (_roll_delay);
828                         }
829                 }
830                 _output->increment_port_buffer_offset (_roll_delay);
831
832                 _roll_delay = 0;
833
834         }
835
836         return nframes; 
837 }
838
839 void
840 Track::set_monitoring (MonitorChoice mc)
841 {
842         if (mc !=  _monitoring) {
843                 _monitoring = mc;
844                 MonitoringChanged (); /* EMIT SIGNAL */
845         }
846 }
847