committed INCOMPLETE 24bit filesource support
[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     $Id$
19 */
20 #include <pbd/error.h>
21 #include <sigc++/retype.h>
22 #include <sigc++/retype_return.h>
23 #include <sigc++/bind.h>
24
25 #include <ardour/audio_track.h>
26 #include <ardour/diskstream.h>
27 #include <ardour/session.h>
28 #include <ardour/redirect.h>
29 #include <ardour/audioregion.h>
30 #include <ardour/route_group_specialized.h>
31 #include <ardour/insert.h>
32 #include <ardour/audioplaylist.h>
33 #include <ardour/panner.h>
34 #include <ardour/utils.h>
35
36 #include "i18n.h"
37
38 using namespace std;
39 using namespace ARDOUR;
40
41 AudioTrack::AudioTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
42         : Route (sess, name, 1, -1, -1, -1, flag),
43           diskstream (0),
44           _midi_rec_enable_control (*this, _session.midi_port())
45 {
46         DiskStream::Flag dflags = DiskStream::Flag (0);
47
48         if (_flags & Hidden) {
49                 dflags = DiskStream::Flag (dflags | DiskStream::Hidden);
50         } else {
51                 dflags = DiskStream::Flag (dflags | DiskStream::Recordable);
52         }
53
54         if (mode == Destructive) {
55                 dflags = DiskStream::Flag (dflags | DiskStream::Destructive);
56                 cerr << "Creating a new audio track, destructive mode\n";
57         } else {
58                 cerr << "Creating a new audio track, NOT destructive mode\n";
59         }
60
61         DiskStream* ds = new DiskStream (_session, name, dflags);
62         
63         _declickable = true;
64         _freeze_record.state = NoFreeze;
65         _saved_meter_point = _meter_point;
66         _mode = mode;
67
68         set_diskstream (*ds, this);
69
70         // we do this even though Route already did it in it's init
71         reset_midi_control (_session.midi_port(), _session.get_midi_control());
72         
73 }
74
75 AudioTrack::AudioTrack (Session& sess, const XMLNode& node)
76         : Route (sess, "to be renamed", 0, 0, -1, -1),
77           diskstream (0),
78           _midi_rec_enable_control (*this, _session.midi_port())
79 {
80         _freeze_record.state = NoFreeze;
81         set_state (node);
82         _declickable = true;
83         _saved_meter_point = _meter_point;
84
85         // we do this even though Route already did it in it's init
86         reset_midi_control (_session.midi_port(), _session.get_midi_control());
87 }
88
89 AudioTrack::~AudioTrack ()
90 {
91         if (diskstream) {
92                 diskstream->unref();
93         }
94 }
95
96 int
97 AudioTrack::deprecated_use_diskstream_connections ()
98 {
99         if (diskstream->deprecated_io_node == 0) {
100                 return 0;
101         }
102
103         const XMLProperty* prop;
104         XMLNode& node (*diskstream->deprecated_io_node);
105
106         /* don't do this more than once. */
107
108         diskstream->deprecated_io_node = 0;
109
110         set_input_minimum (-1);
111         set_input_maximum (-1);
112         set_output_minimum (-1);
113         set_output_maximum (-1);
114         
115         if ((prop = node.property ("gain")) != 0) {
116                 set_gain (atof (prop->value().c_str()), this);
117                 _gain = _desired_gain;
118         }
119
120         if ((prop = node.property ("input-connection")) != 0) {
121                 Connection* c = _session.connection_by_name (prop->value());
122                 
123                 if (c == 0) {
124                         error << string_compose(_("Unknown connection \"%1\" listed for input of %2"), prop->value(), _name) << endmsg;
125                         
126                         if ((c = _session.connection_by_name (_("in 1"))) == 0) {
127                                 error << _("No input connections available as a replacement")
128                                 << endmsg;
129                                 return -1;
130                         } else {
131                                 info << string_compose (_("Connection %1 was not available - \"in 1\" used instead"), prop->value())
132                                << endmsg;
133                         }
134                 }
135
136                 use_input_connection (*c, this);
137
138         } else if ((prop = node.property ("inputs")) != 0) {
139                 if (set_inputs (prop->value())) {
140                         error << string_compose(_("improper input channel list in XML node (%1)"), prop->value()) << endmsg;
141                         return -1;
142                 }
143         }
144         
145         return 0;
146 }
147
148 int
149 AudioTrack::set_diskstream (DiskStream& ds, void *src)
150 {
151         if (diskstream) {
152                 diskstream->unref();
153         }
154
155         diskstream = &ds.ref();
156         diskstream->set_io (*this);
157         diskstream->set_destructive (_mode == Destructive);
158
159         if (diskstream->deprecated_io_node) {
160
161                 if (!connecting_legal) {
162                         ConnectingLegal.connect (mem_fun (*this, &AudioTrack::deprecated_use_diskstream_connections));
163                 } else {
164                         deprecated_use_diskstream_connections ();
165                 }
166         }
167
168         diskstream->set_record_enabled (false, this);
169         diskstream->monitor_input (false);
170
171         ic_connection.disconnect();
172         ic_connection = input_changed.connect (mem_fun (*diskstream, &DiskStream::handle_input_change));
173
174         diskstream_changed (src); /* EMIT SIGNAL */
175
176         return 0;
177 }       
178
179 int 
180 AudioTrack::use_diskstream (string name)
181 {
182         DiskStream *dstream;
183
184         if ((dstream = _session.diskstream_by_name (name)) == 0) {
185           error << string_compose(_("AudioTrack: diskstream \"%1\" not known by session"), name) << endmsg;
186                 return -1;
187         }
188         
189         return set_diskstream (*dstream, this);
190 }
191
192 int 
193 AudioTrack::use_diskstream (id_t id)
194 {
195         DiskStream *dstream;
196
197         if ((dstream = _session.diskstream_by_id (id)) == 0) {
198                 error << string_compose(_("AudioTrack: diskstream \"%1\" not known by session"), id) << endmsg;
199                 return -1;
200         }
201         
202         return set_diskstream (*dstream, this);
203 }
204
205 bool
206 AudioTrack::record_enabled () const
207 {
208         return diskstream->record_enabled ();
209 }
210
211 void
212 AudioTrack::set_record_enable (bool yn, void *src)
213 {
214         if (_freeze_record.state == Frozen) {
215                 return;
216         }
217
218         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
219                 _mix_group->apply (&AudioTrack::set_record_enable, yn, _mix_group);
220                 return;
221         }
222
223         /* keep track of the meter point as it was before we rec-enabled */
224
225         if (!diskstream->record_enabled()) {
226                 _saved_meter_point = _meter_point;
227         }
228         
229         diskstream->set_record_enabled (yn, src);
230
231         if (diskstream->record_enabled()) {
232                 set_meter_point (MeterInput, this);
233         } else {
234                 set_meter_point (_saved_meter_point, this);
235         }
236
237         if (_session.get_midi_feedback()) {
238                 _midi_rec_enable_control.send_feedback (record_enabled());
239         }
240
241 }
242
243 void
244 AudioTrack::set_meter_point (MeterPoint p, void *src)
245 {
246         Route::set_meter_point (p, src);
247 }
248
249 XMLNode&
250 AudioTrack::state(bool full_state)
251 {
252         XMLNode& track_state (Route::state (full_state));
253         char buf[64];
254
255         /* we don't return diskstream state because we don't
256            own the diskstream exclusively. control of the diskstream
257            state is ceded to the Session, even if we create the
258            diskstream.
259         */
260
261         snprintf (buf, sizeof (buf), "%" PRIu64, diskstream->id());
262         track_state.add_property ("diskstream-id", buf);
263
264         return track_state;
265 }
266
267 int
268 AudioTrack::set_state (const XMLNode& node)
269 {
270         const XMLProperty *prop;
271         XMLNodeConstIterator iter;
272         XMLNodeList midi_kids;
273
274         if (Route::set_state (node)) {
275                 return -1;
276         }
277
278         if ((prop = node.property (X_("mode"))) != 0) {
279                 if (prop->value() == X_("normal")) {
280                         _mode = Normal;
281                 } else if (prop->value() == X_("destructive")) {
282                         _mode = Destructive;
283                 } else {
284                         warning << string_compose ("unknown audio track mode \"%1\" seen and ignored", prop->value()) << endmsg;
285                         _mode = Normal;
286                 }
287         } else {
288                 _mode = Normal;
289         }
290
291         midi_kids = node.children ("MIDI");
292         
293         for (iter = midi_kids.begin(); iter != midi_kids.end(); ++iter) {
294         
295                 XMLNodeList kids;
296                 XMLNodeConstIterator miter;
297                 XMLNode*    child;
298
299                 kids = (*iter)->children ();
300
301                 for (miter = kids.begin(); miter != kids.end(); ++miter) {
302
303                         child =* miter;
304
305                         if (child->name() == "rec_enable") {
306                         
307                                 MIDI::eventType ev = MIDI::on; /* initialize to keep gcc happy */
308                                 MIDI::byte additional = 0;  /* ditto */
309                                 MIDI::channel_t chn = 0;    /* ditto */
310
311                                 if (get_midi_node_info (child, ev, chn, additional)) {
312                                         _midi_rec_enable_control.set_control_type (chn, ev, additional);
313                                 } else {
314                                   error << string_compose(_("MIDI rec_enable control specification for %1 is incomplete, so it has been ignored"), _name) << endmsg;
315                                 }
316                         }
317                 }
318         }
319
320         
321         if ((prop = node.property ("diskstream-id")) == 0) {
322                 
323                 /* some old sessions use the diskstream name rather than the ID */
324
325                 if ((prop = node.property ("diskstream")) == 0) {
326                         fatal << _("programming error: AudioTrack given state without diskstream!") << endmsg;
327                         /*NOTREACHED*/
328                         return -1;
329                 }
330
331                 if (use_diskstream (prop->value())) {
332                         return -1;
333                 }
334
335         } else {
336                 
337                 id_t id = strtoull (prop->value().c_str(), 0, 10);
338                 
339                 if (use_diskstream (id)) {
340                         return -1;
341                 }
342         }
343
344
345         XMLNodeList nlist;
346         XMLNodeConstIterator niter;
347         XMLNode *child;
348
349         nlist = node.children();
350         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
351                 child = *niter;
352
353                 if (child->name() == X_("remote_control")) {
354                         if ((prop = child->property (X_("id"))) != 0) {
355                                 int32_t x;
356                                 sscanf (prop->value().c_str(), "%d", &x);
357                                 set_remote_control_id (x);
358                         }
359                 }
360         }
361
362         pending_state = const_cast<XMLNode*> (&node);
363
364         _session.StateReady.connect (mem_fun (*this, &AudioTrack::set_state_part_two));
365
366         return 0;
367 }
368
369 XMLNode& 
370 AudioTrack::get_state()
371 {
372         XMLNode& root (Route::get_state());
373         XMLNode* freeze_node;
374         char buf[32];
375
376         if (_freeze_record.playlist) {
377                 XMLNode* inode;
378
379                 freeze_node = new XMLNode (X_("freeze-info"));
380                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
381                 snprintf (buf, sizeof (buf), "%d", (int) _freeze_record.state);
382                 freeze_node->add_property ("state", buf);
383
384                 for (vector<FreezeRecordInsertInfo*>::iterator i = _freeze_record.insert_info.begin(); i != _freeze_record.insert_info.end(); ++i) {
385                         inode = new XMLNode (X_("insert"));
386                         snprintf (buf, sizeof (buf), "%" PRIu64, (*i)->id);
387                         inode->add_property (X_("id"), buf);
388                         inode->add_child_copy ((*i)->state);
389                 
390                         freeze_node->add_child_nocopy (*inode);
391                 }
392
393                 root.add_child_nocopy (*freeze_node);
394         }
395
396         /* Alignment: act as a proxy for the diskstream */
397         
398         XMLNode* align_node = new XMLNode (X_("alignment"));
399         switch (diskstream->alignment_style()) {
400         case ExistingMaterial:
401                 snprintf (buf, sizeof (buf), X_("existing"));
402                 break;
403         case CaptureTime:
404                 snprintf (buf, sizeof (buf), X_("capture"));
405                 break;
406         }
407         align_node->add_property (X_("style"), buf);
408         root.add_child_nocopy (*align_node);
409
410         /* MIDI control */
411
412         MIDI::channel_t chn;
413         MIDI::eventType ev;
414         MIDI::byte      additional;
415         XMLNode*        midi_node = 0;
416         XMLNode*        child;
417         XMLNodeList     midikids;
418
419         midikids = root.children ("MIDI");
420         if (!midikids.empty()) {
421                 midi_node = midikids.front();
422         }
423         else {
424                 midi_node = root.add_child ("MIDI");
425         }
426                 
427         if (_midi_rec_enable_control.get_control_info (chn, ev, additional) && midi_node) {
428
429                 child = midi_node->add_child ("rec_enable");
430                 set_midi_node_info (child, ev, chn, additional);
431         }
432
433         XMLNode* remote_control_node = new XMLNode (X_("remote_control"));
434         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
435         remote_control_node->add_property (X_("id"), buf);
436         root.add_child_nocopy (*remote_control_node);
437
438         switch (_mode) {
439         case Normal:
440                 root.add_property (X_("mode"), X_("normal"));
441                 break;
442         case Destructive:
443                 root.add_property (X_("mode"), X_("destructive"));
444                 break;
445         }
446
447         return root;
448 }
449
450 void
451 AudioTrack::set_state_part_two ()
452 {
453         XMLNode* fnode;
454         XMLProperty* prop;
455         LocaleGuard lg (X_("POSIX"));
456
457         /* This is called after all session state has been restored but before
458            have been made ports and connections are established.
459         */
460
461         if (pending_state == 0) {
462                 return;
463         }
464
465         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
466
467                 
468                 _freeze_record.have_mementos = false;
469                 _freeze_record.state = Frozen;
470                 
471                 for (vector<FreezeRecordInsertInfo*>::iterator i = _freeze_record.insert_info.begin(); i != _freeze_record.insert_info.end(); ++i) {
472                         delete *i;
473                 }
474                 _freeze_record.insert_info.clear ();
475                 
476                 if ((prop = fnode->property (X_("playlist"))) != 0) {
477                         Playlist* pl = _session.playlist_by_name (prop->value());
478                         if (pl) {
479                                 _freeze_record.playlist = dynamic_cast<AudioPlaylist*> (pl);
480                         } else {
481                                 _freeze_record.playlist = 0;
482                                 _freeze_record.state = NoFreeze;
483                         return;
484                         }
485                 }
486                 
487                 if ((prop = fnode->property (X_("state"))) != 0) {
488                         _freeze_record.state = (FreezeState) atoi (prop->value().c_str());
489                 }
490                 
491                 XMLNodeConstIterator citer;
492                 XMLNodeList clist = fnode->children();
493                 
494                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
495                         if ((*citer)->name() != X_("insert")) {
496                                 continue;
497                         }
498                         
499                         if ((prop = (*citer)->property (X_("id"))) == 0) {
500                                 continue;
501                         }
502                         
503                         FreezeRecordInsertInfo* frii = new FreezeRecordInsertInfo (*((*citer)->children().front()));
504                         frii->insert = 0;
505                         sscanf (prop->value().c_str(), "%" PRIu64, &frii->id);
506                         _freeze_record.insert_info.push_back (frii);
507                 }
508         }
509
510         /* Alignment: act as a proxy for the diskstream */
511
512         if ((fnode = find_named_node (*pending_state, X_("alignment"))) != 0) {
513
514                 if ((prop = fnode->property (X_("style"))) != 0) {
515                         if (prop->value() == "existing") {
516                                 diskstream->set_persistent_align_style (ExistingMaterial);
517                         } else if (prop->value() == "capture") {
518                                 diskstream->set_persistent_align_style (CaptureTime);
519                         }
520                 }
521         }
522         return;
523 }       
524
525 uint32_t
526 AudioTrack::n_process_buffers ()
527 {
528         return max ((uint32_t) diskstream->n_channels(), redirect_max_outs);
529 }
530
531 void
532 AudioTrack::passthru_silence (jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t nframes, jack_nframes_t offset, int declick, bool meter)
533 {
534         uint32_t nbufs = n_process_buffers ();
535         process_output_buffers (_session.get_silent_buffers (nbufs), nbufs, start_frame, end_frame, nframes, offset, true, declick, meter);
536 }
537
538 int 
539 AudioTrack::no_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
540                      bool session_state_changing, bool can_record, bool rec_monitors_input)
541 {
542         if (n_outputs() == 0) {
543                 return 0;
544         }
545
546         if (!_active) {
547                 silence (nframes, offset);
548                 return 0;
549         }
550
551         if (session_state_changing) {
552
553                 /* XXX is this safe to do against transport state changes? */
554
555                 passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
556                 return 0;
557         }
558
559         diskstream->check_record_status (start_frame, nframes, can_record);
560
561         bool send_silence;
562         
563         if (_have_internal_generator) {
564                 /* since the instrument has no input streams,
565                    there is no reason to send any signal
566                    into the route.
567                 */
568                 send_silence = true;
569         } else {
570
571                 if (_session.get_auto_input()) {
572                         if (Config->get_use_sw_monitoring()) {
573                                 send_silence = false;
574                         } else {
575                                 send_silence = true;
576                         }
577                 } else {
578                         if (diskstream->record_enabled()) {
579                                 if (Config->get_use_sw_monitoring()) {
580                                         send_silence = false;
581                                 } else {
582                                         send_silence = true;
583                                 }
584                         } else {
585                                 send_silence = true;
586                         }
587                 }
588         }
589
590         apply_gain_automation = false;
591
592         if (send_silence) {
593                 
594                 /* if we're sending silence, but we want the meters to show levels for the signal,
595                    meter right here.
596                 */
597                 
598                 if (_have_internal_generator) {
599                         passthru_silence (start_frame, end_frame, nframes, offset, 0, true);
600                 } else {
601                         if (_meter_point == MeterInput) {
602                                 just_meter_input (start_frame, end_frame, nframes, offset);
603                         }
604                         passthru_silence (start_frame, end_frame, nframes, offset, 0, false);
605                 }
606
607         } else {
608         
609                 /* we're sending signal, but we may still want to meter the input. 
610                  */
611
612                 passthru (start_frame, end_frame, nframes, offset, 0, (_meter_point == MeterInput));
613         }
614
615         return 0;
616 }
617
618 int
619 AudioTrack::roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, int declick,
620                   bool can_record, bool rec_monitors_input)
621 {
622         int dret;
623         Sample* b;
624         Sample* tmpb;
625         jack_nframes_t transport_frame;
626
627         {
628                 TentativeRWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
629                 if (lm.locked()) {
630                         // automation snapshot can also be called from the non-rt context
631                         // and it uses the redirect list, so we take the lock out here
632                         automation_snapshot (start_frame);
633                 }
634         }
635         
636         if (n_outputs() == 0 && _redirects.empty()) {
637                 return 0;
638         }
639
640         if (!_active) {
641                 silence (nframes, offset);
642                 return 0;
643         }
644
645         transport_frame = _session.transport_frame();
646
647         if ((nframes = check_initial_delay (nframes, offset, transport_frame)) == 0) {
648                 /* need to do this so that the diskstream sets its
649                    playback distance to zero, thus causing diskstream::commit
650                    to do nothing.
651                 */
652                 return diskstream->process (transport_frame, 0, 0, can_record, rec_monitors_input);
653         } 
654
655         _silent = false;
656         apply_gain_automation = false;
657
658         if ((dret = diskstream->process (transport_frame, nframes, offset, can_record, rec_monitors_input)) != 0) {
659                 
660                 silence (nframes, offset);
661
662                 return dret;
663         }
664
665         /* special condition applies */
666         
667         if (_meter_point == MeterInput) {
668                 just_meter_input (start_frame, end_frame, nframes, offset);
669         }
670
671         if (diskstream->record_enabled() && !can_record && !_session.get_auto_input()) {
672
673                 /* not actually recording, but we want to hear the input material anyway,
674                    at least potentially (depending on monitoring options)
675                  */
676
677                 passthru (start_frame, end_frame, nframes, offset, 0, true);
678
679         } else if ((b = diskstream->playback_buffer(0)) != 0) {
680
681                 /*
682                   XXX is it true that the earlier test on n_outputs()
683                   means that we can avoid checking it again here? i think
684                   so, because changing the i/o configuration of an IO
685                   requires holding the AudioEngine lock, which we hold
686                   while in the process() tree.
687                 */
688
689                 
690                 /* copy the diskstream data to all output buffers */
691                 
692                 vector<Sample*>& bufs = _session.get_passthru_buffers ();
693                 uint32_t limit = n_process_buffers ();
694                 
695                 uint32_t n;
696                 uint32_t i;
697
698
699                 for (i = 0, n = 1; i < limit; ++i, ++n) {
700                         memcpy (bufs[i], b, sizeof (Sample) * nframes); 
701                         if (n < diskstream->n_channels()) {
702                                 tmpb = diskstream->playback_buffer(n);
703                                 if (tmpb!=0) {
704                                         b = tmpb;
705                                 }
706                         }
707                 }
708
709                 /* don't waste time with automation if we're recording or we've just stopped (yes it can happen) */
710
711                 if (!diskstream->record_enabled() && _session.transport_rolling()) {
712                         TentativeLockMonitor am (automation_lock, __LINE__, __FILE__);
713                         
714                         if (am.locked() && gain_automation_playback()) {
715                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
716                         }
717                 }
718
719                 process_output_buffers (bufs, limit, start_frame, end_frame, nframes, offset, (!_session.get_record_enabled() || !_session.get_do_not_record_plugins()), declick, (_meter_point != MeterInput));
720                 
721         } else {
722                 /* problem with the diskstream; just be quiet for a bit */
723                 silence (nframes, offset);
724         }
725
726         return 0;
727 }
728
729 int
730 AudioTrack::silent_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
731                          bool can_record, bool rec_monitors_input)
732 {
733         if (n_outputs() == 0 && _redirects.empty()) {
734                 return 0;
735         }
736
737         if (!_active) {
738                 silence (nframes, offset);
739                 return 0;
740         }
741
742         _silent = true;
743         apply_gain_automation = false;
744
745         silence (nframes, offset);
746
747         return diskstream->process (_session.transport_frame() + offset, nframes, offset, can_record, rec_monitors_input);
748 }
749
750 void
751 AudioTrack::toggle_monitor_input ()
752 {
753         for (vector<Port*>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
754                 (*i)->request_monitor_input(!(*i)->monitoring_input());
755         }
756 }
757
758 int
759 AudioTrack::set_name (string str, void *src)
760 {
761         if (record_enabled() && _session.actively_recording()) {
762                 /* this messes things up if done while recording */
763                 return -1;
764         }
765
766         diskstream->set_name (str, src);
767         return IO::set_name (str, src);
768 }
769
770 int
771 AudioTrack::export_stuff (vector<Sample*>& buffers, char * workbuf, uint32_t nbufs, jack_nframes_t start, jack_nframes_t nframes)
772 {
773         gain_t  gain_automation[nframes];
774         gain_t  gain_buffer[nframes];
775         float   mix_buffer[nframes];
776         RedirectList::iterator i;
777         bool post_fader_work = false;
778         gain_t this_gain = _gain;
779         vector<Sample*>::iterator bi;
780         Sample * b;
781         
782         RWLockMonitor rlock (redirect_lock, false, __LINE__, __FILE__);
783                 
784         if (diskstream->playlist()->read (buffers[0], mix_buffer, gain_buffer, workbuf, start, nframes) != nframes) {
785                 return -1;
786         }
787
788         uint32_t n=1;
789         bi = buffers.begin();
790         b = buffers[0];
791         ++bi;
792         for (; bi != buffers.end(); ++bi, ++n) {
793                 if (n < diskstream->n_channels()) {
794                         if (diskstream->playlist()->read ((*bi), mix_buffer, gain_buffer, workbuf, start, nframes, n) != nframes) {
795                                 return -1;
796                         }
797                         b = (*bi);
798                 }
799                 else {
800                         /* duplicate last across remaining buffers */
801                         memcpy ((*bi), b, sizeof (Sample) * nframes); 
802                 }
803         }
804
805
806         /* note: only run inserts during export. other layers in the machinery
807            will already have checked that there are no external port inserts.
808         */
809         
810         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
811                 Insert *insert;
812                 
813                 if ((insert = dynamic_cast<Insert*>(*i)) != 0) {
814                         switch (insert->placement()) {
815                         case PreFader:
816                                 insert->run (buffers, nbufs, nframes, 0);
817                                 break;
818                         case PostFader:
819                                 post_fader_work = true;
820                                 break;
821                         }
822                 }
823         }
824         
825         if (_gain_automation_curve.automation_state() == Play) {
826                 
827                 _gain_automation_curve.get_vector (start, start + nframes, gain_automation, nframes);
828
829                 for (bi = buffers.begin(); bi != buffers.end(); ++bi) {
830                         Sample *b = *bi;
831                         for (jack_nframes_t n = 0; n < nframes; ++n) {
832                                 b[n] *= gain_automation[n];
833                         }
834                 }
835
836         } else {
837
838                 for (bi = buffers.begin(); bi != buffers.end(); ++bi) {
839                         Sample *b = *bi;
840                         for (jack_nframes_t n = 0; n < nframes; ++n) {
841                                 b[n] *= this_gain;
842                         }
843                 }
844         }
845
846         if (post_fader_work) {
847
848                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
849                         PluginInsert *insert;
850                         
851                         if ((insert = dynamic_cast<PluginInsert*>(*i)) != 0) {
852                                 switch ((*i)->placement()) {
853                                 case PreFader:
854                                         break;
855                                 case PostFader:
856                                         insert->run (buffers, nbufs, nframes, 0);
857                                         break;
858                                 }
859                         }
860                 }
861         } 
862
863         return 0;
864 }
865
866 void
867 AudioTrack::set_latency_delay (jack_nframes_t longest_session_latency)
868 {
869         Route::set_latency_delay (longest_session_latency);
870         diskstream->set_roll_delay (_roll_delay);
871 }
872
873 jack_nframes_t
874 AudioTrack::update_total_latency ()
875 {
876         _own_latency = 0;
877
878         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
879                 if ((*i)->active ()) {
880                         _own_latency += (*i)->latency ();
881                 }
882         }
883
884         set_port_latency (_own_latency);
885
886         return _own_latency;
887 }
888
889 void
890 AudioTrack::bounce (InterThreadInfo& itt)
891 {
892         vector<Source*> srcs;
893         _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
894 }
895
896
897 void
898 AudioTrack::bounce_range (jack_nframes_t start, jack_nframes_t end, InterThreadInfo& itt)
899 {
900         vector<Source*> srcs;
901         _session.write_one_track (*this, start, end, false, srcs, itt);
902 }
903
904 void
905 AudioTrack::freeze (InterThreadInfo& itt)
906 {
907         Insert* insert;
908         vector<Source*> srcs;
909         string new_playlist_name;
910         Playlist* new_playlist;
911         string dir;
912         AudioRegion* region;
913         string region_name;
914         
915         if ((_freeze_record.playlist = diskstream->playlist()) == 0) {
916                 return;
917         }
918
919         uint32_t n = 1;
920
921         while (n < (UINT_MAX-1)) {
922          
923                 string candidate;
924                 
925                 candidate = string_compose ("<F%2>%1", _freeze_record.playlist->name(), n);
926
927                 if (_session.playlist_by_name (candidate) == 0) {
928                         new_playlist_name = candidate;
929                         break;
930                 }
931
932                 ++n;
933
934         } 
935
936         if (n == (UINT_MAX-1)) {
937           error << string_compose (X_("There Are too many frozen versions of playlist \"%1\""
938                             " to create another one"), _freeze_record.playlist->name())
939                << endmsg;
940                 return;
941         }
942
943         if (_session.write_one_track (*this, 0, _session.current_end_frame(), true, srcs, itt)) {
944                 return;
945         }
946
947         _freeze_record.insert_info.clear ();
948         _freeze_record.have_mementos = true;
949
950         {
951                 RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__);
952                 
953                 for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); ++r) {
954                         
955                         if ((insert = dynamic_cast<Insert*>(*r)) != 0) {
956                                 
957                                 FreezeRecordInsertInfo* frii  = new FreezeRecordInsertInfo ((*r)->get_state());
958                                 
959                                 frii->insert = insert;
960                                 frii->id = insert->id();
961                                 frii->memento = (*r)->get_memento();
962                                 
963                                 _freeze_record.insert_info.push_back (frii);
964                                 
965                                 /* now deactivate the insert */
966                                 
967                                 insert->set_active (false, this);
968                         }
969                 }
970         }
971
972         new_playlist = new AudioPlaylist (_session, new_playlist_name, false);
973         region_name = new_playlist_name;
974
975         /* create a new region from all filesources, keep it private */
976
977         region = new AudioRegion (srcs, 0, srcs[0]->length(), 
978                                   region_name, 0, 
979                                   (AudioRegion::Flag) (AudioRegion::WholeFile|AudioRegion::DefaultFlags),
980                                   false);
981
982         new_playlist->set_orig_diskstream_id (diskstream->id());
983         new_playlist->add_region (*region, 0);
984         new_playlist->set_frozen (true);
985         region->set_locked (true);
986
987         diskstream->use_playlist (dynamic_cast<AudioPlaylist*>(new_playlist));
988         diskstream->set_record_enabled (false, this);
989
990         _freeze_record.state = Frozen;
991         FreezeChange(); /* EMIT SIGNAL */
992 }
993
994 void
995 AudioTrack::unfreeze ()
996 {
997         if (_freeze_record.playlist) {
998                 diskstream->use_playlist (_freeze_record.playlist);
999
1000                 if (_freeze_record.have_mementos) {
1001
1002                         for (vector<FreezeRecordInsertInfo*>::iterator i = _freeze_record.insert_info.begin(); i != _freeze_record.insert_info.end(); ++i) {
1003                                 (*i)->memento ();
1004                         }
1005
1006                 } else {
1007
1008                         RWLockMonitor lm (redirect_lock, false, __LINE__, __FILE__); // should this be a write lock? jlc
1009                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1010                                 for (vector<FreezeRecordInsertInfo*>::iterator ii = _freeze_record.insert_info.begin(); ii != _freeze_record.insert_info.end(); ++ii) {
1011                                         if ((*ii)->id == (*i)->id()) {
1012                                                 (*i)->set_state (((*ii)->state));
1013                                                 break;
1014                                         }
1015                                 }
1016                         }
1017                 }
1018                 
1019                 _freeze_record.playlist = 0;
1020         }
1021
1022         _freeze_record.state = UnFrozen;
1023         FreezeChange (); /* EMIT SIGNAL */
1024 }
1025
1026 AudioTrack::FreezeRecord::~FreezeRecord ()
1027 {
1028         for (vector<FreezeRecordInsertInfo*>::iterator i = insert_info.begin(); i != insert_info.end(); ++i) {
1029                 delete *i;
1030         }
1031 }
1032
1033 AudioTrack::FreezeState
1034 AudioTrack::freeze_state() const
1035 {
1036         return _freeze_record.state;
1037 }
1038
1039
1040 void
1041 AudioTrack::reset_midi_control (MIDI::Port* port, bool on)
1042 {
1043         MIDI::channel_t chn;
1044         MIDI::eventType ev;
1045         MIDI::byte extra;
1046
1047         Route::reset_midi_control (port, on);
1048         
1049         _midi_rec_enable_control.get_control_info (chn, ev, extra);
1050         if (!on) {
1051                 chn = -1;
1052         }
1053         _midi_rec_enable_control.midi_rebind (port, chn);
1054 }
1055
1056 void
1057 AudioTrack::send_all_midi_feedback ()
1058 {
1059         if (_session.get_midi_feedback()) {
1060
1061                 Route::send_all_midi_feedback();
1062
1063                 _midi_rec_enable_control.send_feedback (record_enabled());
1064         }
1065 }
1066
1067
1068 AudioTrack::MIDIRecEnableControl::MIDIRecEnableControl (AudioTrack& s,  MIDI::Port* port)
1069         : MIDI::Controllable (port, 0), track (s), setting(false)
1070 {
1071         last_written = false; /* XXX need a good out of bound value */
1072 }
1073
1074 void
1075 AudioTrack::MIDIRecEnableControl::set_value (float val)
1076 {
1077         bool bval = ((val >= 0.5f) ? true: false);
1078         
1079         setting = true;
1080         track.set_record_enable (bval, this);
1081         setting = false;
1082 }
1083
1084 void
1085 AudioTrack::MIDIRecEnableControl::send_feedback (bool value)
1086 {
1087
1088         if (!setting && get_midi_feedback()) {
1089                 MIDI::byte val = (MIDI::byte) (value ? 127: 0);
1090                 MIDI::channel_t ch = 0;
1091                 MIDI::eventType ev = MIDI::none;
1092                 MIDI::byte additional = 0;
1093                 MIDI::EventTwoBytes data;
1094             
1095                 if (get_control_info (ch, ev, additional)) {
1096                         data.controller_number = additional;
1097                         data.value = val;
1098
1099                         track._session.send_midi_message (get_port(), ev, ch, data);
1100                 }
1101         }
1102         
1103 }
1104
1105 MIDI::byte*
1106 AudioTrack::MIDIRecEnableControl::write_feedback (MIDI::byte* buf, int32_t& bufsize, bool val, bool force)
1107 {
1108         if (get_midi_feedback()) {
1109
1110                 MIDI::channel_t ch = 0;
1111                 MIDI::eventType ev = MIDI::none;
1112                 MIDI::byte additional = 0;
1113
1114                 if (get_control_info (ch, ev, additional)) {
1115                         if (val != last_written || force) {
1116                                 *buf++ = ev & ch;
1117                                 *buf++ = additional; /* controller number */
1118                                 *buf++ = (MIDI::byte) (val ? 127: 0);
1119                                 last_written = val;
1120                                 bufsize -= 3;
1121                         }
1122                 }
1123         }
1124
1125         return buf;
1126 }
1127
1128 void
1129 AudioTrack::set_mode (TrackMode m)
1130 {
1131         if (diskstream) {
1132                 if (_mode != m) {
1133                         _mode = m;
1134                         diskstream->set_destructive (m == Destructive);
1135                         ModeChanged();
1136                 }
1137         }
1138 }