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