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