Only show user-presets in favorite sidebar
[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_track.h"
30 #include "ardour/audioplaylist.h"
31 #include "ardour/boost_debug.h"
32 #include "ardour/buffer_set.h"
33 #include "ardour/delivery.h"
34 #include "ardour/disk_reader.h"
35 #include "ardour/disk_writer.h"
36 #include "ardour/meter.h"
37 #include "ardour/monitor_control.h"
38 #include "ardour/playlist_factory.h"
39 #include "ardour/processor.h"
40 #include "ardour/profile.h"
41 #include "ardour/region.h"
42 #include "ardour/region_factory.h"
43 #include "ardour/session.h"
44 #include "ardour/session_playlists.h"
45 #include "ardour/source.h"
46 #include "ardour/types_convert.h"
47 #include "ardour/utils.h"
48
49 #include "pbd/i18n.h"
50
51 using namespace std;
52 using namespace ARDOUR;
53 using namespace PBD;
54
55 AudioTrack::AudioTrack (Session& sess, string name, TrackMode mode)
56         : Track (sess, name, PresentationInfo::AudioTrack, mode)
57 {
58 }
59
60 AudioTrack::~AudioTrack ()
61 {
62         if (_freeze_record.playlist && !_session.deletion_in_progress()) {
63                 _freeze_record.playlist->release();
64         }
65 }
66
67 MonitorState
68 AudioTrack::get_auto_monitoring_state () const
69 {
70         /* This is an implementation of the truth table in doc/monitor_modes.pdf;
71            I don't think it's ever going to be too pretty too look at.
72         */
73
74         bool const roll = _session.transport_rolling ();
75         bool const track_rec = _disk_writer->record_enabled ();
76         bool const auto_input = _session.config.get_auto_input ();
77         bool const software_monitor = Config->get_monitoring_model() == SoftwareMonitoring;
78         bool const tape_machine_mode = Config->get_tape_machine_mode ();
79         bool session_rec;
80
81         /* I suspect that just use actively_recording() is good enough all the
82          * time, but just to keep the semantics the same as they were before
83          * sept 26th 2012, we differentiate between the cases where punch is
84          * enabled and those where it is not.
85          *
86          * rg: sept 30 2017: Above is not the case: punch-in/out location is
87          * global session playhead position.
88          * When this method is called from process_output_buffers() we need
89          * to use delay-compensated route's process-position.
90          *
91          * NB. Disk reader/writer may also be offset by a same amount of time.
92          *
93          * Also keep in mind that _session.transport_rolling() is false during
94          * pre-roll but the disk already produces output.
95          *
96          * TODO: FIXME
97          */
98
99         if (_session.config.get_punch_in() || _session.config.get_punch_out()) {
100                 session_rec = _session.actively_recording ();
101         } else {
102                 session_rec = _session.get_record_enabled();
103         }
104
105         if (track_rec) {
106
107                 if (!session_rec && roll && auto_input) {
108                         return MonitoringDisk;
109                 } else {
110                         return software_monitor ? MonitoringInput : MonitoringSilence;
111                 }
112
113         } else {
114
115                 if (tape_machine_mode) {
116
117                         return MonitoringDisk;
118
119                 } else {
120
121                         if (!roll && auto_input) { 
122                                 return software_monitor ? MonitoringInput : MonitoringSilence;
123                         } else {
124                                 return MonitoringDisk;
125                         }
126
127                 }
128         }
129
130         abort(); /* NOTREACHED */
131         return MonitoringSilence;
132 }
133
134 int
135 AudioTrack::set_state (const XMLNode& node, int version)
136 {
137         if (!node.get_property (X_("mode"), _mode)) {
138                 _mode = Normal;
139         }
140
141         if (Profile->get_trx() && _mode == Destructive) {
142                 /* Tracks does not support destructive tracks and trying to
143                    handle it as a normal track would be wrong.
144                 */
145                 error << string_compose (_("%1: this session uses destructive tracks, which are not supported"), PROGRAM_NAME) << endmsg;
146                 return -1;
147         }
148
149         if (Track::set_state (node, version)) {
150                 return -1;
151         }
152
153         pending_state = const_cast<XMLNode*> (&node);
154
155         if (_session.state_of_the_state() & Session::Loading) {
156                 _session.StateReady.connect_same_thread (*this, boost::bind (&AudioTrack::set_state_part_two, this));
157         } else {
158                 set_state_part_two ();
159         }
160
161         return 0;
162 }
163
164 XMLNode&
165 AudioTrack::state (bool save_template)
166 {
167         XMLNode& root (Track::state (save_template));
168         XMLNode* freeze_node;
169
170         if (_freeze_record.playlist) {
171                 XMLNode* inode;
172
173                 freeze_node = new XMLNode (X_("freeze-info"));
174                 freeze_node->set_property ("playlist", _freeze_record.playlist->name());
175                 freeze_node->set_property ("state", _freeze_record.state);
176
177                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
178                         inode = new XMLNode (X_("processor"));
179                         inode->set_property (X_ ("id"), (*i)->id.to_s ());
180                         inode->add_child_copy ((*i)->state);
181
182                         freeze_node->add_child_nocopy (*inode);
183                 }
184
185                 root.add_child_nocopy (*freeze_node);
186         }
187
188         root.set_property (X_("mode"), _mode);
189
190         return root;
191 }
192
193 void
194 AudioTrack::set_state_part_two ()
195 {
196         XMLNode* fnode;
197         XMLProperty const * prop;
198
199         /* This is called after all session state has been restored but before
200            have been made ports and connections are established.
201         */
202
203         if (pending_state == 0) {
204                 return;
205         }
206
207         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
208
209                 _freeze_record.state = Frozen;
210
211                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
212                         delete *i;
213                 }
214                 _freeze_record.processor_info.clear ();
215
216                 if ((prop = fnode->property (X_("playlist"))) != 0) {
217                         boost::shared_ptr<Playlist> pl = _session.playlists->by_name (prop->value());
218                         if (pl) {
219                                 _freeze_record.playlist = boost::dynamic_pointer_cast<AudioPlaylist> (pl);
220                                 _freeze_record.playlist->use();
221                         } else {
222                                 _freeze_record.playlist.reset ();
223                                 _freeze_record.state = NoFreeze;
224                         return;
225                         }
226                 }
227
228                 fnode->get_property (X_("state"), _freeze_record.state);
229
230                 XMLNodeConstIterator citer;
231                 XMLNodeList clist = fnode->children();
232
233                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
234                         if ((*citer)->name() != X_("processor")) {
235                                 continue;
236                         }
237
238                         if ((prop = (*citer)->property (X_("id"))) == 0) {
239                                 continue;
240                         }
241
242                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
243                                                                                    boost::shared_ptr<Processor>());
244                         frii->id = prop->value ();
245                         _freeze_record.processor_info.push_back (frii);
246                 }
247         }
248 }
249
250 int
251 AudioTrack::export_stuff (BufferSet& buffers, samplepos_t start, samplecnt_t nframes,
252                           boost::shared_ptr<Processor> endpoint, bool include_endpoint, bool for_export, bool for_freeze)
253 {
254         boost::scoped_array<gain_t> gain_buffer (new gain_t[nframes]);
255         boost::scoped_array<Sample> mix_buffer (new Sample[nframes]);
256
257         Glib::Threads::RWLock::ReaderLock rlock (_processor_lock);
258
259         boost::shared_ptr<AudioPlaylist> apl = boost::dynamic_pointer_cast<AudioPlaylist>(playlist());
260
261         assert(apl);
262         assert(buffers.count().n_audio() >= 1);
263         assert ((samplecnt_t) buffers.get_audio(0).capacity() >= nframes);
264
265         if (apl->read (buffers.get_audio(0).data(), mix_buffer.get(), gain_buffer.get(), start, nframes) != nframes) {
266                 return -1;
267         }
268
269         uint32_t n=1;
270         Sample* b = buffers.get_audio(0).data();
271         BufferSet::audio_iterator bi = buffers.audio_begin();
272         ++bi;
273         for ( ; bi != buffers.audio_end(); ++bi, ++n) {
274                 if (n < _disk_reader->output_streams().n_audio()) {
275                         if (apl->read (bi->data(), mix_buffer.get(), gain_buffer.get(), start, nframes, n) != nframes) {
276                                 return -1;
277                         }
278                         b = bi->data();
279                 } else {
280                         /* duplicate last across remaining buffers */
281                         memcpy (bi->data(), b, sizeof (Sample) * nframes);
282                 }
283         }
284
285         bounce_process (buffers, start, nframes, endpoint, include_endpoint, for_export, for_freeze);
286
287         return 0;
288 }
289
290 bool
291 AudioTrack::bounceable (boost::shared_ptr<Processor> endpoint, bool include_endpoint) const
292 {
293         if (!endpoint && !include_endpoint) {
294                 /* no processing - just read from the playlist and create new
295                    files: always possible.
296                 */
297                 return true;
298         }
299
300         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
301         uint32_t naudio = n_inputs().n_audio();
302
303         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
304
305                 /* if we're not including the endpoint, potentially stop
306                    right here before we test matching i/o valences.
307                 */
308
309                 if (!include_endpoint && (*r) == endpoint) {
310                         return true;
311                 }
312
313                 /* ignore any processors that do routing, because we will not
314                  * use them during a bounce/freeze/export operation.
315                  */
316
317                 if ((*r)->does_routing()) {
318                         continue;
319                 }
320
321                 /* does the output from the last considered processor match the
322                  * input to this one?
323                  */
324
325                 if (naudio != (*r)->input_streams().n_audio()) {
326                         return false;
327                 }
328
329                 /* we're including the endpoint - if we just hit it,
330                    then stop.
331                 */
332
333                 if ((*r) == endpoint) {
334                         return true;
335                 }
336
337                 /* save outputs of this processor to test against inputs
338                    of the next one.
339                 */
340
341                 naudio = (*r)->output_streams().n_audio();
342         }
343
344         return true;
345 }
346
347 boost::shared_ptr<Region>
348 AudioTrack::bounce (InterThreadInfo& itt)
349 {
350         return bounce_range (_session.current_start_sample(), _session.current_end_sample(), itt, main_outs(), false);
351 }
352
353 boost::shared_ptr<Region>
354 AudioTrack::bounce_range (samplepos_t start, samplepos_t end, InterThreadInfo& itt,
355                           boost::shared_ptr<Processor> endpoint, bool include_endpoint)
356 {
357         vector<boost::shared_ptr<Source> > srcs;
358         return _session.write_one_track (*this, start, end, false, srcs, itt, endpoint, include_endpoint, false, false);
359 }
360
361 void
362 AudioTrack::freeze_me (InterThreadInfo& itt)
363 {
364         vector<boost::shared_ptr<Source> > srcs;
365         string new_playlist_name;
366         boost::shared_ptr<Playlist> new_playlist;
367         string dir;
368         string region_name;
369
370         if ((_freeze_record.playlist = boost::dynamic_pointer_cast<AudioPlaylist>(playlist())) == 0) {
371                 return;
372         }
373
374         uint32_t n = 1;
375
376         while (n < (UINT_MAX-1)) {
377
378                 string candidate;
379
380                 candidate = string_compose ("<F%2>%1", _freeze_record.playlist->name(), n);
381
382                 if (_session.playlists->by_name (candidate) == 0) {
383                         new_playlist_name = candidate;
384                         break;
385                 }
386
387                 ++n;
388
389         }
390
391         if (n == (UINT_MAX-1)) {
392           error << string_compose (X_("There are too many frozen versions of playlist \"%1\""
393                             " to create another one"), _freeze_record.playlist->name())
394                << endmsg;
395                 return;
396         }
397
398         boost::shared_ptr<Region> res;
399
400         if ((res = _session.write_one_track (*this, _session.current_start_sample(), _session.current_end_sample(),
401                                         true, srcs, itt, main_outs(), false, false, true)) == 0) {
402                 return;
403         }
404
405         _freeze_record.processor_info.clear ();
406
407         {
408                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
409
410                 for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
411
412                         if ((*r)->does_routing() && (*r)->active()) {
413                                 break;
414                         }
415                         if (!boost::dynamic_pointer_cast<PeakMeter>(*r)) {
416
417                                 FreezeRecordProcessorInfo* frii  = new FreezeRecordProcessorInfo ((*r)->get_state(), (*r));
418
419                                 frii->id = (*r)->id();
420
421                                 _freeze_record.processor_info.push_back (frii);
422
423                                 /* now deactivate the processor, */
424                                 if (!boost::dynamic_pointer_cast<Amp>(*r)) {
425                                         (*r)->deactivate ();
426                                 }
427                         }
428
429                         _session.set_dirty ();
430                 }
431         }
432
433         new_playlist = PlaylistFactory::create (DataType::AUDIO, _session, new_playlist_name, false);
434
435         /* XXX need main outs automation state _freeze_record.pan_automation_state = _mainpanner->automation_state(); */
436
437         region_name = new_playlist_name;
438
439         /* create a new region from all filesources, keep it private */
440
441         PropertyList plist;
442
443         plist.add (Properties::start, 0);
444         plist.add (Properties::length, srcs[0]->length(srcs[0]->timeline_position()));
445         plist.add (Properties::name, region_name);
446         plist.add (Properties::whole_file, true);
447
448         boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist, false));
449
450         new_playlist->set_orig_track_id (id());
451         new_playlist->add_region (region, _session.current_start_sample());
452         new_playlist->set_frozen (true);
453         region->set_locked (true);
454
455         use_playlist (DataType::AUDIO, boost::dynamic_pointer_cast<AudioPlaylist>(new_playlist));
456         _disk_writer->set_record_enabled (false);
457
458         _freeze_record.playlist->use(); // prevent deletion
459
460         /* reset stuff that has already been accounted for in the freeze process */
461
462         gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
463         gain_control()->set_automation_state (Off);
464
465         /* XXX need to use _main_outs _panner->set_automation_state (Off); */
466
467         _freeze_record.state = Frozen;
468         FreezeChange(); /* EMIT SIGNAL */
469 }
470
471 void
472 AudioTrack::unfreeze ()
473 {
474         if (_freeze_record.playlist) {
475                 _freeze_record.playlist->release();
476                 use_playlist (DataType::AUDIO, _freeze_record.playlist);
477
478                 {
479                         Glib::Threads::RWLock::ReaderLock lm (_processor_lock); // should this be a write lock? jlc
480                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
481                                 for (vector<FreezeRecordProcessorInfo*>::iterator ii = _freeze_record.processor_info.begin(); ii != _freeze_record.processor_info.end(); ++ii) {
482                                         if ((*ii)->id == (*i)->id()) {
483                                                 (*i)->set_state (((*ii)->state), Stateful::current_state_version);
484                                                 break;
485                                         }
486                                 }
487                         }
488                 }
489
490                 _freeze_record.playlist.reset ();
491                 /* XXX need to use _main_outs _panner->set_automation_state (_freeze_record.pan_automation_state); */
492         }
493
494         _freeze_record.state = UnFrozen;
495         FreezeChange (); /* EMIT SIGNAL */
496 }
497
498 boost::shared_ptr<AudioFileSource>
499 AudioTrack::write_source (uint32_t n)
500 {
501         assert (_disk_writer);
502         return _disk_writer->audio_write_source (n);
503 }