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