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