globally change all use of "frame" to refer to audio into "sample".
[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/audioengine.h"
22 #include "ardour/audiofilesource.h"
23 #include "ardour/audioregion.h"
24 #include "ardour/debug.h"
25 #include "ardour/delivery.h"
26 #include "ardour/disk_reader.h"
27 #include "ardour/disk_writer.h"
28 #include "ardour/event_type_map.h"
29 #include "ardour/io_processor.h"
30 #include "ardour/meter.h"
31 #include "ardour/midi_region.h"
32 #include "ardour/monitor_control.h"
33 #include "ardour/playlist.h"
34 #include "ardour/playlist_factory.h"
35 #include "ardour/port.h"
36 #include "ardour/processor.h"
37 #include "ardour/profile.h"
38 #include "ardour/region_factory.h"
39 #include "ardour/record_enable_control.h"
40 #include "ardour/record_safe_control.h"
41 #include "ardour/route_group_specialized.h"
42 #include "ardour/session.h"
43 #include "ardour/session_playlists.h"
44 #include "ardour/smf_source.h"
45 #include "ardour/track.h"
46 #include "ardour/types_convert.h"
47 #include "ardour/utils.h"
48
49 #include "pbd/i18n.h"
50
51 using namespace std;
52 using namespace ARDOUR;
53 using namespace PBD;
54
55 Track::Track (Session& sess, string name, PresentationInfo::Flag flag, TrackMode mode, DataType default_type)
56         : Route (sess, name, flag, default_type)
57         , _saved_meter_point (_meter_point)
58         , _mode (mode)
59         , _alignment_choice (Automatic)
60 {
61         _freeze_record.state = NoFreeze;
62         _declickable = true;
63
64 }
65
66 Track::~Track ()
67 {
68         DEBUG_TRACE (DEBUG::Destruction, string_compose ("track %1 destructor\n", _name));
69
70         if (_disk_reader) {
71                 _disk_reader->set_route (boost::shared_ptr<Route>());
72                 _disk_reader.reset ();
73         }
74
75         if (_disk_writer) {
76                 _disk_writer->set_route (boost::shared_ptr<Route>());
77                 _disk_writer.reset ();
78         }
79 }
80
81 int
82 Track::init ()
83 {
84         if (Route::init ()) {
85                 return -1;
86         }
87
88         DiskIOProcessor::Flag dflags = DiskIOProcessor::Recordable;
89
90         if (_mode == Destructive && !Profile->get_trx()) {
91                 dflags = DiskIOProcessor::Flag (dflags | DiskIOProcessor::Destructive);
92         } else if (_mode == NonLayered){
93                 dflags = DiskIOProcessor::Flag(dflags | DiskIOProcessor::NonLayered);
94         }
95
96         _disk_reader.reset (new DiskReader (_session, name(), dflags));
97         _disk_reader->set_block_size (_session.get_block_size ());
98         _disk_reader->set_route (boost::dynamic_pointer_cast<Route> (shared_from_this()));
99
100         _disk_writer.reset (new DiskWriter (_session, name(), dflags));
101         _disk_writer->set_block_size (_session.get_block_size ());
102         _disk_writer->set_route (boost::dynamic_pointer_cast<Route> (shared_from_this()));
103
104         use_new_playlist (data_type());
105
106         boost::shared_ptr<Route> rp (boost::dynamic_pointer_cast<Route> (shared_from_this()));
107         boost::shared_ptr<Track> rt = boost::dynamic_pointer_cast<Track> (rp);
108
109         _record_enable_control.reset (new RecordEnableControl (_session, EventTypeMap::instance().to_symbol (RecEnableAutomation), *this));
110         add_control (_record_enable_control);
111
112         _record_safe_control.reset (new RecordSafeControl (_session, EventTypeMap::instance().to_symbol (RecSafeAutomation), *this));
113         add_control (_record_safe_control);
114
115         _monitoring_control.reset (new MonitorControl (_session, EventTypeMap::instance().to_symbol (MonitoringAutomation), *this));
116         add_control (_monitoring_control);
117
118         _session.config.ParameterChanged.connect_same_thread (*this, boost::bind (&Track::parameter_changed, this, _1));
119
120         _monitoring_control->Changed.connect_same_thread (*this, boost::bind (&Track::monitoring_changed, this, _1, _2));
121         _record_safe_control->Changed.connect_same_thread (*this, boost::bind (&Track::record_safe_changed, this, _1, _2));
122         _record_enable_control->Changed.connect_same_thread (*this, boost::bind (&Track::record_enable_changed, this, _1, _2));
123
124         _input->changed.connect_same_thread (*this, boost::bind (&Track::input_changed, this));
125
126         return 0;
127 }
128
129 void
130 Track::input_changed ()
131 {
132         if (_disk_writer && _alignment_choice == Automatic) {
133                 set_align_choice_from_io ();
134         }
135 }
136
137 XMLNode&
138 Track::get_state ()
139 {
140         return state (true);
141 }
142
143 XMLNode&
144 Track::state (bool full)
145 {
146         XMLNode& root (Route::state (full));
147
148         if (_playlists[DataType::AUDIO]) {
149                 root.set_property (X_("audio-playlist"), _playlists[DataType::AUDIO]->id().to_s());
150         }
151
152         if (_playlists[DataType::MIDI]) {
153                 root.set_property (X_("midi-playlist"), _playlists[DataType::MIDI]->id().to_s());
154         }
155
156         root.add_child_nocopy (_monitoring_control->get_state ());
157         root.add_child_nocopy (_record_safe_control->get_state ());
158         root.add_child_nocopy (_record_enable_control->get_state ());
159
160         root.set_property (X_("saved-meter-point"), _saved_meter_point);
161         root.set_property (X_("alignment-choice"), _alignment_choice);
162
163         return root;
164 }
165
166 int
167 Track::set_state (const XMLNode& node, int version)
168 {
169         if (Route::set_state (node, version)) {
170                 return -1;
171         }
172
173         XMLNode* child;
174
175         if (version >= 3000 && version < 4000) {
176                 if ((child = find_named_node (node, X_("Diskstream"))) != 0) {
177                         /* XXX if we remember anything from stored DiskStream
178                            state (older Ardour versions) that is needed by a
179                            DiskReader or DiskWriter, we should cook up a new
180                            XMLNode here, populate it with that information
181                            (child nodes, properties, etc.) and then call
182                            ::set_state() on the writer/reader.
183
184                            But at present (June 2017), there's no such state.
185                         */
186                 }
187         }
188
189         std::string playlist_id;
190
191         if (node.get_property (X_("audio-playlist"), playlist_id)) {
192                 find_and_use_playlist (DataType::AUDIO, PBD::ID (playlist_id));
193         }
194
195         if (node.get_property (X_("midi-playlist"), playlist_id)) {
196                 find_and_use_playlist (DataType::MIDI, PBD::ID (playlist_id));
197         }
198
199         XMLNodeList nlist = node.children();
200         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
201                 child = *niter;
202
203                 if (child->name() == Controllable::xml_node_name) {
204                         std::string name;
205                         if (!child->get_property ("name", name)) {
206                                 continue;
207                         }
208
209                         if (name == _record_enable_control->name()) {
210                                 _record_enable_control->set_state (*child, version);
211                         } else if (name == _record_safe_control->name()) {
212                                 _record_safe_control->set_state (*child, version);
213                         } else if (name == _monitoring_control->name()) {
214                                 _monitoring_control->set_state (*child, version);
215                         }
216                 }
217         }
218
219         if (!node.get_property (X_("saved-meter-point"), _saved_meter_point)) {
220                 _saved_meter_point = _meter_point;
221         }
222
223
224         AlignChoice ac;
225
226         if (node.get_property (X_("alignment-choice"), ac)) {
227                 set_align_choice (ac, true);
228         }
229
230         return 0;
231 }
232
233 XMLNode&
234 Track::get_template ()
235 {
236         return state (false);
237 }
238
239 Track::FreezeRecord::~FreezeRecord ()
240 {
241         for (vector<FreezeRecordProcessorInfo*>::iterator i = processor_info.begin(); i != processor_info.end(); ++i) {
242                 delete *i;
243         }
244 }
245
246 Track::FreezeState
247 Track::freeze_state() const
248 {
249         return _freeze_record.state;
250 }
251
252 bool
253 Track::can_record()
254 {
255         bool will_record = true;
256         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end() && will_record; ++i) {
257                 if (!i->connected())
258                         will_record = false;
259         }
260
261         return will_record;
262 }
263
264 int
265 Track::prep_record_enabled (bool yn)
266 {
267         if (yn && _record_safe_control->get_value()) {
268                 return -1;
269         }
270
271         if (!can_be_record_enabled()) {
272                 return -1;
273         }
274
275         /* keep track of the meter point as it was before we rec-enabled */
276         if (!_disk_writer->record_enabled()) {
277                 _saved_meter_point = _meter_point;
278         }
279
280         bool will_follow;
281
282         if (yn) {
283                 will_follow = _disk_writer->prep_record_enable ();
284         } else {
285                 will_follow = _disk_writer->prep_record_disable ();
286         }
287
288         if (will_follow) {
289                 if (yn) {
290                         if (_meter_point != MeterCustom) {
291                                 set_meter_point (MeterInput);
292                         }
293                 } else {
294                         set_meter_point (_saved_meter_point);
295                 }
296         }
297
298         return 0;
299 }
300
301 void
302 Track::record_enable_changed (bool, Controllable::GroupControlDisposition)
303 {
304         _disk_writer->set_record_enabled (_record_enable_control->get_value());
305 }
306
307 void
308 Track::record_safe_changed (bool, Controllable::GroupControlDisposition)
309 {
310         _disk_writer->set_record_safe (_record_safe_control->get_value());
311 }
312
313 bool
314 Track::can_be_record_safe ()
315 {
316         return !_record_enable_control->get_value() && _disk_writer && _session.writable() && (_freeze_record.state != Frozen);
317 }
318
319 bool
320 Track::can_be_record_enabled ()
321 {
322         return !_record_safe_control->get_value() && _disk_writer && !_disk_writer->record_safe() && _session.writable() && (_freeze_record.state != Frozen);
323 }
324
325 void
326 Track::parameter_changed (string const & p)
327 {
328         if (p == "track-name-number") {
329                 resync_track_name ();
330         }
331         else if (p == "track-name-take") {
332                 resync_track_name ();
333         }
334         else if (p == "take-name") {
335                 if (_session.config.get_track_name_take()) {
336                         resync_track_name ();
337                 }
338         }
339 }
340
341 void
342 Track::resync_track_name ()
343 {
344         set_name(name());
345 }
346
347 bool
348 Track::set_name (const string& str)
349 {
350         bool ret;
351
352         if (str.empty ()) {
353                 return false;
354         }
355
356         if (_record_enable_control->get_value()) {
357                 /* when re-arm'ed the file (named after the track) is already ready to rolll */
358                 return false;
359         }
360
361         string diskstream_name = "";
362         if (_session.config.get_track_name_take () && !_session.config.get_take_name ().empty()) {
363                 // Note: any text is fine, legalize_for_path() fixes this later
364                 diskstream_name += _session.config.get_take_name ();
365                 diskstream_name += "_";
366         }
367         const int64_t tracknumber = track_number();
368         if (tracknumber > 0 && _session.config.get_track_name_number()) {
369                 char num[64], fmt[10];
370                 snprintf(fmt, sizeof(fmt), "%%0%d" PRId64, _session.track_number_decimals());
371                 snprintf(num, sizeof(num), fmt, tracknumber);
372                 diskstream_name += num;
373                 diskstream_name += "_";
374         }
375         diskstream_name += str;
376
377         if (diskstream_name == _diskstream_name) {
378                 return true;
379         }
380         _diskstream_name = diskstream_name;
381
382         _disk_writer->set_write_source_name (diskstream_name);
383
384         boost::shared_ptr<Track> me = boost::dynamic_pointer_cast<Track> (shared_from_this ());
385
386         if (_playlists[data_type()]->all_regions_empty () && _session.playlists->playlists_for_track (me).size() == 1) {
387                 /* Only rename the diskstream (and therefore the playlist) if
388                    a) the playlist has never had a region added to it and
389                    b) there is only one playlist for this track.
390
391                    If (a) is not followed, people can get confused if, say,
392                    they have notes about a playlist with a given name and then
393                    it changes (see mantis #4759).
394
395                    If (b) is not followed, we rename the current playlist and not
396                    the other ones, which is a bit confusing (see mantis #4977).
397                 */
398                 _disk_reader->set_name (str);
399                 _disk_writer->set_name (str);
400         }
401
402         for (uint32_t n = 0; n < DataType::num_types; ++n) {
403                 if (_playlists[n]) {
404                         _playlists[n]->set_name (str);
405                 }
406         }
407
408         /* save state so that the statefile fully reflects any filename changes */
409
410         if ((ret = Route::set_name (str)) == 0) {
411                 _session.save_state ("");
412         }
413
414         return ret;
415 }
416
417 void
418 Track::set_latency_compensation (samplecnt_t longest_session_latency)
419 {
420         Route::set_latency_compensation (longest_session_latency);
421         _disk_reader->set_roll_delay (_roll_delay);
422 }
423
424 int
425 Track::no_roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool session_state_changing)
426 {
427         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
428
429         if (!lm.locked()) {
430                 return 0;
431         }
432
433         bool can_record = _session.actively_recording ();
434
435         /* no outputs? nothing to do ... what happens if we have sends etc. ? */
436
437         if (n_outputs().n_total() == 0 && !ARDOUR::Profile->get_mixbus()) {
438                 //Note: Mixbus has its own output mechanism, so we should operate even if no explicit outputs are assigned
439                 return 0;
440         }
441
442         /* not active ... do the minimum possible by just outputting silence */
443
444         if (!_active) {
445                 silence (nframes);
446                 if (_meter_point == MeterInput && ((_monitoring_control->monitoring_choice() & MonitorInput) || _disk_writer->record_enabled())) {
447                         _meter->reset();
448                 }
449                 return 0;
450         }
451
452         if (session_state_changing) {
453                 if (_session.transport_speed() != 0.0f) {
454                         /* we're rolling but some state is changing (e.g. our
455                            disk reader contents) so we cannot use them. Be
456                            silent till this is over. Don't declick.
457
458                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
459                         */
460                         passthru_silence (start_sample, end_sample, nframes, 0);
461                         return 0;
462                 }
463                 /* we're really not rolling, so we're either delivery silence or actually
464                    monitoring, both of which are safe to do while session_state_changing is true.
465                 */
466         }
467
468         _disk_writer->check_record_status (start_sample, can_record);
469
470         bool be_silent;
471
472         MonitorState const s = monitoring_state ();
473         /* we are not rolling, so be silent even if we are monitoring disk, as there
474            will be no disk data coming in.
475         */
476         switch (s) {
477         case MonitoringSilence:
478                 be_silent = true;
479                 break;
480         case MonitoringDisk:
481                 be_silent = true;
482                 break;
483         case MonitoringInput:
484                 be_silent = false;
485                 break;
486         default:
487                 be_silent = false;
488                 break;
489         }
490
491         //if we have an internal generator, let it play regardless of monitoring state
492         if (_have_internal_generator) {
493                 be_silent = false;
494         }
495
496         _amp->apply_gain_automation (false);
497
498         /* if have_internal_generator, or .. */
499
500         if (be_silent) {
501
502                 if (_meter_point == MeterInput) {
503                         /* still need input monitoring and metering */
504
505                         bool const track_rec = _disk_writer->record_enabled ();
506                         bool const auto_input = _session.config.get_auto_input ();
507                         bool const software_monitor = Config->get_monitoring_model() == SoftwareMonitoring;
508                         bool const tape_machine_mode = Config->get_tape_machine_mode ();
509                         bool no_meter = false;
510
511                         /* this needs a proper K-map
512                          * and should be separated into a function similar to monitoring_state()
513                          * that also handles roll() states in audio_track.cc, midi_track.cc and route.cc
514                          *
515                          * see http://www.oofus.co.uk/ardour/Ardour3MonitorModesV3.pdf
516                          */
517                         if (!auto_input && !track_rec) {
518                                 no_meter=true;
519                         }
520                         else if (tape_machine_mode && !track_rec && auto_input) {
521                                 no_meter=true;
522                         }
523                         else if (!software_monitor && tape_machine_mode && !track_rec) {
524                                 no_meter=true;
525                         }
526                         else if (!software_monitor && !tape_machine_mode && !track_rec && !auto_input) {
527                                 no_meter=true;
528                         }
529
530                         if (no_meter) {
531                                 BufferSet& bufs (_session.get_silent_buffers (n_process_buffers()));
532                                 _meter->run (bufs, start_sample, end_sample, 1.0, nframes, true);
533                                 _input->process_input (boost::shared_ptr<Processor>(), start_sample, end_sample, _session.transport_speed(), nframes);
534                         } else {
535                                 _input->process_input (_meter, start_sample, end_sample, _session.transport_speed(), nframes);
536                         }
537                 }
538
539                 passthru_silence (start_sample, end_sample, nframes, 0);
540
541         } else {
542
543                 BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
544
545                 fill_buffers_with_input (bufs, _input, nframes);
546
547                 if (_meter_point == MeterInput) {
548                         _meter->run (bufs, start_sample, end_sample, _session.transport_speed(), nframes, true);
549                 }
550
551                 passthru (bufs, start_sample, end_sample, nframes, false);
552         }
553
554         flush_processor_buffers_locked (nframes);
555
556         return 0;
557 }
558
559 boost::shared_ptr<Playlist>
560 Track::playlist ()
561 {
562         return _playlists[data_type()];
563 }
564
565 void
566 Track::request_input_monitoring (bool m)
567 {
568         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
569                 AudioEngine::instance()->request_input_monitoring ((*i)->name(), m);
570         }
571 }
572
573 void
574 Track::ensure_input_monitoring (bool m)
575 {
576         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
577                 AudioEngine::instance()->ensure_input_monitoring ((*i)->name(), m);
578         }
579 }
580
581 bool
582 Track::destructive () const
583 {
584         return _disk_writer->destructive ();
585 }
586
587 list<boost::shared_ptr<Source> > &
588 Track::last_capture_sources ()
589 {
590         return _disk_writer->last_capture_sources ();
591 }
592
593 void
594 Track::update_latency_information ()
595 {
596         Glib::Threads::RWLock::ReaderLock lr (_processor_lock);
597         samplecnt_t chain_latency = _input->latency ();
598
599         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
600                 (*p)->set_input_latency (chain_latency);
601                 chain_latency += (*p)->signal_latency ();
602         }
603 }
604
605 std::string
606 Track::steal_write_source_name()
607 {
608         return _disk_writer->steal_write_source_name ();
609 }
610
611 void
612 Track::reset_write_sources (bool r, bool force)
613 {
614         _disk_writer->reset_write_sources (r, force);
615 }
616
617 float
618 Track::playback_buffer_load () const
619 {
620         return _disk_reader->buffer_load ();
621 }
622
623 float
624 Track::capture_buffer_load () const
625 {
626         return _disk_writer->buffer_load ();
627 }
628
629 int
630 Track::do_refill ()
631 {
632         return _disk_reader->do_refill ();
633 }
634
635 int
636 Track::do_flush (RunContext c, bool force)
637 {
638         return _disk_writer->do_flush (c, force);
639 }
640
641 void
642 Track::set_pending_overwrite (bool o)
643 {
644         _disk_reader->set_pending_overwrite (o);
645 }
646
647 int
648 Track::seek (samplepos_t p, bool complete_refill)
649 {
650         if (_disk_reader->seek (p, complete_refill)) {
651                 return -1;
652         }
653         return _disk_writer->seek (p, complete_refill);
654 }
655
656 int
657 Track::can_internal_playback_seek (samplecnt_t p)
658 {
659         return _disk_reader->can_internal_playback_seek (p);
660 }
661
662 int
663 Track::internal_playback_seek (samplecnt_t p)
664 {
665         return _disk_reader->internal_playback_seek (p);
666 }
667
668 void
669 Track::non_realtime_locate (samplepos_t p)
670 {
671         Route::non_realtime_locate (p);
672
673         if (!is_private_route()) {
674                 /* don't waste i/o cycles and butler calls
675                    for private tracks (e.g.auditioner)
676                 */
677                 _disk_reader->non_realtime_locate (p);
678                 _disk_writer->non_realtime_locate (p);
679         }
680 }
681
682 void
683 Track::non_realtime_speed_change ()
684 {
685         _disk_reader->non_realtime_speed_change ();
686 }
687
688 int
689 Track::overwrite_existing_buffers ()
690 {
691         return _disk_reader->overwrite_existing_buffers ();
692 }
693
694 samplecnt_t
695 Track::get_captured_samples (uint32_t n) const
696 {
697         return _disk_writer->get_captured_samples (n);
698 }
699
700 int
701 Track::set_loop (Location* l)
702 {
703         if (_disk_reader->set_loop (l)) {
704                 return -1;
705         }
706         return _disk_writer->set_loop (l);
707 }
708
709 void
710 Track::transport_looped (samplepos_t p)
711 {
712         return _disk_writer->transport_looped (p);
713 }
714
715 bool
716 Track::realtime_speed_change ()
717 {
718         if (_disk_reader->realtime_speed_change ()) {
719                 return -1;
720         }
721         return _disk_writer->realtime_speed_change ();
722 }
723
724 void
725 Track::realtime_handle_transport_stopped ()
726 {
727         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
728
729         if (!lm.locked ()) {
730                 return;
731         }
732
733         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
734                 (*i)->realtime_handle_transport_stopped ();
735         }
736 }
737
738 void
739 Track::transport_stopped_wallclock (struct tm & n, time_t t, bool g)
740 {
741         _disk_writer->transport_stopped_wallclock (n, t, g);
742 }
743
744 bool
745 Track::pending_overwrite () const
746 {
747         return _disk_reader->pending_overwrite ();
748 }
749
750 void
751 Track::prepare_to_stop (samplepos_t t, samplepos_t a)
752 {
753         _disk_writer->prepare_to_stop (t, a);
754 }
755
756 void
757 Track::set_slaved (bool s)
758 {
759         _disk_reader->set_slaved (s);
760         _disk_writer->set_slaved (s);
761 }
762
763 ChanCount
764 Track::n_channels ()
765 {
766         return _disk_reader->output_streams();
767 }
768
769 samplepos_t
770 Track::get_capture_start_sample (uint32_t n) const
771 {
772         return _disk_writer->get_capture_start_sample (n);
773 }
774
775 AlignStyle
776 Track::alignment_style () const
777 {
778         return _disk_writer->alignment_style ();
779 }
780
781 AlignChoice
782 Track::alignment_choice () const
783 {
784         return _disk_writer->alignment_choice ();
785 }
786
787 samplepos_t
788 Track::current_capture_start () const
789 {
790         return _disk_writer->current_capture_start ();
791 }
792
793 samplepos_t
794 Track::current_capture_end () const
795 {
796         return _disk_writer->current_capture_end ();
797 }
798
799 void
800 Track::playlist_modified ()
801 {
802         _disk_reader->playlist_modified ();
803 }
804
805 int
806 Track::find_and_use_playlist (DataType dt, PBD::ID const & id)
807 {
808         boost::shared_ptr<Playlist> playlist;
809
810         if ((playlist = _session.playlists->by_id (id)) == 0) {
811                 return -1;
812         }
813
814         if (!playlist) {
815                 error << string_compose(_("DiskIOProcessor: \"%1\" isn't an playlist"), id.to_s()) << endmsg;
816                 return -1;
817         }
818
819         return use_playlist (dt, playlist);
820 }
821
822 int
823 Track::use_playlist (DataType dt, boost::shared_ptr<Playlist> p)
824 {
825         int ret;
826
827         if ((ret = _disk_reader->use_playlist (dt, p)) == 0) {
828                 if ((ret = _disk_writer->use_playlist (dt, p)) == 0) {
829                         p->set_orig_track_id (id());
830                 }
831         }
832
833         if (ret == 0) {
834                 _playlists[dt] = p;
835         }
836
837         return ret;
838 }
839
840 int
841 Track::use_copy_playlist ()
842 {
843         assert (_playlists[data_type()]);
844
845         if (_playlists[data_type()] == 0) {
846                 error << string_compose(_("DiskIOProcessor %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
847                 return -1;
848         }
849
850         string newname;
851         boost::shared_ptr<Playlist> playlist;
852
853         newname = Playlist::bump_name (_playlists[data_type()]->name(), _session);
854
855         if ((playlist = PlaylistFactory::create (_playlists[data_type()], newname)) == 0) {
856                 return -1;
857         }
858
859         playlist->reset_shares();
860
861         return use_playlist (data_type(), playlist);
862 }
863
864 int
865 Track::use_new_playlist (DataType dt)
866 {
867         string newname;
868         boost::shared_ptr<Playlist> playlist = _playlists[dt];
869
870         if (playlist) {
871                 newname = Playlist::bump_name (playlist->name(), _session);
872         } else {
873                 newname = Playlist::bump_name (_name, _session);
874         }
875
876         playlist = PlaylistFactory::create (dt, _session, newname, is_private_route());
877
878         if (!playlist) {
879                 return -1;
880         }
881
882         return use_playlist (dt, playlist);
883 }
884
885 void
886 Track::set_align_choice (AlignChoice ac, bool force)
887 {
888         switch (ac) {
889         case Automatic:
890                 _alignment_choice = Automatic;
891                 set_align_choice_from_io ();
892                 return;
893         default:
894                 break;
895         }
896
897         _disk_writer->set_align_choice (ac, force);
898         _alignment_choice = ac;
899 }
900
901 void
902 Track::set_align_style (AlignStyle s, bool force)
903 {
904         _disk_writer->set_align_style (s, force);
905 }
906
907 void
908 Track::set_align_choice_from_io ()
909 {
910         bool have_physical = false;
911
912         if (_input) {
913                 uint32_t n = 0;
914                 vector<string> connections;
915                 boost::shared_ptr<Port> p;
916
917                 while (true) {
918
919                         p = _input->nth (n++);
920
921                         if (!p) {
922                                 break;
923                         }
924
925                         if (p->get_connections (connections) != 0) {
926                                 if (AudioEngine::instance()->port_is_physical (connections[0])) {
927                                         have_physical = true;
928                                         break;
929                                 }
930                         }
931
932                         connections.clear ();
933                 }
934         }
935
936 #ifdef MIXBUS
937         // compensate for latency when bouncing from master or mixbus.
938         // we need to use "ExistingMaterial" to pick up the master bus' latency
939         // see also Route::direct_feeds_according_to_reality
940         IOVector ios;
941         ios.push_back (_input);
942         if (_session.master_out() && ios.fed_by (_session.master_out()->output())) {
943                 have_physical = true;
944         }
945         for (uint32_t n = 0; n < NUM_MIXBUSES && !have_physical; ++n) {
946                 if (_session.get_mixbus (n) && ios.fed_by (_session.get_mixbus(n)->output())) {
947                         have_physical = true;
948                 }
949         }
950 #endif
951
952         if (have_physical) {
953                 _disk_writer->set_align_style (ExistingMaterial);
954         } else {
955                 _disk_writer->set_align_style (CaptureTime);
956         }
957 }
958
959 void
960 Track::set_block_size (pframes_t n)
961 {
962         Route::set_block_size (n);
963         _disk_reader->set_block_size (n);
964         _disk_writer->set_block_size (n);
965 }
966
967 void
968 Track::adjust_playback_buffering ()
969 {
970         if (_disk_reader) {
971                 _disk_reader->adjust_buffering ();
972         }
973 }
974
975 void
976 Track::adjust_capture_buffering ()
977 {
978         if (_disk_writer) {
979                 _disk_writer->adjust_buffering ();
980         }
981 }
982
983 #ifdef USE_TRACKS_CODE_FEATURES
984
985 /* This is the Tracks version of Track::monitoring_state().
986  *
987  * Ardour developers: try to flag or fix issues if parts of the libardour API
988  * change in ways that invalidate this
989  */
990
991 MonitorState
992 Track::monitoring_state () const
993 {
994         /* Explicit requests */
995
996         if (_monitoring != MonitorInput) {
997                 return MonitoringInput;
998         }
999
1000         if (_monitoring & MonitorDisk) {
1001                 return MonitoringDisk;
1002         }
1003
1004         /* This is an implementation of the truth table in doc/monitor_modes.pdf;
1005            I don't think it's ever going to be too pretty too look at.
1006         */
1007
1008         // GZ: NOT USED IN TRACKS
1009         //bool const auto_input = _session.config.get_auto_input ();
1010         //bool const software_monitor = Config->get_monitoring_model() == SoftwareMonitoring;
1011         //bool const tape_machine_mode = Config->get_tape_machine_mode ();
1012
1013         bool const roll = _session.transport_rolling ();
1014         bool const track_rec = _diskstream->record_enabled ();
1015         bool session_rec = _session.actively_recording ();
1016
1017         if (track_rec) {
1018
1019                 if (!session_rec && roll) {
1020                         return MonitoringDisk;
1021                 } else {
1022                         return MonitoringInput;
1023                 }
1024
1025         } else {
1026
1027                 if (roll) {
1028                         return MonitoringDisk;
1029                 }
1030         }
1031
1032         return MonitoringSilence;
1033 }
1034
1035 #else
1036
1037 /* This is the Ardour/Mixbus version of Track::monitoring_state().
1038  *
1039  * Tracks developers: do NOT modify this method under any circumstances.
1040  */
1041
1042 MonitorState
1043 Track::monitoring_state () const
1044 {
1045         /* Explicit requests */
1046         MonitorChoice m (_monitoring_control->monitoring_choice());
1047
1048         if (m != MonitorAuto) {
1049
1050                 MonitorState ms ((MonitorState) 0);
1051
1052                 if (m & MonitorInput) {
1053                         ms = MonitoringInput;
1054                 }
1055
1056                 if (m & MonitorDisk) {
1057                         ms = MonitorState (ms | MonitoringDisk);
1058                 }
1059
1060                 return ms;
1061         }
1062
1063         switch (_session.config.get_session_monitoring ()) {
1064                 case MonitorDisk:
1065                         return MonitoringDisk;
1066                         break;
1067                 case MonitorInput:
1068                         return MonitoringInput;
1069                         break;
1070                 default:
1071                         break;
1072         }
1073
1074         /* This is an implementation of the truth table in doc/monitor_modes.pdf;
1075            I don't think it's ever going to be too pretty too look at.
1076         */
1077
1078         bool const roll = _session.transport_rolling ();
1079         bool const track_rec = _disk_writer->record_enabled ();
1080         bool const auto_input = _session.config.get_auto_input ();
1081         bool const software_monitor = Config->get_monitoring_model() == SoftwareMonitoring;
1082         bool const tape_machine_mode = Config->get_tape_machine_mode ();
1083         bool session_rec;
1084
1085         /* I suspect that just use actively_recording() is good enough all the
1086          * time, but just to keep the semantics the same as they were before
1087          * sept 26th 2012, we differentiate between the cases where punch is
1088          * enabled and those where it is not.
1089          *
1090          * rg: I suspect this is not the case: monitoring may differ
1091          */
1092
1093         if (_session.config.get_punch_in() || _session.config.get_punch_out() || _session.preroll_record_punch_enabled ()) {
1094                 session_rec = _session.actively_recording ();
1095         } else {
1096                 session_rec = _session.get_record_enabled();
1097         }
1098
1099         if (track_rec) {
1100
1101                 if (!session_rec && roll && auto_input) {
1102                         return MonitoringDisk;
1103                 } else {
1104                         return software_monitor ? MonitoringInput : MonitoringSilence;
1105                 }
1106
1107         } else {
1108
1109                 if (tape_machine_mode) {
1110
1111                         return MonitoringDisk;
1112
1113                 } else {
1114
1115                         if (!roll && auto_input) {
1116                                 return software_monitor ? MonitoringInput : MonitoringSilence;
1117                         } else {
1118                                 return MonitoringDisk;
1119                         }
1120
1121                 }
1122         }
1123
1124         abort(); /* NOTREACHED */
1125         return MonitoringSilence;
1126 }
1127
1128 #endif
1129
1130 void
1131 Track::maybe_declick (BufferSet& bufs, samplecnt_t nframes, int declick)
1132 {
1133         /* never declick if there is an internal generator - we just want it to
1134            keep generating sound without interruption.
1135
1136            ditto if we are monitoring inputs.
1137         */
1138
1139         if (_have_internal_generator || (_monitoring_control->monitoring_choice() == MonitorInput)) {
1140                 return;
1141         }
1142
1143         if (!declick) {
1144                 declick = _pending_declick;
1145         }
1146
1147         if (declick != 0) {
1148                 Amp::declick (bufs, nframes, declick);
1149         }
1150 }
1151
1152 samplecnt_t
1153 Track::check_initial_delay (samplecnt_t nframes, samplepos_t& transport_sample)
1154 {
1155         if (_roll_delay > nframes) {
1156
1157                 _roll_delay -= nframes;
1158                 silence_unlocked (nframes);
1159                 /* transport sample is not legal for caller to use */
1160                 return 0;
1161
1162         } else if (_roll_delay > 0) {
1163
1164                 nframes -= _roll_delay;
1165                 silence_unlocked (_roll_delay);
1166                 transport_sample += _roll_delay;
1167
1168                 /* shuffle all the port buffers for things that lead "out" of this Route
1169                    to reflect that we just wrote _roll_delay samples of silence.
1170                 */
1171
1172                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1173                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1174                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
1175                         if (iop) {
1176                                 iop->increment_port_buffer_offset (_roll_delay);
1177                         }
1178                 }
1179                 _output->increment_port_buffer_offset (_roll_delay);
1180
1181                 _roll_delay = 0;
1182
1183         }
1184
1185         return nframes;
1186 }
1187
1188 void
1189 Track::monitoring_changed (bool, Controllable::GroupControlDisposition)
1190 {
1191         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1192                 (*i)->monitoring_changed ();
1193         }
1194 }
1195
1196 MeterState
1197 Track::metering_state () const
1198 {
1199         bool rv;
1200         if (_session.transport_rolling ()) {
1201                 // audio_track.cc || midi_track.cc roll() runs meter IFF:
1202                 rv = _meter_point == MeterInput && ((_monitoring_control->monitoring_choice() & MonitorInput) || _disk_writer->record_enabled());
1203         } else {
1204                 // track no_roll() always metering if
1205                 rv = _meter_point == MeterInput;
1206         }
1207         return rv ? MeteringInput : MeteringRoute;
1208 }
1209
1210 bool
1211 Track::set_processor_state (XMLNode const & node, XMLProperty const* prop, ProcessorList& new_order, bool& must_configure)
1212 {
1213         if (Route::set_processor_state (node, prop, new_order, must_configure)) {
1214                 return true;
1215         }
1216
1217         cerr << name() << " looking for state for track procs, DR = " << _disk_reader << endl;
1218
1219         if (prop->value() == "diskreader") {
1220                 if (_disk_reader) {
1221                         _disk_reader->set_state (node, Stateful::current_state_version);
1222                         new_order.push_back (_disk_reader);
1223                         return true;
1224                 }
1225         } else if (prop->value() == "diskwriter") {
1226                 if (_disk_writer) {
1227                         _disk_writer->set_state (node, Stateful::current_state_version);
1228                         new_order.push_back (_disk_writer);
1229                         return true;
1230                 }
1231         }
1232
1233         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
1234         return false;
1235 }
1236
1237 void
1238 Track::use_captured_sources (SourceList& srcs, CaptureInfos const & capture_info)
1239 {
1240         if (srcs.empty()) {
1241                 return;
1242         }
1243
1244         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (srcs.front());
1245         boost::shared_ptr<SMFSource> mfs = boost::dynamic_pointer_cast<SMFSource> (srcs.front());
1246
1247         if (afs) {
1248                 use_captured_audio_sources (srcs, capture_info);
1249         }
1250
1251         if (mfs) {
1252                 use_captured_midi_sources (srcs, capture_info);
1253         }
1254 }
1255
1256 void
1257 Track::use_captured_midi_sources (SourceList& srcs, CaptureInfos const & capture_info)
1258 {
1259         if (srcs.empty() || data_type() != DataType::MIDI) {
1260                 return;
1261         }
1262
1263         boost::shared_ptr<SMFSource> mfs = boost::dynamic_pointer_cast<SMFSource> (srcs.front());
1264         boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
1265         boost::shared_ptr<MidiRegion> midi_region;
1266         CaptureInfos::const_iterator ci;
1267
1268         if (!mfs || !pl) {
1269                 return;
1270         }
1271
1272         samplecnt_t total_capture = 0;
1273
1274         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1275                 total_capture += (*ci)->samples;
1276         }
1277
1278         /* we will want to be able to keep (over)writing the source
1279            but we don't want it to be removable. this also differs
1280            from the audio situation, where the source at this point
1281            must be considered immutable. luckily, we can rely on
1282            MidiSource::mark_streaming_write_completed() to have
1283            already done the necessary work for that.
1284         */
1285
1286         string whole_file_region_name;
1287         whole_file_region_name = region_name_from_path (mfs->name(), true);
1288
1289         /* Register a new region with the Session that
1290            describes the entire source. Do this first
1291            so that any sub-regions will obviously be
1292            children of this one (later!)
1293         */
1294
1295         try {
1296                 PropertyList plist;
1297
1298                 plist.add (Properties::name, whole_file_region_name);
1299                 plist.add (Properties::whole_file, true);
1300                 plist.add (Properties::automatic, true);
1301                 plist.add (Properties::start, 0);
1302                 plist.add (Properties::length, total_capture);
1303                 plist.add (Properties::layer, 0);
1304
1305                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1306
1307                 midi_region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1308                 midi_region->special_set_position (capture_info.front()->start);
1309         }
1310
1311         catch (failed_constructor& err) {
1312                 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1313                 /* XXX what now? */
1314         }
1315
1316         pl->clear_changes ();
1317         pl->freeze ();
1318
1319         /* Session sample time of the initial capture in this pass, which is where the source starts */
1320         samplepos_t initial_capture = 0;
1321         if (!capture_info.empty()) {
1322                 initial_capture = capture_info.front()->start;
1323         }
1324
1325         BeatsSamplesConverter converter (_session.tempo_map(), capture_info.front()->start);
1326         const samplepos_t preroll_off = _session.preroll_record_trim_len ();
1327
1328         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1329
1330                 string region_name;
1331
1332                 RegionFactory::region_name (region_name, mfs->name(), false);
1333
1334                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1335                                                                       _name, (*ci)->start, (*ci)->samples, region_name));
1336
1337
1338                 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->samples << " add a region\n";
1339
1340                 try {
1341                         PropertyList plist;
1342
1343                         /* start of this region is the offset between the start of its capture and the start of the whole pass */
1344                         plist.add (Properties::start, (*ci)->start - initial_capture);
1345                         plist.add (Properties::length, (*ci)->samples);
1346                         plist.add (Properties::length_beats, converter.from((*ci)->samples).to_double());
1347                         plist.add (Properties::name, region_name);
1348
1349                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1350                         midi_region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1351                         if (preroll_off > 0) {
1352                                 midi_region->trim_front ((*ci)->start - initial_capture + preroll_off);
1353                         }
1354                 }
1355
1356                 catch (failed_constructor& err) {
1357                         error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1358                         continue; /* XXX is this OK? */
1359                 }
1360
1361                 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1362
1363                 pl->add_region (midi_region, (*ci)->start + preroll_off, _disk_writer->non_layered());
1364         }
1365
1366         pl->thaw ();
1367         _session.add_command (new StatefulDiffCommand (pl));
1368 }
1369
1370 void
1371 Track::use_captured_audio_sources (SourceList& srcs, CaptureInfos const & capture_info)
1372 {
1373         if (srcs.empty() || data_type() != DataType::AUDIO) {
1374                 return;
1375         }
1376
1377         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (srcs.front());
1378         boost::shared_ptr<Playlist> pl = _playlists[DataType::AUDIO];
1379         boost::shared_ptr<AudioRegion> region;
1380
1381         if (!afs || !pl) {
1382                 return;
1383         }
1384
1385         /* destructive tracks have a single, never changing region */
1386
1387         if (destructive()) {
1388
1389                 /* send a signal that any UI can pick up to do the right thing. there is
1390                    a small problem here in that a UI may need the peak data to be ready
1391                    for the data that was recorded and this isn't interlocked with that
1392                    process. this problem is deferred to the UI.
1393                  */
1394
1395                 pl->LayeringChanged(); // XXX this may not get the UI to do the right thing
1396                 return;
1397         }
1398
1399         string whole_file_region_name;
1400         whole_file_region_name = region_name_from_path (afs->name(), true);
1401
1402         /* Register a new region with the Session that
1403            describes the entire source. Do this first
1404            so that any sub-regions will obviously be
1405            children of this one (later!)
1406         */
1407
1408         try {
1409                 PropertyList plist;
1410
1411                 plist.add (Properties::start, afs->last_capture_start_sample());
1412                 plist.add (Properties::length, afs->length(0));
1413                 plist.add (Properties::name, whole_file_region_name);
1414                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1415                 rx->set_automatic (true);
1416                 rx->set_whole_file (true);
1417
1418                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1419                 region->special_set_position (afs->natural_position());
1420         }
1421
1422
1423         catch (failed_constructor& err) {
1424                 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1425                 /* XXX what now? */
1426         }
1427
1428         pl->clear_changes ();
1429         pl->set_capture_insertion_in_progress (true);
1430         pl->freeze ();
1431
1432         const samplepos_t preroll_off = _session.preroll_record_trim_len ();
1433         samplecnt_t buffer_position = afs->last_capture_start_sample ();
1434         CaptureInfos::const_iterator ci;
1435
1436         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1437
1438                 string region_name;
1439
1440                 RegionFactory::region_name (region_name, whole_file_region_name, false);
1441
1442                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1443                                                                       _name, (*ci)->start, (*ci)->samples, region_name, buffer_position));
1444
1445                 try {
1446
1447                         PropertyList plist;
1448
1449                         plist.add (Properties::start, buffer_position);
1450                         plist.add (Properties::length, (*ci)->samples);
1451                         plist.add (Properties::name, region_name);
1452
1453                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1454                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1455                         if (preroll_off > 0) {
1456                                 region->trim_front (buffer_position + preroll_off);
1457                         }
1458                 }
1459
1460                 catch (failed_constructor& err) {
1461                         error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1462                         continue; /* XXX is this OK? */
1463                 }
1464
1465                 pl->add_region (region, (*ci)->start + preroll_off, 1, _disk_writer->non_layered());
1466                 pl->set_layer (region, DBL_MAX);
1467
1468                 buffer_position += (*ci)->samples;
1469         }
1470
1471         pl->thaw ();
1472         pl->set_capture_insertion_in_progress (false);
1473         _session.add_command (new StatefulDiffCommand (pl));
1474 }
1475
1476