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