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