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