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