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