Use XMLNode::get/set_property in ARDOUR::AudioTrack class
[ardour.git] / libs / ardour / audio_track.cc
1 /*
2     Copyright (C) 2002 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 */
19
20 #include <boost/scoped_array.hpp>
21
22 #include "pbd/enumwriter.h"
23 #include "pbd/error.h"
24
25 #include "evoral/Curve.hpp"
26
27 #include "ardour/amp.h"
28 #include "ardour/audio_buffer.h"
29 #include "ardour/audio_diskstream.h"
30 #include "ardour/audio_track.h"
31 #include "ardour/audioplaylist.h"
32 #include "ardour/boost_debug.h"
33 #include "ardour/buffer_set.h"
34 #include "ardour/delivery.h"
35 #include "ardour/meter.h"
36 #include "ardour/monitor_control.h"
37 #include "ardour/playlist_factory.h"
38 #include "ardour/processor.h"
39 #include "ardour/profile.h"
40 #include "ardour/region.h"
41 #include "ardour/region_factory.h"
42 #include "ardour/session.h"
43 #include "ardour/session_playlists.h"
44 #include "ardour/source.h"
45 #include "ardour/types_convert.h"
46 #include "ardour/utils.h"
47
48 #include "pbd/i18n.h"
49
50 using namespace std;
51 using namespace ARDOUR;
52 using namespace PBD;
53
54 AudioTrack::AudioTrack (Session& sess, string name, TrackMode mode)
55         : Track (sess, name, PresentationInfo::AudioTrack, mode)
56 {
57 }
58
59 AudioTrack::~AudioTrack ()
60 {
61         if (_freeze_record.playlist && !_session.deletion_in_progress()) {
62                 _freeze_record.playlist->release();
63         }
64 }
65
66 boost::shared_ptr<Diskstream>
67 AudioTrack::create_diskstream ()
68 {
69         AudioDiskstream::Flag dflags = AudioDiskstream::Flag (AudioDiskstream::Recordable);
70
71         if (_mode == Destructive && !Profile->get_trx()) {
72                 dflags = AudioDiskstream::Flag (dflags | AudioDiskstream::Destructive);
73         } else if (_mode == NonLayered){
74                 dflags = AudioDiskstream::Flag(dflags | AudioDiskstream::NonLayered);
75         }
76
77         return boost::shared_ptr<AudioDiskstream> (new AudioDiskstream (_session, name(), dflags));
78 }
79
80 void
81 AudioTrack::set_diskstream (boost::shared_ptr<Diskstream> ds)
82 {
83         Track::set_diskstream (ds);
84
85         _diskstream->set_track (this);
86 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
87         if (Profile->get_trx()) {
88                 _diskstream->set_destructive (false);
89         } else {
90                 _diskstream->set_destructive (_mode == Destructive);
91         }
92         _diskstream->set_non_layered (_mode == NonLayered);
93 #endif
94
95         if (audio_diskstream()->deprecated_io_node) {
96
97                 if (!IO::connecting_legal) {
98                         IO::ConnectingLegal.connect_same_thread (*this, boost::bind (&AudioTrack::deprecated_use_diskstream_connections, this));
99                 } else {
100                         deprecated_use_diskstream_connections ();
101                 }
102         }
103
104         _diskstream->set_record_enabled (false);
105         _diskstream->request_input_monitoring (false);
106
107         DiskstreamChanged (); /* EMIT SIGNAL */
108 }
109
110 boost::shared_ptr<AudioDiskstream>
111 AudioTrack::audio_diskstream() const
112 {
113         return boost::dynamic_pointer_cast<AudioDiskstream>(_diskstream);
114 }
115
116 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
117 int
118 AudioTrack::set_mode (TrackMode m)
119 {
120         if (m != _mode) {
121
122                 if (!Profile->get_trx() && _diskstream->set_destructive (m == Destructive)) {
123                         return -1;
124                 }
125
126                 _diskstream->set_non_layered (m == NonLayered);
127                 _mode = m;
128
129                 TrackModeChanged (); /* EMIT SIGNAL */
130         }
131
132         return 0;
133 }
134
135 bool
136 AudioTrack::can_use_mode (TrackMode m, bool& bounce_required)
137 {
138         switch (m) {
139         case NonLayered:
140         case Normal:
141                 bounce_required = false;
142                 return true;
143
144         case Destructive:
145                 if (Profile->get_trx()) {
146                         return false;
147                 } else {
148                         return _diskstream->can_become_destructive (bounce_required);
149                 }
150                 break;
151
152         default:
153                 return false;
154         }
155 }
156 #endif
157
158 int
159 AudioTrack::deprecated_use_diskstream_connections ()
160 {
161         boost::shared_ptr<AudioDiskstream> diskstream = audio_diskstream();
162
163         if (diskstream->deprecated_io_node == 0) {
164                 return 0;
165         }
166
167         XMLNode& node (*diskstream->deprecated_io_node);
168
169         /* don't do this more than once. */
170
171         diskstream->deprecated_io_node = 0;
172
173         float val;
174         if (node.get_property ("gain", val)) {
175                 _amp->gain_control()->set_value (val, PBD::Controllable::NoGroup);
176         }
177
178         std::string str;
179         if (node.get_property ("input-connection", str)) {
180                 boost::shared_ptr<Bundle> c = _session.bundle_by_name (str);
181
182                 if (c == 0) {
183                         error << string_compose(_("Unknown bundle \"%1\" listed for input of %2"), str, _name) << endmsg;
184
185                         if ((c = _session.bundle_by_name (_("in 1"))) == 0) {
186                                 error << _("No input bundles available as a replacement")
187                                 << endmsg;
188                                 return -1;
189                         } else {
190                                 info << string_compose (_("Bundle %1 was not available - \"in 1\" used instead"), str)
191                                << endmsg;
192                         }
193                 }
194
195                 _input->connect_ports_to_bundle (c, true, this);
196
197         } else if (node.get_property ("inputs", str)) {
198                 if (_input->set_ports (str)) {
199                         error << string_compose(_("improper input channel list in XML node (%1)"), str) << endmsg;
200                         return -1;
201                 }
202         }
203
204         return 0;
205 }
206
207 int
208 AudioTrack::set_state (const XMLNode& node, int version)
209 {
210         if (!node.get_property (X_("mode"), _mode)) {
211                 _mode = Normal;
212         }
213
214         if (Profile->get_trx() && _mode == Destructive) {
215                 /* Tracks does not support destructive tracks and trying to
216                    handle it as a normal track would be wrong.
217                 */
218                 error << string_compose (_("%1: this session uses destructive tracks, which are not supported"), PROGRAM_NAME) << endmsg;
219                 return -1;
220         }
221
222         if (Track::set_state (node, version)) {
223                 return -1;
224         }
225
226         pending_state = const_cast<XMLNode*> (&node);
227
228         if (_session.state_of_the_state() & Session::Loading) {
229                 _session.StateReady.connect_same_thread (*this, boost::bind (&AudioTrack::set_state_part_two, this));
230         } else {
231                 set_state_part_two ();
232         }
233
234         return 0;
235 }
236
237 XMLNode&
238 AudioTrack::state (bool full_state)
239 {
240         XMLNode& root (Track::state(full_state));
241         XMLNode* freeze_node;
242
243         if (_freeze_record.playlist) {
244                 XMLNode* inode;
245
246                 freeze_node = new XMLNode (X_("freeze-info"));
247                 freeze_node->set_property ("playlist", _freeze_record.playlist->name());
248                 freeze_node->set_property ("state", _freeze_record.state);
249
250                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
251                         inode = new XMLNode (X_("processor"));
252                         inode->set_property (X_ ("id"), (*i)->id.to_s ());
253                         inode->add_child_copy ((*i)->state);
254
255                         freeze_node->add_child_nocopy (*inode);
256                 }
257
258                 root.add_child_nocopy (*freeze_node);
259         }
260
261         root.set_property (X_("mode"), _mode);
262
263         return root;
264 }
265
266 void
267 AudioTrack::set_state_part_two ()
268 {
269         XMLNode* fnode;
270         XMLProperty const * prop;
271         LocaleGuard lg;
272
273         /* This is called after all session state has been restored but before
274            have been made ports and connections are established.
275         */
276
277         if (pending_state == 0) {
278                 return;
279         }
280
281         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
282
283                 _freeze_record.state = Frozen;
284
285                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
286                         delete *i;
287                 }
288                 _freeze_record.processor_info.clear ();
289
290                 if ((prop = fnode->property (X_("playlist"))) != 0) {
291                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
292                         if (pl) {
293                                 _freeze_record.playlist = boost::dynamic_pointer_cast<AudioPlaylist> (pl);
294                                 _freeze_record.playlist->use();
295                         } else {
296                                 _freeze_record.playlist.reset ();
297                                 _freeze_record.state = NoFreeze;
298                         return;
299                         }
300                 }
301
302                 fnode->get_property (X_("state"), _freeze_record.state);
303
304                 XMLNodeConstIterator citer;
305                 XMLNodeList clist = fnode->children();
306
307                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
308                         if ((*citer)->name() != X_("processor")) {
309                                 continue;
310                         }
311
312                         if ((prop = (*citer)->property (X_("id"))) == 0) {
313                                 continue;
314                         }
315
316                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
317                                                                                    boost::shared_ptr<Processor>());
318                         frii->id = prop->value ();
319                         _freeze_record.processor_info.push_back (frii);
320                 }
321         }
322 }
323
324 /** @param need_butler to be set to true if this track now needs the butler, otherwise it can be left alone
325  *  or set to false.
326  */
327 int
328 AudioTrack::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
329 {
330         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
331
332         if (!lm.locked()) {
333                 boost::shared_ptr<AudioDiskstream> diskstream = audio_diskstream();
334                 framecnt_t playback_distance = diskstream->calculate_playback_distance(nframes);
335                 if (can_internal_playback_seek(::llabs(playback_distance))) {
336                         /* TODO should declick */
337                         internal_playback_seek(playback_distance);
338                 }
339                 return 0;
340         }
341
342         framepos_t transport_frame;
343         boost::shared_ptr<AudioDiskstream> diskstream = audio_diskstream();
344
345         if (n_outputs().n_total() == 0 && _processors.empty()) {
346                 return 0;
347         }
348
349         if (!_active) {
350                 silence (nframes);
351                 if (_meter_point == MeterInput && ((_monitoring_control->monitoring_choice() & MonitorInput) || _diskstream->record_enabled())) {
352                         _meter->reset();
353                 }
354                 return 0;
355         }
356
357         transport_frame = _session.transport_frame();
358
359         int dret;
360         framecnt_t playback_distance;
361
362         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
363
364                 /* need to do this so that the diskstream sets its
365                    playback distance to zero, thus causing diskstream::commit
366                    to do nothing.
367                 */
368
369                 BufferSet bufs; /* empty set, no matter - nothing will happen */
370
371                 dret = diskstream->process (bufs, transport_frame, 0, playback_distance, false);
372                 need_butler = diskstream->commit (playback_distance);
373                 return dret;
374         }
375
376         _silent = false;
377         _amp->apply_gain_automation(false);
378
379         BufferSet& bufs = _session.get_route_buffers (n_process_buffers ());
380
381         fill_buffers_with_input (bufs, _input, nframes);
382
383         if (_meter_point == MeterInput && ((_monitoring_control->monitoring_choice() & MonitorInput) || _diskstream->record_enabled())) {
384                 _meter->run (bufs, start_frame, end_frame, 1.0 /*speed()*/, nframes, true);
385         }
386
387         if ((dret = diskstream->process (bufs, transport_frame, nframes, playback_distance, (monitoring_state() == MonitoringDisk))) != 0) {
388                 need_butler = diskstream->commit (playback_distance);
389                 silence (nframes);
390                 return dret;
391         }
392
393         process_output_buffers (bufs, start_frame, end_frame, nframes, declick, (!diskstream->record_enabled() && _session.transport_rolling()));
394
395         flush_processor_buffers_locked (nframes);
396
397         need_butler = diskstream->commit (playback_distance);
398
399         return 0;
400 }
401
402 int
403 AudioTrack::export_stuff (BufferSet& buffers, framepos_t start, framecnt_t nframes,
404                           boost::shared_ptr<Processor> endpoint, bool include_endpoint, bool for_export, bool for_freeze)
405 {
406         boost::scoped_array<gain_t> gain_buffer (new gain_t[nframes]);
407         boost::scoped_array<Sample> mix_buffer (new Sample[nframes]);
408         boost::shared_ptr<AudioDiskstream> diskstream = audio_diskstream();
409
410         Glib::Threads::RWLock::ReaderLock rlock (_processor_lock);
411
412         boost::shared_ptr<AudioPlaylist> apl = boost::dynamic_pointer_cast<AudioPlaylist>(diskstream->playlist());
413
414         assert(apl);
415         assert(buffers.count().n_audio() >= 1);
416         assert ((framecnt_t) buffers.get_audio(0).capacity() >= nframes);
417
418         if (apl->read (buffers.get_audio(0).data(), mix_buffer.get(), gain_buffer.get(), start, nframes) != nframes) {
419                 return -1;
420         }
421
422         uint32_t n=1;
423         Sample* b = buffers.get_audio(0).data();
424         BufferSet::audio_iterator bi = buffers.audio_begin();
425         ++bi;
426         for ( ; bi != buffers.audio_end(); ++bi, ++n) {
427                 if (n < diskstream->n_channels().n_audio()) {
428                         if (apl->read (bi->data(), mix_buffer.get(), gain_buffer.get(), start, nframes, n) != nframes) {
429                                 return -1;
430                         }
431                         b = bi->data();
432                 } else {
433                         /* duplicate last across remaining buffers */
434                         memcpy (bi->data(), b, sizeof (Sample) * nframes);
435                 }
436         }
437
438         bounce_process (buffers, start, nframes, endpoint, include_endpoint, for_export, for_freeze);
439
440         return 0;
441 }
442
443 bool
444 AudioTrack::bounceable (boost::shared_ptr<Processor> endpoint, bool include_endpoint) const
445 {
446         if (!endpoint && !include_endpoint) {
447                 /* no processing - just read from the playlist and create new
448                    files: always possible.
449                 */
450                 return true;
451         }
452
453         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
454         uint32_t naudio = n_inputs().n_audio();
455
456         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
457
458                 /* if we're not including the endpoint, potentially stop
459                    right here before we test matching i/o valences.
460                 */
461
462                 if (!include_endpoint && (*r) == endpoint) {
463                         return true;
464                 }
465
466                 /* ignore any processors that do routing, because we will not
467                  * use them during a bounce/freeze/export operation.
468                  */
469
470                 if ((*r)->does_routing()) {
471                         continue;
472                 }
473
474                 /* does the output from the last considered processor match the
475                  * input to this one?
476                  */
477
478                 if (naudio != (*r)->input_streams().n_audio()) {
479                         return false;
480                 }
481
482                 /* we're including the endpoint - if we just hit it,
483                    then stop.
484                 */
485
486                 if ((*r) == endpoint) {
487                         return true;
488                 }
489
490                 /* save outputs of this processor to test against inputs
491                    of the next one.
492                 */
493
494                 naudio = (*r)->output_streams().n_audio();
495         }
496
497         return true;
498 }
499
500 boost::shared_ptr<Region>
501 AudioTrack::bounce (InterThreadInfo& itt)
502 {
503         return bounce_range (_session.current_start_frame(), _session.current_end_frame(), itt, main_outs(), false);
504 }
505
506 boost::shared_ptr<Region>
507 AudioTrack::bounce_range (framepos_t start, framepos_t end, InterThreadInfo& itt,
508                           boost::shared_ptr<Processor> endpoint, bool include_endpoint)
509 {
510         vector<boost::shared_ptr<Source> > srcs;
511         return _session.write_one_track (*this, start, end, false, srcs, itt, endpoint, include_endpoint, false, false);
512 }
513
514 void
515 AudioTrack::freeze_me (InterThreadInfo& itt)
516 {
517         vector<boost::shared_ptr<Source> > srcs;
518         string new_playlist_name;
519         boost::shared_ptr<Playlist> new_playlist;
520         string dir;
521         string region_name;
522         boost::shared_ptr<AudioDiskstream> diskstream = audio_diskstream();
523
524         if ((_freeze_record.playlist = boost::dynamic_pointer_cast<AudioPlaylist>(diskstream->playlist())) == 0) {
525                 return;
526         }
527
528         uint32_t n = 1;
529
530         while (n < (UINT_MAX-1)) {
531
532                 string candidate;
533
534                 candidate = string_compose ("<F%2>%1", _freeze_record.playlist->name(), n);
535
536                 if (_session.playlists->by_name (candidate) == 0) {
537                         new_playlist_name = candidate;
538                         break;
539                 }
540
541                 ++n;
542
543         }
544
545         if (n == (UINT_MAX-1)) {
546           error << string_compose (X_("There are too many frozen versions of playlist \"%1\""
547                             " to create another one"), _freeze_record.playlist->name())
548                << endmsg;
549                 return;
550         }
551
552         boost::shared_ptr<Region> res;
553
554         if ((res = _session.write_one_track (*this, _session.current_start_frame(), _session.current_end_frame(),
555                                         true, srcs, itt, main_outs(), false, false, true)) == 0) {
556                 return;
557         }
558
559         _freeze_record.processor_info.clear ();
560
561         {
562                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
563
564                 for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
565
566                         if ((*r)->does_routing() && (*r)->active()) {
567                                 break;
568                         }
569                         if (!boost::dynamic_pointer_cast<PeakMeter>(*r)) {
570
571                                 FreezeRecordProcessorInfo* frii  = new FreezeRecordProcessorInfo ((*r)->get_state(), (*r));
572
573                                 frii->id = (*r)->id();
574
575                                 _freeze_record.processor_info.push_back (frii);
576
577                                 /* now deactivate the processor, */
578                                 if (!boost::dynamic_pointer_cast<Amp>(*r)) {
579                                         (*r)->deactivate ();
580                                 }
581                         }
582
583                         _session.set_dirty ();
584                 }
585         }
586
587         new_playlist = PlaylistFactory::create (DataType::AUDIO, _session, new_playlist_name, false);
588
589         /* XXX need main outs automation state _freeze_record.pan_automation_state = _mainpanner->automation_state(); */
590
591         region_name = new_playlist_name;
592
593         /* create a new region from all filesources, keep it private */
594
595         PropertyList plist;
596
597         plist.add (Properties::start, 0);
598         plist.add (Properties::length, srcs[0]->length(srcs[0]->timeline_position()));
599         plist.add (Properties::name, region_name);
600         plist.add (Properties::whole_file, true);
601
602         boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist, false));
603
604         new_playlist->set_orig_track_id (id());
605         new_playlist->add_region (region, _session.current_start_frame());
606         new_playlist->set_frozen (true);
607         region->set_locked (true);
608
609         diskstream->use_playlist (boost::dynamic_pointer_cast<AudioPlaylist>(new_playlist));
610         diskstream->set_record_enabled (false);
611
612         _freeze_record.playlist->use(); // prevent deletion
613
614         /* reset stuff that has already been accounted for in the freeze process */
615
616         gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
617         gain_control()->set_automation_state (Off);
618
619         /* XXX need to use _main_outs _panner->set_automation_state (Off); */
620
621         _freeze_record.state = Frozen;
622         FreezeChange(); /* EMIT SIGNAL */
623 }
624
625 void
626 AudioTrack::unfreeze ()
627 {
628         if (_freeze_record.playlist) {
629                 _freeze_record.playlist->release();
630                 audio_diskstream()->use_playlist (_freeze_record.playlist);
631
632                 {
633                         Glib::Threads::RWLock::ReaderLock lm (_processor_lock); // should this be a write lock? jlc
634                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
635                                 for (vector<FreezeRecordProcessorInfo*>::iterator ii = _freeze_record.processor_info.begin(); ii != _freeze_record.processor_info.end(); ++ii) {
636                                         if ((*ii)->id == (*i)->id()) {
637                                                 (*i)->set_state (((*ii)->state), Stateful::current_state_version);
638                                                 break;
639                                         }
640                                 }
641                         }
642                 }
643
644                 _freeze_record.playlist.reset ();
645                 /* XXX need to use _main_outs _panner->set_automation_state (_freeze_record.pan_automation_state); */
646         }
647
648         _freeze_record.state = UnFrozen;
649         FreezeChange (); /* EMIT SIGNAL */
650 }
651
652 boost::shared_ptr<AudioFileSource>
653 AudioTrack::write_source (uint32_t n)
654 {
655         boost::shared_ptr<AudioDiskstream> ds = boost::dynamic_pointer_cast<AudioDiskstream> (_diskstream);
656         assert (ds);
657         return ds->write_source (n);
658 }
659
660 boost::shared_ptr<Diskstream>
661 AudioTrack::diskstream_factory (XMLNode const & node)
662 {
663         return boost::shared_ptr<Diskstream> (new AudioDiskstream (_session, node));
664 }