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