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