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