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