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