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