4e611211f306cc3167146a875b3fbeba647b79c1
[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/audioplaylist.h"
24 #include "ardour/audioregion.h"
25 #include "ardour/debug.h"
26 #include "ardour/delivery.h"
27 #include "ardour/disk_reader.h"
28 #include "ardour/disk_writer.h"
29 #include "ardour/event_type_map.h"
30 #include "ardour/io_processor.h"
31 #include "ardour/meter.h"
32 #include "ardour/midi_playlist.h"
33 #include "ardour/midi_region.h"
34 #include "ardour/monitor_control.h"
35 #include "ardour/playlist.h"
36 #include "ardour/playlist_factory.h"
37 #include "ardour/port.h"
38 #include "ardour/processor.h"
39 #include "ardour/profile.h"
40 #include "ardour/region_factory.h"
41 #include "ardour/record_enable_control.h"
42 #include "ardour/record_safe_control.h"
43 #include "ardour/route_group_specialized.h"
44 #include "ardour/session.h"
45 #include "ardour/session_playlists.h"
46 #include "ardour/smf_source.h"
47 #include "ardour/track.h"
48 #include "ardour/types_convert.h"
49 #include "ardour/utils.h"
50
51 #include "pbd/i18n.h"
52
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56
57 Track::Track (Session& sess, string name, PresentationInfo::Flag flag, TrackMode mode, DataType default_type)
58         : Route (sess, name, flag, default_type)
59         , _saved_meter_point (_meter_point)
60         , _mode (mode)
61         , _alignment_choice (Automatic)
62 {
63         _freeze_record.state = NoFreeze;
64         _declickable = true;
65
66 }
67
68 Track::~Track ()
69 {
70         DEBUG_TRACE (DEBUG::Destruction, string_compose ("track %1 destructor\n", _name));
71
72         if (_disk_reader) {
73                 _disk_reader->set_route (boost::shared_ptr<Route>());
74                 _disk_reader.reset ();
75         }
76
77         if (_disk_writer) {
78                 _disk_writer->set_route (boost::shared_ptr<Route>());
79                 _disk_writer.reset ();
80         }
81 }
82
83 int
84 Track::init ()
85 {
86         if (Route::init ()) {
87                 return -1;
88         }
89
90         DiskIOProcessor::Flag dflags = DiskIOProcessor::Recordable;
91
92         if (_mode == Destructive && !Profile->get_trx()) {
93                 dflags = DiskIOProcessor::Flag (dflags | DiskIOProcessor::Destructive);
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         _disk_reader->set_owner (this);
100
101         _disk_writer.reset (new DiskWriter (_session, name(), dflags));
102         _disk_writer->set_block_size (_session.get_block_size ());
103         _disk_writer->set_route (boost::dynamic_pointer_cast<Route> (shared_from_this()));
104         _disk_writer->set_owner (this);
105
106         set_align_choice_from_io ();
107
108         use_new_playlist (data_type());
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         if (version >= 3000 && version < 6000) {
178                 if (XMLNode* ds_node = find_named_node (node, "Diskstream")) {
179                         std::string name;
180                         if (ds_node->get_property ("name", name)) {
181
182                                 ds_node->set_property ("active", true);
183
184                                 _disk_writer->set_state (*ds_node, version);
185                                 _disk_reader->set_state (*ds_node, version);
186
187                                 AlignChoice ac;
188                                 if (ds_node->get_property (X_("capture-alignment"), ac)) {
189                                         set_align_choice (ac, true);
190                                 }
191
192                                 if (boost::shared_ptr<AudioPlaylist> pl = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) {
193                                         use_playlist (DataType::AUDIO, pl);
194                                 }
195
196                                 if (boost::shared_ptr<MidiPlaylist> pl = boost::dynamic_pointer_cast<MidiPlaylist> (_session.playlists->by_name (name))) {
197                                         use_playlist (DataType::MIDI, pl);
198                                 }
199                         }
200                 }
201         }
202
203         XMLNode* child;
204         std::string playlist_id;
205
206         if (node.get_property (X_("audio-playlist"), playlist_id)) {
207                 find_and_use_playlist (DataType::AUDIO, PBD::ID (playlist_id));
208         }
209
210         if (node.get_property (X_("midi-playlist"), playlist_id)) {
211                 find_and_use_playlist (DataType::MIDI, PBD::ID (playlist_id));
212         }
213
214         XMLNodeList nlist = node.children();
215         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
216                 child = *niter;
217
218                 if (child->name() == Controllable::xml_node_name) {
219                         std::string name;
220                         if (!child->get_property ("name", name)) {
221                                 continue;
222                         }
223
224                         if (name == _record_enable_control->name()) {
225                                 _record_enable_control->set_state (*child, version);
226                         } else if (name == _record_safe_control->name()) {
227                                 _record_safe_control->set_state (*child, version);
228                         } else if (name == _monitoring_control->name()) {
229                                 _monitoring_control->set_state (*child, version);
230                         }
231                 }
232         }
233
234         if (!node.get_property (X_("saved-meter-point"), _saved_meter_point)) {
235                 _saved_meter_point = _meter_point;
236         }
237
238
239         AlignChoice ac;
240
241         if (node.get_property (X_("alignment-choice"), ac)) {
242                 set_align_choice (ac, true);
243         }
244
245         return 0;
246 }
247
248 XMLNode&
249 Track::get_template ()
250 {
251         return state (false);
252 }
253
254 Track::FreezeRecord::~FreezeRecord ()
255 {
256         for (vector<FreezeRecordProcessorInfo*>::iterator i = processor_info.begin(); i != processor_info.end(); ++i) {
257                 delete *i;
258         }
259 }
260
261 Track::FreezeState
262 Track::freeze_state() const
263 {
264         return _freeze_record.state;
265 }
266
267 bool
268 Track::can_record()
269 {
270         bool will_record = true;
271         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end() && will_record; ++i) {
272                 if (!i->connected())
273                         will_record = false;
274         }
275
276         return will_record;
277 }
278
279 int
280 Track::prep_record_enabled (bool yn)
281 {
282         if (yn && _record_safe_control->get_value()) {
283                 return -1;
284         }
285
286         if (!can_be_record_enabled()) {
287                 return -1;
288         }
289
290         /* keep track of the meter point as it was before we rec-enabled */
291         if (!_disk_writer->record_enabled()) {
292                 _saved_meter_point = _meter_point;
293         }
294
295         bool will_follow;
296
297         if (yn) {
298                 will_follow = _disk_writer->prep_record_enable ();
299         } else {
300                 will_follow = _disk_writer->prep_record_disable ();
301         }
302
303         if (will_follow) {
304                 if (yn) {
305                         if (_meter_point != MeterCustom) {
306                                 set_meter_point (MeterInput);
307                         }
308                 } else {
309                         set_meter_point (_saved_meter_point);
310                 }
311         }
312
313         return 0;
314 }
315
316 void
317 Track::record_enable_changed (bool, Controllable::GroupControlDisposition)
318 {
319         _disk_writer->set_record_enabled (_record_enable_control->get_value());
320 }
321
322 void
323 Track::record_safe_changed (bool, Controllable::GroupControlDisposition)
324 {
325         _disk_writer->set_record_safe (_record_safe_control->get_value());
326 }
327
328 bool
329 Track::can_be_record_safe ()
330 {
331         return !_record_enable_control->get_value() && _disk_writer && _session.writable() && (_freeze_record.state != Frozen);
332 }
333
334 bool
335 Track::can_be_record_enabled ()
336 {
337         return !_record_safe_control->get_value() && _disk_writer && !_disk_writer->record_safe() && _session.writable() && (_freeze_record.state != Frozen);
338 }
339
340 void
341 Track::parameter_changed (string const & p)
342 {
343         if (p == "track-name-number") {
344                 resync_track_name ();
345         }
346         else if (p == "track-name-take") {
347                 resync_track_name ();
348         }
349         else if (p == "take-name") {
350                 if (_session.config.get_track_name_take()) {
351                         resync_track_name ();
352                 }
353         }
354 }
355
356 void
357 Track::resync_track_name ()
358 {
359         set_name(name());
360 }
361
362 bool
363 Track::set_name (const string& str)
364 {
365         bool ret;
366
367         if (str.empty ()) {
368                 return false;
369         }
370
371         if (_record_enable_control->get_value()) {
372                 /* when re-arm'ed the file (named after the track) is already ready to rolll */
373                 return false;
374         }
375
376         string diskstream_name = "";
377         if (_session.config.get_track_name_take () && !_session.config.get_take_name ().empty()) {
378                 // Note: any text is fine, legalize_for_path() fixes this later
379                 diskstream_name += _session.config.get_take_name ();
380                 diskstream_name += "_";
381         }
382         const int64_t tracknumber = track_number();
383         if (tracknumber > 0 && _session.config.get_track_name_number()) {
384                 char num[64], fmt[10];
385                 snprintf(fmt, sizeof(fmt), "%%0%d" PRId64, _session.track_number_decimals());
386                 snprintf(num, sizeof(num), fmt, tracknumber);
387                 diskstream_name += num;
388                 diskstream_name += "_";
389         }
390         diskstream_name += str;
391
392         if (diskstream_name == _diskstream_name) {
393                 return true;
394         }
395         _diskstream_name = diskstream_name;
396
397         _disk_writer->set_write_source_name (diskstream_name);
398
399         boost::shared_ptr<Track> me = boost::dynamic_pointer_cast<Track> (shared_from_this ());
400
401         if (_playlists[data_type()]->all_regions_empty () && _session.playlists->playlists_for_track (me).size() == 1) {
402                 /* Only rename the diskstream (and therefore the playlist) if
403                    a) the playlist has never had a region added to it and
404                    b) there is only one playlist for this track.
405
406                    If (a) is not followed, people can get confused if, say,
407                    they have notes about a playlist with a given name and then
408                    it changes (see mantis #4759).
409
410                    If (b) is not followed, we rename the current playlist and not
411                    the other ones, which is a bit confusing (see mantis #4977).
412                 */
413                 _disk_reader->set_name (str);
414                 _disk_writer->set_name (str);
415         }
416
417         for (uint32_t n = 0; n < DataType::num_types; ++n) {
418                 if (_playlists[n]) {
419                         _playlists[n]->set_name (str);
420                 }
421         }
422
423         /* save state so that the statefile fully reflects any filename changes */
424
425         if ((ret = Route::set_name (str)) == 0) {
426                 _session.save_state ("");
427         }
428
429         return ret;
430 }
431
432 boost::shared_ptr<Playlist>
433 Track::playlist ()
434 {
435         return _playlists[data_type()];
436 }
437
438 void
439 Track::request_input_monitoring (bool m)
440 {
441         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
442                 AudioEngine::instance()->request_input_monitoring ((*i)->name(), m);
443         }
444 }
445
446 void
447 Track::ensure_input_monitoring (bool m)
448 {
449         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
450                 AudioEngine::instance()->ensure_input_monitoring ((*i)->name(), m);
451         }
452 }
453
454 bool
455 Track::destructive () const
456 {
457         return _disk_writer->destructive ();
458 }
459
460 list<boost::shared_ptr<Source> > &
461 Track::last_capture_sources ()
462 {
463         return _disk_writer->last_capture_sources ();
464 }
465
466 std::string
467 Track::steal_write_source_name()
468 {
469         return _disk_writer->steal_write_source_name ();
470 }
471
472 void
473 Track::reset_write_sources (bool r, bool force)
474 {
475         _disk_writer->reset_write_sources (r, force);
476 }
477
478 float
479 Track::playback_buffer_load () const
480 {
481         return _disk_reader->buffer_load ();
482 }
483
484 float
485 Track::capture_buffer_load () const
486 {
487         return _disk_writer->buffer_load ();
488 }
489
490 int
491 Track::do_refill ()
492 {
493         return _disk_reader->do_refill ();
494 }
495
496 int
497 Track::do_flush (RunContext c, bool force)
498 {
499         return _disk_writer->do_flush (c, force);
500 }
501
502 void
503 Track::set_pending_overwrite (bool o)
504 {
505         _disk_reader->set_pending_overwrite (o);
506 }
507
508 int
509 Track::seek (samplepos_t p, bool complete_refill)
510 {
511         if (_disk_reader->seek (p, complete_refill)) {
512                 return -1;
513         }
514         return _disk_writer->seek (p, complete_refill);
515 }
516
517 int
518 Track::can_internal_playback_seek (samplecnt_t p)
519 {
520         return _disk_reader->can_internal_playback_seek (p);
521 }
522
523 int
524 Track::internal_playback_seek (samplecnt_t p)
525 {
526         return _disk_reader->internal_playback_seek (p);
527 }
528
529 void
530 Track::non_realtime_locate (samplepos_t p)
531 {
532         Route::non_realtime_locate (p);
533
534         if (!is_private_route()) {
535                 /* don't waste i/o cycles and butler calls
536                    for private tracks (e.g.auditioner)
537                 */
538                 _disk_reader->non_realtime_locate (p);
539                 _disk_writer->non_realtime_locate (p);
540         }
541 }
542
543 void
544 Track::non_realtime_speed_change ()
545 {
546         _disk_reader->non_realtime_speed_change ();
547 }
548
549 int
550 Track::overwrite_existing_buffers ()
551 {
552         return _disk_reader->overwrite_existing_buffers ();
553 }
554
555 samplecnt_t
556 Track::get_captured_samples (uint32_t n) const
557 {
558         return _disk_writer->get_captured_samples (n);
559 }
560
561 int
562 Track::set_loop (Location* l)
563 {
564         if (_disk_reader->set_loop (l)) {
565                 return -1;
566         }
567         return _disk_writer->set_loop (l);
568 }
569
570 void
571 Track::transport_looped (samplepos_t p)
572 {
573         return _disk_writer->transport_looped (p);
574 }
575
576 void
577 Track::realtime_handle_transport_stopped ()
578 {
579         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
580
581         if (!lm.locked ()) {
582                 return;
583         }
584
585         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
586                 (*i)->realtime_handle_transport_stopped ();
587         }
588 }
589
590 void
591 Track::transport_stopped_wallclock (struct tm & n, time_t t, bool g)
592 {
593         _disk_writer->transport_stopped_wallclock (n, t, g);
594 }
595
596 bool
597 Track::pending_overwrite () const
598 {
599         return _disk_reader->pending_overwrite ();
600 }
601
602 void
603 Track::set_slaved (bool s)
604 {
605         _disk_reader->set_slaved (s);
606         _disk_writer->set_slaved (s);
607 }
608
609 ChanCount
610 Track::n_channels ()
611 {
612         return _disk_reader->output_streams();
613 }
614
615 samplepos_t
616 Track::get_capture_start_sample (uint32_t n) const
617 {
618         return _disk_writer->get_capture_start_sample (n);
619 }
620
621 AlignStyle
622 Track::alignment_style () const
623 {
624         return _disk_writer->alignment_style ();
625 }
626
627 AlignChoice
628 Track::alignment_choice () const
629 {
630         return _alignment_choice;
631 }
632
633 samplepos_t
634 Track::current_capture_start () const
635 {
636         return _disk_writer->current_capture_start ();
637 }
638
639 samplepos_t
640 Track::current_capture_end () const
641 {
642         return _disk_writer->current_capture_end ();
643 }
644
645 void
646 Track::playlist_modified ()
647 {
648         _disk_reader->playlist_modified ();
649 }
650
651 int
652 Track::find_and_use_playlist (DataType dt, PBD::ID const & id)
653 {
654         boost::shared_ptr<Playlist> playlist;
655
656         if ((playlist = _session.playlists->by_id (id)) == 0) {
657                 return -1;
658         }
659
660         if (!playlist) {
661                 error << string_compose(_("DiskIOProcessor: \"%1\" isn't an playlist"), id.to_s()) << endmsg;
662                 return -1;
663         }
664
665         return use_playlist (dt, playlist);
666 }
667
668 int
669 Track::use_playlist (DataType dt, boost::shared_ptr<Playlist> p)
670 {
671         int ret;
672
673         if ((ret = _disk_reader->use_playlist (dt, p)) == 0) {
674                 if ((ret = _disk_writer->use_playlist (dt, p)) == 0) {
675                         p->set_orig_track_id (id());
676                 }
677         }
678
679         if (ret == 0) {
680                 _playlists[dt] = p;
681         }
682
683         _session.set_dirty ();
684         PlaylistChanged (); /* EMIT SIGNAL */
685
686         return ret;
687 }
688
689 int
690 Track::use_copy_playlist ()
691 {
692         assert (_playlists[data_type()]);
693
694         if (_playlists[data_type()] == 0) {
695                 error << string_compose(_("DiskIOProcessor %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
696                 return -1;
697         }
698
699         string newname;
700         boost::shared_ptr<Playlist> playlist;
701
702         newname = Playlist::bump_name (_playlists[data_type()]->name(), _session);
703
704         if ((playlist = PlaylistFactory::create (_playlists[data_type()], newname)) == 0) {
705                 return -1;
706         }
707
708         playlist->reset_shares();
709
710         return use_playlist (data_type(), playlist);
711 }
712
713 int
714 Track::use_new_playlist (DataType dt)
715 {
716         string newname;
717         boost::shared_ptr<Playlist> playlist = _playlists[dt];
718
719         if (playlist) {
720                 newname = Playlist::bump_name (playlist->name(), _session);
721         } else {
722                 newname = Playlist::bump_name (_name, _session);
723         }
724
725         playlist = PlaylistFactory::create (dt, _session, newname, is_private_route());
726
727         if (!playlist) {
728                 return -1;
729         }
730
731         return use_playlist (dt, playlist);
732 }
733
734 void
735 Track::set_align_choice (AlignChoice ac, bool force)
736 {
737         _alignment_choice = ac;
738         switch (ac) {
739                 case Automatic:
740                         set_align_choice_from_io ();
741                         break;
742                 case UseCaptureTime:
743                         _disk_writer->set_align_style (CaptureTime, force);
744                         break;
745                 case UseExistingMaterial:
746                         _disk_writer->set_align_style (ExistingMaterial, force);
747                         break;
748         }
749 }
750
751 void
752 Track::set_align_style (AlignStyle s, bool force)
753 {
754         _disk_writer->set_align_style (s, force);
755 }
756
757 void
758 Track::set_align_choice_from_io ()
759 {
760         bool have_physical = false;
761
762         if (_input) {
763                 uint32_t n = 0;
764                 vector<string> connections;
765                 boost::shared_ptr<Port> p;
766
767                 while (true) {
768
769                         p = _input->nth (n++);
770
771                         if (!p) {
772                                 break;
773                         }
774
775                         if (p->get_connections (connections) != 0) {
776                                 if (AudioEngine::instance()->port_is_physical (connections[0])) {
777                                         have_physical = true;
778                                         break;
779                                 }
780                         }
781
782                         connections.clear ();
783                 }
784         }
785
786 #ifdef MIXBUS
787         // compensate for latency when bouncing from master or mixbus.
788         // we need to use "ExistingMaterial" to pick up the master bus' latency
789         // see also Route::direct_feeds_according_to_reality
790         IOVector ios;
791         ios.push_back (_input);
792         if (_session.master_out() && ios.fed_by (_session.master_out()->output())) {
793                 have_physical = true;
794         }
795         for (uint32_t n = 0; n < NUM_MIXBUSES && !have_physical; ++n) {
796                 if (_session.get_mixbus (n) && ios.fed_by (_session.get_mixbus(n)->output())) {
797                         have_physical = true;
798                 }
799         }
800 #endif
801
802         if (have_physical) {
803                 _disk_writer->set_align_style (ExistingMaterial);
804         } else {
805                 _disk_writer->set_align_style (CaptureTime);
806         }
807 }
808
809 void
810 Track::set_block_size (pframes_t n)
811 {
812         Route::set_block_size (n);
813         _disk_reader->set_block_size (n);
814         _disk_writer->set_block_size (n);
815 }
816
817 void
818 Track::adjust_playback_buffering ()
819 {
820         if (_disk_reader) {
821                 _disk_reader->adjust_buffering ();
822         }
823 }
824
825 void
826 Track::adjust_capture_buffering ()
827 {
828         if (_disk_writer) {
829                 _disk_writer->adjust_buffering ();
830         }
831 }
832
833
834 void
835 Track::maybe_declick (BufferSet& bufs, samplecnt_t nframes, int declick)
836 {
837         /* never declick if there is an internal generator - we just want it to
838            keep generating sound without interruption.
839
840            ditto if we are monitoring inputs.
841         */
842
843         if (_have_internal_generator || (_monitoring_control->monitoring_choice() == MonitorInput)) {
844                 return;
845         }
846
847         if (!declick) {
848                 declick = _pending_declick;
849         }
850
851         if (declick != 0) {
852                 Amp::declick (bufs, nframes, declick);
853         }
854 }
855
856 void
857 Track::monitoring_changed (bool, Controllable::GroupControlDisposition)
858 {
859         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
860                 (*i)->monitoring_changed ();
861         }
862 }
863
864 MeterState
865 Track::metering_state () const
866 {
867         bool rv;
868         if (_session.transport_rolling ()) {
869                 // audio_track.cc || midi_track.cc roll() runs meter IFF:
870                 rv = _meter_point == MeterInput && ((_monitoring_control->monitoring_choice() & MonitorInput) || _disk_writer->record_enabled());
871         } else {
872                 // track no_roll() always metering if
873                 rv = _meter_point == MeterInput;
874         }
875         return rv ? MeteringInput : MeteringRoute;
876 }
877
878 bool
879 Track::set_processor_state (XMLNode const & node, XMLProperty const* prop, ProcessorList& new_order, bool& must_configure)
880 {
881         if (Route::set_processor_state (node, prop, new_order, must_configure)) {
882                 return true;
883         }
884
885         cerr << name() << " looking for state for track procs, DR = " << _disk_reader << endl;
886
887         if (prop->value() == "diskreader") {
888                 if (_disk_reader) {
889                         _disk_reader->set_state (node, Stateful::current_state_version);
890                         new_order.push_back (_disk_reader);
891                         return true;
892                 }
893         } else if (prop->value() == "diskwriter") {
894                 if (_disk_writer) {
895                         _disk_writer->set_state (node, Stateful::current_state_version);
896                         new_order.push_back (_disk_writer);
897                         return true;
898                 }
899         }
900
901         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
902         return false;
903 }
904
905 void
906 Track::use_captured_sources (SourceList& srcs, CaptureInfos const & capture_info)
907 {
908         if (srcs.empty()) {
909                 return;
910         }
911
912         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (srcs.front());
913         boost::shared_ptr<SMFSource> mfs = boost::dynamic_pointer_cast<SMFSource> (srcs.front());
914
915         if (afs) {
916                 use_captured_audio_sources (srcs, capture_info);
917         }
918
919         if (mfs) {
920                 use_captured_midi_sources (srcs, capture_info);
921         }
922 }
923
924 void
925 Track::use_captured_midi_sources (SourceList& srcs, CaptureInfos const & capture_info)
926 {
927         if (srcs.empty() || data_type() != DataType::MIDI) {
928                 return;
929         }
930
931         boost::shared_ptr<SMFSource> mfs = boost::dynamic_pointer_cast<SMFSource> (srcs.front());
932         boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
933         boost::shared_ptr<MidiRegion> midi_region;
934         CaptureInfos::const_iterator ci;
935
936         if (!mfs || !pl) {
937                 return;
938         }
939
940         samplecnt_t total_capture = 0;
941
942         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
943                 total_capture += (*ci)->samples;
944         }
945
946         /* we will want to be able to keep (over)writing the source
947            but we don't want it to be removable. this also differs
948            from the audio situation, where the source at this point
949            must be considered immutable. luckily, we can rely on
950            MidiSource::mark_streaming_write_completed() to have
951            already done the necessary work for that.
952         */
953
954         string whole_file_region_name;
955         whole_file_region_name = region_name_from_path (mfs->name(), true);
956
957         /* Register a new region with the Session that
958            describes the entire source. Do this first
959            so that any sub-regions will obviously be
960            children of this one (later!)
961         */
962
963         try {
964                 PropertyList plist;
965
966                 plist.add (Properties::name, whole_file_region_name);
967                 plist.add (Properties::whole_file, true);
968                 plist.add (Properties::automatic, true);
969                 plist.add (Properties::start, 0);
970                 plist.add (Properties::length, total_capture);
971                 plist.add (Properties::layer, 0);
972
973                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
974
975                 midi_region = boost::dynamic_pointer_cast<MidiRegion> (rx);
976                 midi_region->special_set_position (capture_info.front()->start);
977         }
978
979         catch (failed_constructor& err) {
980                 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
981                 /* XXX what now? */
982         }
983
984         pl->clear_changes ();
985         pl->freeze ();
986
987         /* Session sample time of the initial capture in this pass, which is where the source starts */
988         samplepos_t initial_capture = 0;
989         if (!capture_info.empty()) {
990                 initial_capture = capture_info.front()->start;
991         }
992
993         BeatsSamplesConverter converter (_session.tempo_map(), capture_info.front()->start);
994         const samplepos_t preroll_off = _session.preroll_record_trim_len ();
995
996         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
997
998                 string region_name;
999
1000                 RegionFactory::region_name (region_name, mfs->name(), false);
1001
1002                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1003                                                                       _name, (*ci)->start, (*ci)->samples, region_name));
1004
1005
1006                 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->samples << " add a region\n";
1007
1008                 try {
1009                         PropertyList plist;
1010
1011                         /* start of this region is the offset between the start of its capture and the start of the whole pass */
1012                         plist.add (Properties::start, (*ci)->start - initial_capture);
1013                         plist.add (Properties::length, (*ci)->samples);
1014                         plist.add (Properties::length_beats, converter.from((*ci)->samples).to_double());
1015                         plist.add (Properties::name, region_name);
1016
1017                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1018                         midi_region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1019                         if (preroll_off > 0) {
1020                                 midi_region->trim_front ((*ci)->start - initial_capture + preroll_off);
1021                         }
1022                 }
1023
1024                 catch (failed_constructor& err) {
1025                         error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1026                         continue; /* XXX is this OK? */
1027                 }
1028
1029                 cerr << "add new region, len = " << (*ci)->samples << " @ " << (*ci)->start << endl;
1030
1031                 pl->add_region (midi_region, (*ci)->start + preroll_off, 1, _session.config.get_layered_record_mode ());
1032         }
1033
1034         pl->thaw ();
1035         _session.add_command (new StatefulDiffCommand (pl));
1036 }
1037
1038 void
1039 Track::use_captured_audio_sources (SourceList& srcs, CaptureInfos const & capture_info)
1040 {
1041         if (srcs.empty() || data_type() != DataType::AUDIO) {
1042                 return;
1043         }
1044
1045         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (srcs.front());
1046         boost::shared_ptr<Playlist> pl = _playlists[DataType::AUDIO];
1047         boost::shared_ptr<AudioRegion> region;
1048
1049         if (!afs || !pl) {
1050                 return;
1051         }
1052
1053         /* destructive tracks have a single, never changing region */
1054
1055         if (destructive()) {
1056
1057                 /* send a signal that any UI can pick up to do the right thing. there is
1058                    a small problem here in that a UI may need the peak data to be ready
1059                    for the data that was recorded and this isn't interlocked with that
1060                    process. this problem is deferred to the UI.
1061                  */
1062
1063                 pl->LayeringChanged(); // XXX this may not get the UI to do the right thing
1064                 return;
1065         }
1066
1067         string whole_file_region_name;
1068         whole_file_region_name = region_name_from_path (afs->name(), true);
1069
1070         /* Register a new region with the Session that
1071            describes the entire source. Do this first
1072            so that any sub-regions will obviously be
1073            children of this one (later!)
1074         */
1075
1076         try {
1077                 PropertyList plist;
1078
1079                 plist.add (Properties::start, afs->last_capture_start_sample());
1080                 plist.add (Properties::length, afs->length(0));
1081                 plist.add (Properties::name, whole_file_region_name);
1082                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1083                 rx->set_automatic (true);
1084                 rx->set_whole_file (true);
1085
1086                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1087                 region->special_set_position (afs->natural_position());
1088         }
1089
1090
1091         catch (failed_constructor& err) {
1092                 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1093                 /* XXX what now? */
1094         }
1095
1096         pl->clear_changes ();
1097         pl->set_capture_insertion_in_progress (true);
1098         pl->freeze ();
1099
1100         const samplepos_t preroll_off = _session.preroll_record_trim_len ();
1101         samplecnt_t buffer_position = afs->last_capture_start_sample ();
1102         CaptureInfos::const_iterator ci;
1103
1104         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1105
1106                 string region_name;
1107
1108                 RegionFactory::region_name (region_name, whole_file_region_name, false);
1109
1110                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1111                                                                       _name, (*ci)->start, (*ci)->samples, region_name, buffer_position));
1112
1113                 try {
1114
1115                         PropertyList plist;
1116
1117                         plist.add (Properties::start, buffer_position);
1118                         plist.add (Properties::length, (*ci)->samples);
1119                         plist.add (Properties::name, region_name);
1120
1121                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1122                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1123                         if (preroll_off > 0) {
1124                                 region->trim_front (buffer_position + preroll_off);
1125                         }
1126                 }
1127
1128                 catch (failed_constructor& err) {
1129                         error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1130                         continue; /* XXX is this OK? */
1131                 }
1132
1133                 pl->add_region (region, (*ci)->start + preroll_off, 1, _session.config.get_layered_record_mode());
1134                 pl->set_layer (region, DBL_MAX);
1135
1136                 buffer_position += (*ci)->samples;
1137         }
1138
1139         pl->thaw ();
1140         pl->set_capture_insertion_in_progress (false);
1141         _session.add_command (new StatefulDiffCommand (pl));
1142 }
1143
1144