the return of VST support
[ardour.git] / libs / ardour / audio_diskstream.cc
1 /*
2     Copyright (C) 2000-2003 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: diskstream.cc 567 2006-06-07 14:54:12Z trutkin $
19 */
20
21 #include <fstream>
22 #include <cstdio>
23 #include <unistd.h>
24 #include <cmath>
25 #include <cerrno>
26 #include <string>
27 #include <climits>
28 #include <fcntl.h>
29 #include <cstdlib>
30 #include <ctime>
31 #include <sys/stat.h>
32 #include <sys/mman.h>
33
34 #include <pbd/error.h>
35 #include <pbd/basename.h>
36 #include <glibmm/thread.h>
37 #include <pbd/xml++.h>
38
39 #include <ardour/ardour.h>
40 #include <ardour/audioengine.h>
41 #include <ardour/audio_diskstream.h>
42 #include <ardour/utils.h>
43 #include <ardour/configuration.h>
44 #include <ardour/audiofilesource.h>
45 #include <ardour/destructive_filesource.h>
46 #include <ardour/send.h>
47 #include <ardour/audioplaylist.h>
48 #include <ardour/cycle_timer.h>
49 #include <ardour/audioregion.h>
50
51 #include "i18n.h"
52 #include <locale.h>
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57
58 jack_nframes_t AudioDiskstream::disk_io_chunk_frames;
59
60 sigc::signal<void,AudioDiskstream*>    AudioDiskstream::AudioDiskstreamCreated;
61 sigc::signal<void,list<AudioFileSource*>*> AudioDiskstream::DeleteSources;
62 sigc::signal<void>                AudioDiskstream::DiskOverrun;
63 sigc::signal<void>                AudioDiskstream::DiskUnderrun;
64
65 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Flag flag)
66         : _name (name),
67           _session (sess)
68 {
69         /* prevent any write sources from being created */
70
71         in_set_state = true;
72
73         init (flag);
74         use_new_playlist ();
75
76         in_set_state = false;
77
78         AudioDiskstreamCreated (this); /* EMIT SIGNAL */
79 }
80         
81 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
82         : _session (sess)
83         
84 {
85         in_set_state = true;
86         init (Recordable);
87
88         if (set_state (node)) {
89                 in_set_state = false;
90                 throw failed_constructor();
91         }
92
93         in_set_state = false;
94
95         if (destructive()) {
96                 use_destructive_playlist ();
97         }
98
99         AudioDiskstreamCreated (this); /* EMIT SIGNAL */
100 }
101
102 void
103 AudioDiskstream::init_channel (ChannelInfo &chan)
104 {
105         chan.playback_wrap_buffer = 0;
106         chan.capture_wrap_buffer = 0;
107         chan.speed_buffer = 0;
108         chan.peak_power = 0.0f;
109         chan.write_source = 0;
110         chan.source = 0;
111         chan.current_capture_buffer = 0;
112         chan.current_playback_buffer = 0;
113         chan.curr_capture_cnt = 0;
114         
115         chan.playback_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
116         chan.capture_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
117         chan.capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
118         
119         
120         /* touch the ringbuffer buffers, which will cause
121            them to be mapped into locked physical RAM if
122            we're running with mlockall(). this doesn't do
123            much if we're not.  
124         */
125         memset (chan.playback_buf->buffer(), 0, sizeof (Sample) * chan.playback_buf->bufsize());
126         memset (chan.capture_buf->buffer(), 0, sizeof (Sample) * chan.capture_buf->bufsize());
127         memset (chan.capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * chan.capture_transition_buf->bufsize());
128 }
129
130
131 void
132 AudioDiskstream::init (Flag f)
133 {
134         _id = new_id();
135         _refcnt = 0;
136         _flags = f;
137         _io = 0;
138         _alignment_style = ExistingMaterial;
139         _persistent_alignment_style = ExistingMaterial;
140         first_input_change = true;
141         _playlist = 0;
142         i_am_the_modifier = 0;
143         g_atomic_int_set (&_record_enabled, 0);
144         was_recording = false;
145         capture_start_frame = 0;
146         capture_captured = 0;
147         _visible_speed = 1.0f;
148         _actual_speed = 1.0f;
149         _buffer_reallocation_required = false;
150         _seek_required = false;
151         first_recordable_frame = max_frames;
152         last_recordable_frame = max_frames;
153         _roll_delay = 0;
154         _capture_offset = 0;
155         _processed = false;
156         _slaved = false;
157         adjust_capture_position = 0;
158         last_possibly_recording = 0;
159         loop_location = 0;
160         wrap_buffer_size = 0;
161         speed_buffer_size = 0;
162         last_phase = 0;
163         phi = (uint64_t) (0x1000000);
164         file_frame = 0;
165         playback_sample = 0;
166         playback_distance = 0;
167         _read_data_count = 0;
168         _write_data_count = 0;
169         deprecated_io_node = 0;
170
171         /* there are no channels at this point, so these
172            two calls just get speed_buffer_size and wrap_buffer
173            size setup without duplicating their code.
174         */
175
176         set_block_size (_session.get_block_size());
177         allocate_temporary_buffers ();
178
179         pending_overwrite = false;
180         overwrite_frame = 0;
181         overwrite_queued = false;
182         input_change_pending = NoChange;
183
184         add_channel ();
185         _n_channels = 1;
186 }
187
188 void
189 AudioDiskstream::destroy_channel (ChannelInfo &chan)
190 {
191         if (chan.write_source) {
192                 chan.write_source->release ();
193                 chan.write_source = 0;
194         }
195                 
196         if (chan.speed_buffer) {
197                 delete [] chan.speed_buffer;
198         }
199
200         if (chan.playback_wrap_buffer) {
201                 delete [] chan.playback_wrap_buffer;
202         }
203         if (chan.capture_wrap_buffer) {
204                 delete [] chan.capture_wrap_buffer;
205         }
206         
207         delete chan.playback_buf;
208         delete chan.capture_buf;
209         delete chan.capture_transition_buf;
210         
211         chan.playback_buf = 0;
212         chan.capture_buf = 0;
213 }
214
215 AudioDiskstream::~AudioDiskstream ()
216 {
217         Glib::Mutex::Lock lm (state_lock);
218
219         if (_playlist) {
220                 _playlist->unref ();
221         }
222
223         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
224                 destroy_channel((*chan));
225         }
226         
227         channels.clear();
228 }
229
230 void
231 AudioDiskstream::handle_input_change (IOChange change, void *src)
232 {
233         Glib::Mutex::Lock lm (state_lock);
234
235         if (!(input_change_pending & change)) {
236                 input_change_pending = IOChange (input_change_pending|change);
237                 _session.request_input_change_handling ();
238         }
239 }
240
241 void
242 AudioDiskstream::non_realtime_input_change ()
243 {
244         { 
245                 Glib::Mutex::Lock lm (state_lock);
246
247                 if (input_change_pending == NoChange) {
248                         return;
249                 }
250
251                 if (input_change_pending & ConfigurationChanged) {
252
253                         if (_io->n_inputs() > _n_channels) {
254                                 
255                                 // we need to add new channel infos
256                                 
257                                 int diff = _io->n_inputs() - channels.size();
258                                 
259                                 for (int i = 0; i < diff; ++i) {
260                                         add_channel ();
261                                 }
262                                 
263                 } else if (_io->n_inputs() < _n_channels) {
264                                 
265                                 // we need to get rid of channels
266                                 
267                                 int diff = channels.size() - _io->n_inputs();
268                                 
269                                 for (int i = 0; i < diff; ++i) {
270                                         remove_channel ();
271                                 }
272                         }
273                 } 
274
275                 get_input_sources ();
276                 set_capture_offset ();
277                 
278                 if (first_input_change) {
279                         set_align_style (_persistent_alignment_style);
280                         first_input_change = false;
281                 } else {
282                         set_align_style_from_io ();
283                 }
284
285                 input_change_pending = NoChange;
286         }
287
288         /* reset capture files */
289
290         reset_write_sources (false);
291
292         /* now refill channel buffers */
293
294         if (speed() != 1.0f || speed() != -1.0f) {
295                 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()));
296         }
297         else {
298                 seek (_session.transport_frame());
299         }
300 }
301
302 void
303 AudioDiskstream::get_input_sources ()
304 {
305         uint32_t ni = _io->n_inputs();
306         
307         for (uint32_t n = 0; n < ni; ++n) {
308                 
309                 const char **connections = _io->input(n)->get_connections ();
310                 ChannelInfo& chan = channels[n];
311                 
312                 if (connections == 0 || connections[0] == 0) {
313                         
314                         if (chan.source) {
315                                 // _source->disable_metering ();
316                         }
317                         
318                         chan.source = 0;
319                         
320                 } else {
321                         chan.source = _session.engine().get_port_by_name (connections[0]);
322                 }
323                 
324                 if (connections) {
325                         free (connections);
326                 }
327         }
328 }               
329
330 int
331 AudioDiskstream::find_and_use_playlist (const string& name)
332 {
333         Playlist* pl;
334         AudioPlaylist* playlist;
335                 
336         if ((pl = _session.get_playlist (name)) == 0) {
337                 error << string_compose(_("AudioDiskstream: Session doesn't know about a Playlist called \"%1\""), name) << endmsg;
338                 return -1;
339         }
340
341         if ((playlist = dynamic_cast<AudioPlaylist*> (pl)) == 0) {
342                 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
343                 return -1;
344         }
345
346         return use_playlist (playlist);
347 }
348
349 int
350 AudioDiskstream::use_playlist (AudioPlaylist* playlist)
351 {
352         {
353                 Glib::Mutex::Lock lm (state_lock);
354
355                 if (playlist == _playlist) {
356                         return 0;
357                 }
358
359                 plstate_connection.disconnect();
360                 plmod_connection.disconnect ();
361                 plgone_connection.disconnect ();
362
363                 if (_playlist) {
364                         _playlist->unref();
365                 }
366                         
367                 _playlist = playlist;
368                 _playlist->ref();
369
370                 if (!in_set_state && recordable()) {
371                         reset_write_sources (false);
372                 }
373                 
374                 plstate_connection = _playlist->StateChanged.connect (mem_fun (*this, &AudioDiskstream::playlist_changed));
375                 plmod_connection = _playlist->Modified.connect (mem_fun (*this, &AudioDiskstream::playlist_modified));
376                 plgone_connection = _playlist->GoingAway.connect (mem_fun (*this, &AudioDiskstream::playlist_deleted));
377         }
378
379         if (!overwrite_queued) {
380                 _session.request_overwrite_buffer (this);
381                 overwrite_queued = true;
382         }
383         
384         PlaylistChanged (); /* EMIT SIGNAL */
385         _session.set_dirty ();
386
387         return 0;
388 }
389
390 void
391 AudioDiskstream::playlist_deleted (Playlist* pl)
392 {
393         /* this catches an ordering issue with session destruction. playlists 
394            are destroyed before diskstreams. we have to invalidate any handles
395            we have to the playlist.
396         */
397
398         _playlist = 0;
399 }
400
401 int
402 AudioDiskstream::use_new_playlist ()
403 {
404         string newname;
405         AudioPlaylist* playlist;
406
407         if (!in_set_state && destructive()) {
408                 return 0;
409         }
410
411         if (_playlist) {
412                 newname = Playlist::bump_name (_playlist->name(), _session);
413         } else {
414                 newname = Playlist::bump_name (_name, _session);
415         }
416
417         if ((playlist = new AudioPlaylist (_session, newname, hidden())) != 0) {
418                 playlist->set_orig_diskstream_id (id());
419                 return use_playlist (playlist);
420         } else { 
421                 return -1;
422         }
423 }
424
425 int
426 AudioDiskstream::use_copy_playlist ()
427 {
428         if (destructive()) {
429                 return 0;
430         }
431
432         if (_playlist == 0) {
433                 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
434                 return -1;
435         }
436
437         string newname;
438         AudioPlaylist* playlist;
439
440         newname = Playlist::bump_name (_playlist->name(), _session);
441         
442         if ((playlist  = new AudioPlaylist (*_playlist, newname)) != 0) {
443                 playlist->set_orig_diskstream_id (id());
444                 return use_playlist (playlist);
445         } else { 
446                 return -1;
447         }
448 }
449
450 void
451 AudioDiskstream::setup_destructive_playlist ()
452 {
453         AudioRegion::SourceList srcs;
454
455         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
456                 srcs.push_back ((*chan).write_source);
457         }
458
459         /* a single full-sized region */
460
461         AudioRegion* region = new AudioRegion (srcs, 0, max_frames, _name);
462         _playlist->add_region (*region, 0);             
463 }
464
465 void
466 AudioDiskstream::use_destructive_playlist ()
467 {
468         /* use the sources associated with the single full-extent region */
469         
470         Playlist::RegionList* rl = _playlist->regions_at (0);
471
472         if (rl->empty()) {
473                 reset_write_sources (false, true);
474                 return;
475         }
476
477         AudioRegion* region = dynamic_cast<AudioRegion*> (rl->front());
478
479         if (region == 0) {
480                 throw failed_constructor();
481         }
482
483         delete rl;
484
485         uint32_t n;
486         ChannelList::iterator chan;
487
488         for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
489                 (*chan).write_source = dynamic_cast<AudioFileSource*>(&region->source (n));
490                 (*chan).write_source->set_allow_remove_if_empty (false);
491         }
492
493         /* the source list will never be reset for a destructive track */
494 }
495
496 void
497 AudioDiskstream::set_io (IO& io)
498 {
499         _io = &io;
500         set_align_style_from_io ();
501 }
502
503 int
504 AudioDiskstream::set_name (string str, void *src)
505 {
506         if (str != _name) {
507                 _playlist->set_name (str);
508                 _name = str;
509                 
510                 if (!in_set_state && recordable()) {
511                         /* rename existing capture files so that they have the correct name */
512                         return rename_write_sources ();
513                 } else {
514                         return -1;
515                 }
516         }
517
518         return 0;
519 }
520
521 void
522 AudioDiskstream::set_speed (double sp)
523 {
524         _session.request_diskstream_speed (*this, sp);
525
526         /* to force a rebuffering at the right place */
527         playlist_modified();
528 }
529
530 bool
531 AudioDiskstream::realtime_set_speed (double sp, bool global)
532 {
533         bool changed = false;
534         double new_speed = sp * _session.transport_speed();
535         
536         if (_visible_speed != sp) {
537                 _visible_speed = sp;
538                 changed = true;
539         }
540         
541         if (new_speed != _actual_speed) {
542                 
543                 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() * 
544                                                                             fabs (new_speed)) + 1;
545                 
546                 if (required_wrap_size > wrap_buffer_size) {
547                         _buffer_reallocation_required = true;
548                 }
549                 
550                 _actual_speed = new_speed;
551                 phi = (uint64_t) (0x1000000 * fabs(_actual_speed));
552         }
553
554         if (changed) {
555                 if (!global) {
556                         _seek_required = true;
557                 }
558                  speed_changed (); /* EMIT SIGNAL */
559         }
560
561         return _buffer_reallocation_required || _seek_required;
562 }
563
564 void
565 AudioDiskstream::non_realtime_set_speed ()
566 {
567         if (_buffer_reallocation_required)
568         {
569                 Glib::Mutex::Lock lm (state_lock);
570                 allocate_temporary_buffers ();
571
572                 _buffer_reallocation_required = false;
573         }
574
575         if (_seek_required) {
576                 if (speed() != 1.0f || speed() != -1.0f) {
577                         seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()), true);
578                 }
579                 else {
580                         seek (_session.transport_frame(), true);
581                 }
582
583                 _seek_required = false;
584         }
585 }
586
587 void
588 AudioDiskstream::prepare ()
589 {
590         _processed = false;
591         playback_distance = 0;
592 }
593
594 void
595 AudioDiskstream::check_record_status (jack_nframes_t transport_frame, jack_nframes_t nframes, bool can_record)
596 {
597         int possibly_recording;
598         int rolling;
599         int change;
600         const int transport_rolling = 0x4;
601         const int track_rec_enabled = 0x2;
602         const int global_rec_enabled = 0x1;
603
604         /* merge together the 3 factors that affect record status, and compute
605            what has changed.
606         */
607
608         rolling = _session.transport_speed() != 0.0f;
609         possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
610         change = possibly_recording ^ last_possibly_recording;
611
612         if (possibly_recording == last_possibly_recording) {
613                 return;
614         }
615
616         /* change state */
617
618         /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
619
620         if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) || 
621             ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
622                 
623                 /* starting to record: compute first+last frames */
624
625                 first_recordable_frame = transport_frame + _capture_offset;
626                 last_recordable_frame = max_frames;
627                 capture_start_frame = transport_frame;
628
629                 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
630
631                         /* was stopped, now rolling (and recording) */
632
633                         if (_alignment_style == ExistingMaterial) {
634                                 first_recordable_frame += _session.worst_output_latency();
635                         } else {
636                                 first_recordable_frame += _roll_delay;
637                         }
638
639                 } else {
640
641                         /* was rolling, but record state changed */
642
643                         if (_alignment_style == ExistingMaterial) {
644
645
646                                 if (!_session.get_punch_in()) {
647
648                                         /* manual punch in happens at the correct transport frame
649                                            because the user hit a button. but to get alignment correct 
650                                            we have to back up the position of the new region to the 
651                                            appropriate spot given the roll delay.
652                                         */
653
654                                         capture_start_frame -= _roll_delay;
655
656                                         /* XXX paul notes (august 2005): i don't know why
657                                            this is needed.
658                                         */
659
660                                         first_recordable_frame += _capture_offset;
661
662                                 } else {
663
664                                         /* autopunch toggles recording at the precise
665                                            transport frame, and then the DS waits
666                                            to start recording for a time that depends
667                                            on the output latency.
668                                         */
669
670                                         first_recordable_frame += _session.worst_output_latency();
671                                 }
672
673                         } else {
674
675                                 if (_session.get_punch_in()) {
676                                         first_recordable_frame += _roll_delay;
677                                 } else {
678                                         capture_start_frame -= _roll_delay;
679                                 }
680                         }
681                         
682                 }
683
684                 if (_flags & Recordable) {
685                         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
686                                 
687                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
688                                 (*chan).capture_transition_buf->get_write_vector(&transvec);
689                                 
690                                 if (transvec.len[0] > 0) {
691                                         transvec.buf[0]->type = CaptureStart;
692                                         transvec.buf[0]->capture_val = capture_start_frame;
693                                         (*chan).capture_transition_buf->increment_write_ptr(1);
694                                 }
695                                 else {
696                                         // bad!
697                                         fatal << X_("programming error: capture_transition_buf is full on rec start!  inconceivable!") 
698                                               << endmsg;
699                                 }
700                         }
701                 }
702
703         } else if (!record_enabled() || !can_record) {
704                 
705                 /* stop recording */
706
707                 last_recordable_frame = transport_frame + _capture_offset;
708                 
709                 if (_alignment_style == ExistingMaterial) {
710                         last_recordable_frame += _session.worst_output_latency();
711                 } else {
712                         last_recordable_frame += _roll_delay;
713                 }
714         }
715
716         last_possibly_recording = possibly_recording;
717 }
718
719 int
720 AudioDiskstream::process (jack_nframes_t transport_frame, jack_nframes_t nframes, jack_nframes_t offset, bool can_record, bool rec_monitors_input)
721 {
722         uint32_t n;
723         ChannelList::iterator c;
724         int ret = -1;
725         jack_nframes_t rec_offset = 0;
726         jack_nframes_t rec_nframes = 0;
727         bool nominally_recording;
728         bool re = record_enabled ();
729         bool collect_playback = false;
730
731         /* if we've already processed the frames corresponding to this call,
732            just return. this allows multiple routes that are taking input
733            from this diskstream to call our ::process() method, but have
734            this stuff only happen once. more commonly, it allows both
735            the AudioTrack that is using this AudioDiskstream *and* the Session
736            to call process() without problems.
737         */
738
739         if (_processed) {
740                 return 0;
741         }
742
743         check_record_status (transport_frame, nframes, can_record);
744
745         nominally_recording = (can_record && re);
746
747         if (nframes == 0) {
748                 _processed = true;
749                 return 0;
750         }
751
752         /* This lock is held until the end of AudioDiskstream::commit, so these two functions
753            must always be called as a pair. The only exception is if this function
754            returns a non-zero value, in which case, ::commit should not be called.
755         */
756
757         // If we can't take the state lock return.
758         if (!state_lock.trylock()) {
759                 return 1;
760         }
761
762         adjust_capture_position = 0;
763
764         for (c = channels.begin(); c != channels.end(); ++c) {
765                 (*c).current_capture_buffer = 0;
766                 (*c).current_playback_buffer  = 0;
767         }
768
769         if (nominally_recording || (_session.get_record_enabled() && _session.get_punch_in())) {
770                 OverlapType ot;
771                 
772                 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
773
774                 switch (ot) {
775                 case OverlapNone:
776                         rec_nframes = 0;
777                         break;
778                         
779                 case OverlapInternal:
780                 /*     ----------    recrange
781                          |---|       transrange
782                 */
783                         rec_nframes = nframes;
784                         rec_offset = 0;
785                         break;
786                         
787                 case OverlapStart:
788                         /*    |--------|    recrange
789                             -----|          transrange
790                         */
791                         rec_nframes = transport_frame + nframes - first_recordable_frame;
792                         if (rec_nframes) {
793                                 rec_offset = first_recordable_frame - transport_frame;
794                         }
795                         break;
796                         
797                 case OverlapEnd:
798                         /*    |--------|    recrange
799                                  |--------  transrange
800                         */
801                         rec_nframes = last_recordable_frame - transport_frame;
802                         rec_offset = 0;
803                         break;
804                         
805                 case OverlapExternal:
806                         /*    |--------|    recrange
807                             --------------  transrange
808                         */
809                         rec_nframes = last_recordable_frame - last_recordable_frame;
810                         rec_offset = first_recordable_frame - transport_frame;
811                         break;
812                 }
813
814                 if (rec_nframes && !was_recording) {
815                         capture_captured = 0;
816                         was_recording = true;
817                 }
818         }
819
820
821         if (can_record && !_last_capture_regions.empty()) {
822                 _last_capture_regions.clear ();
823         }
824
825         if (nominally_recording || rec_nframes) {
826
827                 for (n = 0, c = channels.begin(); c != channels.end(); ++c, ++n) {
828                         
829                         ChannelInfo& chan (*c);
830                 
831                         chan.capture_buf->get_write_vector (&chan.capture_vector);
832
833                         if (rec_nframes <= chan.capture_vector.len[0]) {
834                                 
835                                 chan.current_capture_buffer = chan.capture_vector.buf[0];
836
837                                 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
838                                    rec_offset
839                                 */
840
841                                 memcpy (chan.current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
842
843                         } else {
844
845                                 jack_nframes_t total = chan.capture_vector.len[0] + chan.capture_vector.len[1];
846
847                                 if (rec_nframes > total) {
848                                         DiskOverrun ();
849                                         goto out;
850                                 }
851
852                                 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
853                                 jack_nframes_t first = chan.capture_vector.len[0];
854
855                                 memcpy (chan.capture_wrap_buffer, buf, sizeof (Sample) * first);
856                                 memcpy (chan.capture_vector.buf[0], buf, sizeof (Sample) * first);
857                                 memcpy (chan.capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
858                                 memcpy (chan.capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
859                                 
860                                 chan.current_capture_buffer = chan.capture_wrap_buffer;
861                         }
862                 }
863
864         } else {
865
866                 if (was_recording) {
867                         finish_capture (rec_monitors_input);
868                 }
869
870         }
871         
872         if (rec_nframes) {
873                 
874                 /* data will be written to disk */
875
876                 if (rec_nframes == nframes && rec_offset == 0) {
877
878                         for (c = channels.begin(); c != channels.end(); ++c) {
879                                 (*c).current_playback_buffer = (*c).current_capture_buffer;
880                         }
881
882                         playback_distance = nframes;
883
884                 } else {
885
886
887                         /* we can't use the capture buffer as the playback buffer, because
888                            we recorded only a part of the current process' cycle data
889                            for capture.
890                         */
891
892                         collect_playback = true;
893                 }
894
895                 adjust_capture_position = rec_nframes;
896
897         } else if (nominally_recording) {
898
899                 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
900
901                 for (c = channels.begin(); c != channels.end(); ++c) {
902                         (*c).current_playback_buffer = (*c).current_capture_buffer;
903                 }
904
905                 playback_distance = nframes;
906
907         } else {
908
909                 collect_playback = true;
910         }
911
912         if (collect_playback) {
913
914                 /* we're doing playback */
915
916                 jack_nframes_t necessary_samples;
917
918                 /* no varispeed playback if we're recording, because the output .... TBD */
919
920                 if (rec_nframes == 0 && _actual_speed != 1.0f) {
921                         necessary_samples = (jack_nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
922                 } else {
923                         necessary_samples = nframes;
924                 }
925                 
926                 for (c = channels.begin(); c != channels.end(); ++c) {
927                         (*c).playback_buf->get_read_vector (&(*c).playback_vector);
928                 }
929
930                 n = 0;                  
931
932                 for (c = channels.begin(); c != channels.end(); ++c, ++n) {
933                 
934                         ChannelInfo& chan (*c);
935
936                         if (necessary_samples <= chan.playback_vector.len[0]) {
937
938                                 chan.current_playback_buffer = chan.playback_vector.buf[0];
939
940                         } else {
941                                 jack_nframes_t total = chan.playback_vector.len[0] + chan.playback_vector.len[1];
942                                 
943                                 if (necessary_samples > total) {
944                                         DiskUnderrun ();
945                                         goto out;
946                                         
947                                 } else {
948                                         
949                                         memcpy ((char *) chan.playback_wrap_buffer, chan.playback_vector.buf[0],
950                                                 chan.playback_vector.len[0] * sizeof (Sample));
951                                         memcpy (chan.playback_wrap_buffer + chan.playback_vector.len[0], chan.playback_vector.buf[1], 
952                                                 (necessary_samples - chan.playback_vector.len[0]) * sizeof (Sample));
953                                         
954                                         chan.current_playback_buffer = chan.playback_wrap_buffer;
955                                 }
956                         }
957                 } 
958
959                 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
960                         
961                         uint64_t phase = last_phase;
962                         jack_nframes_t i = 0;
963
964                         // Linearly interpolate into the alt buffer
965                         // using 40.24 fixp maths (swh)
966
967                         for (c = channels.begin(); c != channels.end(); ++c) {
968
969                                 float fr;
970                                 ChannelInfo& chan (*c);
971
972                                 i = 0;
973                                 phase = last_phase;
974
975                                 for (jack_nframes_t outsample = 0; outsample < nframes; ++outsample) {
976                                         i = phase >> 24;
977                                         fr = (phase & 0xFFFFFF) / 16777216.0f;
978                                         chan.speed_buffer[outsample] = 
979                                                 chan.current_playback_buffer[i] * (1.0f - fr) +
980                                                 chan.current_playback_buffer[i+1] * fr;
981                                         phase += phi;
982                                 }
983                                 
984                                 chan.current_playback_buffer = chan.speed_buffer;
985                         }
986
987                         playback_distance = i + 1;
988                         last_phase = (phase & 0xFFFFFF);
989
990                 } else {
991                         playback_distance = nframes;
992                 }
993
994         }
995
996         ret = 0;
997
998   out:
999         _processed = true;
1000
1001         if (ret) {
1002
1003                 /* we're exiting with failure, so ::commit will not
1004                    be called. unlock the state lock.
1005                 */
1006                 
1007                 state_lock.unlock();
1008         } 
1009
1010         return ret;
1011 }
1012
1013 void
1014 AudioDiskstream::recover ()
1015 {
1016         state_lock.unlock();
1017         _processed = false;
1018 }
1019
1020 bool
1021 AudioDiskstream::commit (jack_nframes_t nframes)
1022 {
1023         bool need_butler = false;
1024
1025         if (_actual_speed < 0.0) {
1026                 playback_sample -= playback_distance;
1027         } else {
1028                 playback_sample += playback_distance;
1029         }
1030
1031         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1032
1033                 (*chan).playback_buf->increment_read_ptr (playback_distance);
1034                 
1035                 if (adjust_capture_position) {
1036                         (*chan).capture_buf->increment_write_ptr (adjust_capture_position);
1037                 }
1038         }
1039         
1040         if (adjust_capture_position != 0) {
1041                 capture_captured += adjust_capture_position;
1042                 adjust_capture_position = 0;
1043         }
1044         
1045         if (_slaved) {
1046                 need_butler = channels[0].playback_buf->write_space() >= channels[0].playback_buf->bufsize() / 2;
1047         } else {
1048                 need_butler = channels[0].playback_buf->write_space() >= disk_io_chunk_frames
1049                         || channels[0].capture_buf->read_space() >= disk_io_chunk_frames;
1050         }
1051
1052         state_lock.unlock();
1053
1054         _processed = false;
1055
1056         return need_butler;
1057 }
1058
1059 void
1060 AudioDiskstream::set_pending_overwrite (bool yn)
1061 {
1062         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
1063         
1064         pending_overwrite = yn;
1065
1066         overwrite_frame = playback_sample;
1067         overwrite_offset = channels.front().playback_buf->get_read_ptr();
1068 }
1069
1070 int
1071 AudioDiskstream::overwrite_existing_buffers ()
1072 {
1073         Sample* mixdown_buffer;
1074         float* gain_buffer;
1075         char * workbuf;
1076         int ret = -1;
1077         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1078
1079         overwrite_queued = false;
1080
1081         /* assume all are the same size */
1082         jack_nframes_t size = channels[0].playback_buf->bufsize();
1083         
1084         mixdown_buffer = new Sample[size];
1085         gain_buffer = new float[size];
1086         workbuf = new char[size*4];
1087         
1088         /* reduce size so that we can fill the buffer correctly. */
1089         size--;
1090         
1091         uint32_t n=0;
1092         jack_nframes_t start;
1093
1094         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1095
1096                 start = overwrite_frame;
1097                 jack_nframes_t cnt = size;
1098                 
1099                 /* to fill the buffer without resetting the playback sample, we need to
1100                    do it one or two chunks (normally two).
1101
1102                    |----------------------------------------------------------------------|
1103
1104                                        ^
1105                                        overwrite_offset
1106                     |<- second chunk->||<----------------- first chunk ------------------>|
1107                    
1108                 */
1109                 
1110                 jack_nframes_t to_read = size - overwrite_offset;
1111
1112                 if (read ((*chan).playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, workbuf,
1113                           start, to_read, *chan, n, reversed)) {
1114                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
1115                                          _id, size, playback_sample) << endmsg;
1116                         goto out;
1117                 }
1118                         
1119                 if (cnt > to_read) {
1120
1121                         cnt -= to_read;
1122                 
1123                         if (read ((*chan).playback_buf->buffer(), mixdown_buffer, gain_buffer, workbuf,
1124                                   start, cnt, *chan, n, reversed)) {
1125                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
1126                                                  _id, size, playback_sample) << endmsg;
1127                                 goto out;
1128                         }
1129                 }
1130         }
1131
1132         ret = 0;
1133  
1134   out:
1135         pending_overwrite = false;
1136         delete [] gain_buffer;
1137         delete [] mixdown_buffer;
1138         delete [] workbuf;
1139         return ret;
1140 }
1141
1142 int
1143 AudioDiskstream::seek (jack_nframes_t frame, bool complete_refill)
1144 {
1145         Glib::Mutex::Lock lm (state_lock);
1146         uint32_t n;
1147         int ret;
1148         ChannelList::iterator chan;
1149
1150         for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1151                 (*chan).playback_buf->reset ();
1152                 (*chan).capture_buf->reset ();
1153         }
1154         
1155         playback_sample = frame;
1156         file_frame = frame;
1157
1158         if (complete_refill) {
1159                 while ((ret = do_refill (0, 0, 0)) > 0);
1160         } else {
1161                 ret = do_refill (0, 0, 0);
1162         }
1163
1164         return ret;
1165 }
1166
1167 int
1168 AudioDiskstream::can_internal_playback_seek (jack_nframes_t distance)
1169 {
1170         ChannelList::iterator chan;
1171
1172         for (chan = channels.begin(); chan != channels.end(); ++chan) {
1173                 if ((*chan).playback_buf->read_space() < distance) {
1174                         return false;
1175                 } 
1176         }
1177         return true;
1178 }
1179
1180 int
1181 AudioDiskstream::internal_playback_seek (jack_nframes_t distance)
1182 {
1183         ChannelList::iterator chan;
1184
1185         for (chan = channels.begin(); chan != channels.end(); ++chan) {
1186                 (*chan).playback_buf->increment_read_ptr (distance);
1187         }
1188
1189         first_recordable_frame += distance;
1190         playback_sample += distance;
1191         
1192         return 0;
1193 }
1194
1195 int
1196 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, char * workbuf, jack_nframes_t& start, jack_nframes_t cnt, 
1197                   ChannelInfo& channel_info, int channel, bool reversed)
1198 {
1199         jack_nframes_t this_read = 0;
1200         bool reloop = false;
1201         jack_nframes_t loop_end = 0;
1202         jack_nframes_t loop_start = 0;
1203         jack_nframes_t loop_length = 0;
1204         jack_nframes_t offset = 0;
1205         Location *loc = 0;
1206
1207         if (!reversed) {
1208                 /* Make the use of a Location atomic for this read operation.
1209                    
1210                    Note: Locations don't get deleted, so all we care about
1211                    when I say "atomic" is that we are always pointing to
1212                    the same one and using a start/length values obtained
1213                    just once.
1214                 */
1215                 
1216                 if ((loc = loop_location) != 0) {
1217                         loop_start = loc->start();
1218                         loop_end = loc->end();
1219                         loop_length = loop_end - loop_start;
1220                 }
1221                 
1222                 /* if we are looping, ensure that the first frame we read is at the correct
1223                    position within the loop.
1224                 */
1225                 
1226                 if (loc && start >= loop_end) {
1227                         //cerr << "start adjusted from " << start;
1228                         start = loop_start + ((start - loop_start) % loop_length);
1229                         //cerr << "to " << start << endl;
1230                 }
1231                 //cerr << "start is " << start << "  loopstart: " << loop_start << "  loopend: " << loop_end << endl;
1232         }
1233
1234         while (cnt) {
1235
1236                 /* take any loop into account. we can't read past the end of the loop. */
1237
1238                 if (loc && (loop_end - start < cnt)) {
1239                         this_read = loop_end - start;
1240                         //cerr << "reloop true: thisread: " << this_read << "  cnt: " << cnt << endl;
1241                         reloop = true;
1242                 } else {
1243                         reloop = false;
1244                         this_read = cnt;
1245                 }
1246
1247                 if (this_read == 0) {
1248                         break;
1249                 }
1250
1251                 this_read = min(cnt,this_read);
1252
1253                 if (_playlist->read (buf+offset, mixdown_buffer, gain_buffer, workbuf, start, this_read, channel) != this_read) {
1254                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read, 
1255                                          start) << endmsg;
1256                         return -1;
1257                 }
1258
1259                 _read_data_count = _playlist->read_data_count();
1260                 
1261                 if (reversed) {
1262
1263                         /* don't adjust start, since caller has already done that
1264                          */
1265
1266                         swap_by_ptr (buf, buf + this_read - 1);
1267                         
1268                 } else {
1269                         
1270                         /* if we read to the end of the loop, go back to the beginning */
1271                         
1272                         if (reloop) {
1273                                 start = loop_start;
1274                         } else {
1275                                 start += this_read;
1276                         }
1277                 } 
1278
1279                 cnt -= this_read;
1280                 offset += this_read;
1281         }
1282
1283         return 0;
1284 }
1285
1286 int
1287 AudioDiskstream::do_refill (Sample* mixdown_buffer, float* gain_buffer, char * workbuf)
1288 {
1289         int32_t ret = 0;
1290         jack_nframes_t to_read;
1291         RingBufferNPT<Sample>::rw_vector vector;
1292         bool free_mixdown;
1293         bool free_gain;
1294         bool free_workbuf;
1295         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1296         jack_nframes_t total_space;
1297         jack_nframes_t zero_fill;
1298         uint32_t chan_n;
1299         ChannelList::iterator i;
1300         jack_nframes_t ts;
1301
1302         channels.front().playback_buf->get_write_vector (&vector);
1303         
1304         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1305                 return 0;
1306         }
1307         
1308         /* if there are 2+ chunks of disk i/o possible for
1309            this track, let the caller know so that it can arrange
1310            for us to be called again, ASAP.
1311         */
1312         
1313         if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1314                 ret = 1;
1315         }
1316         
1317         /* if we're running close to normal speed and there isn't enough 
1318            space to do disk_io_chunk_frames of I/O, then don't bother.  
1319            
1320            at higher speeds, just do it because the sync between butler
1321            and audio thread may not be good enough.
1322         */
1323         
1324         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1325                 return 0;
1326         }
1327         
1328         /* when slaved, don't try to get too close to the read pointer. this
1329            leaves space for the buffer reversal to have something useful to
1330            work with.
1331         */
1332         
1333         if (_slaved && total_space < (channels.front().playback_buf->bufsize() / 2)) {
1334                 return 0;
1335         }
1336
1337         total_space = min (disk_io_chunk_frames, total_space);
1338
1339         if (reversed) {
1340
1341                 if (file_frame == 0) {
1342
1343                         /* at start: nothing to do but fill with silence */
1344
1345                         for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1346                                         
1347                                 ChannelInfo& chan (*i);
1348                                 chan.playback_buf->get_write_vector (&vector);
1349                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1350                                 if (vector.len[1]) {
1351                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1352                                 }
1353                                 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1354                         }
1355                         return 0;
1356                 }
1357
1358                 if (file_frame < total_space) {
1359
1360                         /* too close to the start: read what we can, 
1361                            and then zero fill the rest 
1362                         */
1363
1364                         zero_fill = total_space - file_frame;
1365                         total_space = file_frame;
1366                         file_frame = 0;
1367
1368                 } else {
1369                         
1370                         /* move read position backwards because we are going
1371                            to reverse the data.
1372                         */
1373                         
1374                         file_frame -= total_space;
1375                         zero_fill = 0;
1376                 }
1377
1378         } else {
1379
1380                 if (file_frame == max_frames) {
1381
1382                         /* at end: nothing to do but fill with silence */
1383                         
1384                         for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1385                                         
1386                                 ChannelInfo& chan (*i);
1387                                 chan.playback_buf->get_write_vector (&vector);
1388                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1389                                 if (vector.len[1]) {
1390                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1391                                 }
1392                                 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1393                         }
1394                         return 0;
1395                 }
1396                 
1397                 if (file_frame > max_frames - total_space) {
1398
1399                         /* to close to the end: read what we can, and zero fill the rest */
1400
1401                         zero_fill = total_space - (max_frames - file_frame);
1402                         total_space = max_frames - file_frame;
1403
1404                 } else {
1405                         zero_fill = 0;
1406                 }
1407         }
1408
1409         /* Please note: the code to allocate buffers isn't run
1410            during normal butler thread operation. Its there
1411            for other times when we need to call do_refill()
1412            from somewhere other than the butler thread.
1413         */
1414
1415         if (mixdown_buffer == 0) {
1416                 mixdown_buffer = new Sample[disk_io_chunk_frames];
1417                 free_mixdown = true;
1418         } else {
1419                 free_mixdown = false;
1420         }
1421
1422         if (gain_buffer == 0) {
1423                 gain_buffer = new float[disk_io_chunk_frames];
1424                 free_gain = true;
1425         } else {
1426                 free_gain = false;
1427         }
1428
1429         if (workbuf == 0) {
1430                 workbuf = new char[disk_io_chunk_frames * 4];
1431                 free_workbuf = true;
1432         } else {
1433                 free_workbuf = false;
1434         }
1435         
1436         jack_nframes_t file_frame_tmp = 0;
1437
1438         for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1439
1440                 ChannelInfo& chan (*i);
1441                 Sample* buf1;
1442                 Sample* buf2;
1443                 jack_nframes_t len1, len2;
1444
1445                 chan.playback_buf->get_write_vector (&vector);
1446
1447                 ts = total_space;
1448                 file_frame_tmp = file_frame;
1449
1450                 if (reversed) {
1451                         buf1 = vector.buf[1];
1452                         len1 = vector.len[1];
1453                         buf2 = vector.buf[0];
1454                         len2 = vector.len[0];
1455                 } else {
1456                         buf1 = vector.buf[0];
1457                         len1 = vector.len[0];
1458                         buf2 = vector.buf[1];
1459                         len2 = vector.len[1];
1460                 }
1461
1462
1463                 to_read = min (ts, len1);
1464                 to_read = min (to_read, disk_io_chunk_frames);
1465
1466                 if (to_read) {
1467
1468                         if (read (buf1, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1469                                 ret = -1;
1470                                 goto out;
1471                         }
1472                         
1473                         chan.playback_buf->increment_write_ptr (to_read);
1474                         ts -= to_read;
1475                 }
1476
1477                 to_read = min (ts, len2);
1478
1479                 if (to_read) {
1480
1481                         
1482                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1483                            so read some or all of vector.len[1] as well.
1484                         */
1485
1486                         if (read (buf2, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1487                                 ret = -1;
1488                                 goto out;
1489                         }
1490                 
1491                         chan.playback_buf->increment_write_ptr (to_read);
1492                 }
1493
1494                 if (zero_fill) {
1495                         /* do something */
1496                 }
1497
1498         }
1499         
1500         file_frame = file_frame_tmp;
1501
1502   out:
1503         if (free_mixdown) {
1504                 delete [] mixdown_buffer;
1505         }
1506         if (free_gain) {
1507                 delete [] gain_buffer;
1508         }
1509         if (free_workbuf) {
1510                 delete [] workbuf;
1511         }
1512
1513         return ret;
1514 }       
1515
1516 int
1517 AudioDiskstream::do_flush (char * workbuf, bool force_flush)
1518 {
1519         uint32_t to_write;
1520         int32_t ret = 0;
1521         RingBufferNPT<Sample>::rw_vector vector;
1522         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1523         jack_nframes_t total;
1524         
1525         /* important note: this function will write *AT MOST* 
1526            disk_io_chunk_frames of data to disk. it will never 
1527            write more than that. if its writes that much and there 
1528            is more than that waiting to be written, it will return 1,
1529            otherwise 0 on success or -1 on failure.
1530
1531            if there is less than disk_io_chunk_frames to be written, 
1532            no data will be written at all unless `force_flush' is true.  
1533         */
1534
1535         _write_data_count = 0;
1536
1537         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1538         
1539                 (*chan).capture_buf->get_read_vector (&vector);
1540
1541                 total = vector.len[0] + vector.len[1];
1542
1543                 
1544                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1545                         goto out;
1546                 }
1547
1548                 
1549                 /* if there are 2+ chunks of disk i/o possible for
1550                    this track, let the caller know so that it can arrange
1551                    for us to be called again, ASAP.
1552                    
1553                    if we are forcing a flush, then if there is* any* extra
1554                    work, let the caller know.
1555
1556                    if we are no longer recording and there is any extra work,
1557                    let the caller know too.
1558                 */
1559
1560                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1561                         ret = 1;
1562                 } 
1563
1564                 to_write = min (disk_io_chunk_frames, (jack_nframes_t) vector.len[0]);
1565                 
1566                 
1567                 // check the transition buffer when recording destructive
1568                 // important that we get this after the capture buf
1569
1570                 if (destructive()) {
1571                         (*chan).capture_transition_buf->get_read_vector(&transvec);
1572                         size_t transcount = transvec.len[0] + transvec.len[1];
1573                         bool have_start = false;
1574                         size_t ti;
1575
1576                         for (ti=0; ti < transcount; ++ti) {
1577                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1578                                 
1579                                 if (captrans.type == CaptureStart) {
1580                                         // by definition, the first data we got above represents the given capture pos
1581
1582                                         (*chan).write_source->mark_capture_start (captrans.capture_val);
1583                                         (*chan).curr_capture_cnt = 0;
1584
1585                                         have_start = true;
1586                                 }
1587                                 else if (captrans.type == CaptureEnd) {
1588
1589                                         // capture end, the capture_val represents total frames in capture
1590
1591                                         if (captrans.capture_val <= (*chan).curr_capture_cnt + to_write) {
1592
1593                                                 // shorten to make the write a perfect fit
1594                                                 uint32_t nto_write = (captrans.capture_val - (*chan).curr_capture_cnt); 
1595
1596                                                 if (nto_write < to_write) {
1597                                                         ret = 1; // should we?
1598                                                 }
1599                                                 to_write = nto_write;
1600
1601                                                 (*chan).write_source->mark_capture_end ();
1602                                                 
1603                                                 // increment past this transition, but go no further
1604                                                 ++ti;
1605                                                 break;
1606                                         }
1607                                         else {
1608                                                 // actually ends just beyond this chunk, so force more work
1609                                                 ret = 1;
1610                                                 break;
1611                                         }
1612                                 }
1613                         }
1614
1615                         if (ti > 0) {
1616                                 (*chan).capture_transition_buf->increment_read_ptr(ti);
1617                         }
1618                 }
1619
1620                 if ((!(*chan).write_source) || (*chan).write_source->write (vector.buf[0], to_write, workbuf) != to_write) {
1621                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1622                         return -1;
1623                 }
1624
1625                 (*chan).capture_buf->increment_read_ptr (to_write);
1626                 (*chan).curr_capture_cnt += to_write;
1627                 
1628                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1629                 
1630                         /* we wrote all of vector.len[0] but it wasn't an entire
1631                            disk_io_chunk_frames of data, so arrange for some part 
1632                            of vector.len[1] to be flushed to disk as well.
1633                         */
1634                 
1635                         to_write = min ((jack_nframes_t)(disk_io_chunk_frames - to_write), (jack_nframes_t) vector.len[1]);
1636                 
1637                         if ((*chan).write_source->write (vector.buf[1], to_write, workbuf) != to_write) {
1638                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1639                                 return -1;
1640                         }
1641
1642                         _write_data_count += (*chan).write_source->write_data_count();
1643         
1644                         (*chan).capture_buf->increment_read_ptr (to_write);
1645                         (*chan).curr_capture_cnt += to_write;
1646                 }
1647         }
1648
1649   out:
1650         return ret;
1651 }
1652
1653 void
1654 AudioDiskstream::playlist_changed (Change ignored)
1655 {
1656         playlist_modified ();
1657 }
1658
1659 void
1660 AudioDiskstream::playlist_modified ()
1661 {
1662         if (!i_am_the_modifier && !overwrite_queued) {
1663                 _session.request_overwrite_buffer (this);
1664                 overwrite_queued = true;
1665         } 
1666 }
1667
1668 void
1669 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1670 {
1671         uint32_t buffer_position;
1672         bool more_work = true;
1673         int err = 0;
1674         AudioRegion* region = 0;
1675         jack_nframes_t total_capture;
1676         AudioRegion::SourceList srcs;
1677         AudioRegion::SourceList::iterator src;
1678         ChannelList::iterator chan;
1679         vector<CaptureInfo*>::iterator ci;
1680         uint32_t n = 0; 
1681         list<AudioFileSource*>* deletion_list;
1682         bool mark_write_completed = false;
1683
1684         finish_capture (true);
1685
1686         /* butler is already stopped, but there may be work to do 
1687            to flush remaining data to disk.
1688         */
1689
1690         while (more_work && !err) {
1691                 switch (do_flush ( _session.conversion_buffer(Session::TransportContext), true)) {
1692                 case 0:
1693                         more_work = false;
1694                         break;
1695                 case 1:
1696                         break;
1697                 case -1:
1698                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1699                         err++;
1700                 }
1701         }
1702
1703         /* XXX is there anything we can do if err != 0 ? */
1704         Glib::Mutex::Lock lm (capture_info_lock);
1705         
1706         if (capture_info.empty()) {
1707                 return;
1708         }
1709
1710         if (abort_capture) {
1711                 
1712                 ChannelList::iterator chan;
1713                 
1714                 deletion_list = new list<AudioFileSource*>;
1715
1716                 for ( chan = channels.begin(); chan != channels.end(); ++chan) {
1717
1718                         if ((*chan).write_source) {
1719                                 
1720                                 (*chan).write_source->mark_for_remove ();
1721                                 (*chan).write_source->release ();
1722                                 
1723                                 deletion_list->push_back ((*chan).write_source);
1724
1725                                 (*chan).write_source = 0;
1726                         }
1727                         
1728                         /* new source set up in "out" below */
1729                 }
1730                 
1731                 if (!deletion_list->empty()) {
1732                         DeleteSources (deletion_list);
1733                 } else {
1734                         delete deletion_list;
1735                 }
1736
1737                 goto out;
1738         } 
1739
1740         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1741                 total_capture += (*ci)->frames;
1742         }
1743
1744         /* figure out the name for this take */
1745
1746         for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1747
1748                 AudioFileSource* s = (*chan).write_source;
1749                 
1750                 if (s) {
1751
1752                         AudioFileSource* fsrc;
1753
1754                         srcs.push_back (s);
1755
1756                         if ((fsrc = dynamic_cast<AudioFileSource *>(s)) != 0) {
1757                                 fsrc->update_header (capture_info.front()->start, when, twhen);
1758                         }
1759
1760                         s->set_captured_for (_name);
1761                         
1762                 }
1763         }
1764
1765         /* destructive tracks have a single, never changing region */
1766
1767         if (destructive()) {
1768
1769                 /* send a signal that any UI can pick up to do the right thing. there is 
1770                    a small problem here in that a UI may need the peak data to be ready
1771                    for the data that was recorded and this isn't interlocked with that
1772                    process. this problem is deferred to the UI.
1773                  */
1774                 
1775                 _playlist->Modified();
1776
1777         } else {
1778
1779                 /* Register a new region with the Session that
1780                    describes the entire source. Do this first
1781                    so that any sub-regions will obviously be
1782                    children of this one (later!)
1783                 */
1784                 
1785                 try {
1786                         region = new AudioRegion (srcs, channels[0].write_source->last_capture_start_frame(), total_capture, 
1787                                                   region_name_from_path (channels[0].write_source->name()), 
1788                                                   0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
1789                         
1790                         region->special_set_position (capture_info.front()->start);
1791                 }
1792                 
1793                 
1794                 catch (failed_constructor& err) {
1795                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1796                         /* XXX what now? */
1797                 }
1798                 
1799                 _last_capture_regions.push_back (region);
1800
1801                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1802                 
1803                 _session.add_undo (_playlist->get_memento());
1804                 _playlist->freeze ();
1805                 
1806                 for (buffer_position = channels[0].write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1807                         
1808                         string region_name;
1809                         _session.region_name (region_name, channels[0].write_source->name(), false);
1810                         
1811                         // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1812                         
1813                         try {
1814                                 region = new AudioRegion (srcs, buffer_position, (*ci)->frames, region_name);
1815                         }
1816                         
1817                         catch (failed_constructor& err) {
1818                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1819                                 continue; /* XXX is this OK? */
1820                         }
1821                         
1822                         _last_capture_regions.push_back (region);
1823                         
1824                         // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1825                         
1826                         i_am_the_modifier++;
1827                         _playlist->add_region (*region, (*ci)->start);
1828                         i_am_the_modifier--;
1829                         
1830                         buffer_position += (*ci)->frames;
1831                 }
1832
1833                 _playlist->thaw ();
1834                 _session.add_redo_no_execute (_playlist->get_memento());
1835         }
1836
1837         mark_write_completed = true;
1838
1839         reset_write_sources (mark_write_completed);
1840
1841   out:
1842         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1843                 delete *ci;
1844         }
1845
1846         capture_info.clear ();
1847         capture_start_frame = 0;
1848 }
1849
1850 void
1851 AudioDiskstream::finish_capture (bool rec_monitors_input)
1852 {
1853         was_recording = false;
1854         
1855         if (capture_captured == 0) {
1856                 return;
1857         }
1858
1859         if (recordable() && destructive()) {
1860                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1861                         
1862                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1863                         (*chan).capture_transition_buf->get_write_vector(&transvec);
1864                         
1865                         
1866                         if (transvec.len[0] > 0) {
1867                                 transvec.buf[0]->type = CaptureEnd;
1868                                 transvec.buf[0]->capture_val = capture_captured;
1869                                 (*chan).capture_transition_buf->increment_write_ptr(1);
1870                         }
1871                         else {
1872                                 // bad!
1873                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1874                         }
1875                 }
1876         }
1877         
1878         
1879         CaptureInfo* ci = new CaptureInfo;
1880         
1881         ci->start =  capture_start_frame;
1882         ci->frames = capture_captured;
1883         
1884         /* XXX theoretical race condition here. Need atomic exchange ? 
1885            However, the circumstances when this is called right 
1886            now (either on record-disable or transport_stopped)
1887            mean that no actual race exists. I think ...
1888            We now have a capture_info_lock, but it is only to be used
1889            to synchronize in the transport_stop and the capture info
1890            accessors, so that invalidation will not occur (both non-realtime).
1891         */
1892
1893         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1894
1895         capture_info.push_back (ci);
1896         capture_captured = 0;
1897 }
1898
1899 void
1900 AudioDiskstream::set_record_enabled (bool yn, void* src)
1901 {
1902         bool rolling = _session.transport_speed() != 0.0f;
1903
1904         if (!recordable() || !_session.record_enabling_legal()) {
1905                 return;
1906         }
1907         
1908         /* if we're turning on rec-enable, there needs to be an
1909            input connection.
1910          */
1911
1912         if (yn && channels[0].source == 0) {
1913
1914                 /* pick up connections not initiated *from* the IO object
1915                    we're associated with.
1916                 */
1917
1918                 get_input_sources ();
1919         }
1920
1921         /* yes, i know that this not proof against race conditions, but its
1922            good enough. i think.
1923         */
1924
1925         if (record_enabled() != yn) {
1926                 if (yn) {
1927                         g_atomic_int_set (&_record_enabled, 1);
1928                         capturing_sources.clear ();
1929                         if (Config->get_use_hardware_monitoring())  {
1930                                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1931                                         if ((*chan).source) {
1932                                                 (*chan).source->request_monitor_input (!(_session.get_auto_input() && rolling));
1933                                         }
1934                                         capturing_sources.push_back ((*chan).write_source);
1935                                 }
1936                         } else {
1937                                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1938                                         capturing_sources.push_back ((*chan).write_source);
1939                                 }
1940                         }
1941
1942                 } else {
1943                         g_atomic_int_set (&_record_enabled, 0);
1944                         if (Config->get_use_hardware_monitoring()) {
1945                                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1946                                         if ((*chan).source) {
1947                                                 (*chan).source->request_monitor_input (false);
1948                                         }
1949                                 }
1950                         }
1951                         capturing_sources.clear ();
1952                 }
1953
1954                 record_enable_changed (src); /* EMIT SIGNAL */
1955         }
1956 }
1957
1958 XMLNode&
1959 AudioDiskstream::get_state ()
1960 {
1961         XMLNode* node = new XMLNode ("AudioDiskstream");
1962         char buf[64];
1963         LocaleGuard lg (X_("POSIX"));
1964
1965         snprintf (buf, sizeof(buf), "0x%x", _flags);
1966         node->add_property ("flags", buf);
1967
1968         snprintf (buf, sizeof(buf), "%zd", channels.size());
1969         node->add_property ("channels", buf);
1970
1971         node->add_property ("playlist", _playlist->name());
1972         
1973         snprintf (buf, sizeof(buf), "%f", _visible_speed);
1974         node->add_property ("speed", buf);
1975
1976         node->add_property("name", _name);
1977         snprintf (buf, sizeof(buf), "%" PRIu64, id());
1978         node->add_property("id", buf);
1979
1980         if (!capturing_sources.empty() && _session.get_record_enabled()) {
1981
1982                 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1983                 XMLNode* cs_grandchild;
1984
1985                 for (vector<AudioFileSource*>::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1986                         cs_grandchild = new XMLNode (X_("file"));
1987                         cs_grandchild->add_property (X_("path"), (*i)->path());
1988                         cs_child->add_child_nocopy (*cs_grandchild);
1989                 }
1990
1991                 /* store the location where capture will start */
1992
1993                 Location* pi;
1994
1995                 if (_session.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1996                         snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1997                 } else {
1998                         snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1999                 }
2000
2001                 cs_child->add_property (X_("at"), buf);
2002                 node->add_child_nocopy (*cs_child);
2003         }
2004
2005         if (_extra_xml) {
2006                 node->add_child_copy (*_extra_xml);
2007         }
2008
2009         return* node;
2010 }
2011
2012 int
2013 AudioDiskstream::set_state (const XMLNode& node)
2014 {
2015         const XMLProperty* prop;
2016         XMLNodeList nlist = node.children();
2017         XMLNodeIterator niter;
2018         uint32_t nchans = 1;
2019         XMLNode* capture_pending_node = 0;
2020         LocaleGuard lg (X_("POSIX"));
2021
2022         in_set_state = true;
2023
2024         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2025                 if ((*niter)->name() == IO::state_node_name) {
2026                         deprecated_io_node = new XMLNode (**niter);
2027                 }
2028
2029                 if ((*niter)->name() == X_("CapturingSources")) {
2030                         capture_pending_node = *niter;
2031                 }
2032         }
2033
2034         /* prevent write sources from being created */
2035         
2036         in_set_state = true;
2037         
2038         if ((prop = node.property ("name")) != 0) {
2039                 _name = prop->value();
2040         } 
2041
2042         if (deprecated_io_node) {
2043                 if ((prop = deprecated_io_node->property ("id")) != 0) {
2044                         sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2045                 }
2046         } else {
2047                 if ((prop = node.property ("id")) != 0) {
2048                         sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2049                 }
2050         }
2051
2052         if ((prop = node.property ("flags")) != 0) {
2053                 _flags = strtol (prop->value().c_str(), 0, 0);
2054         }
2055
2056         if ((prop = node.property ("channels")) != 0) {
2057                 nchans = atoi (prop->value().c_str());
2058         }
2059         
2060         // create necessary extra channels
2061         // we are always constructed with one
2062         // and we always need one
2063
2064         if (nchans > _n_channels) {
2065
2066                 // we need to add new channel infos
2067                 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2068
2069                 int diff = nchans - channels.size();
2070
2071                 for (int i=0; i < diff; ++i) {
2072                         add_channel ();
2073                 }
2074
2075         } else if (nchans < _n_channels) {
2076
2077                 // we need to get rid of channels
2078                 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2079
2080                 int diff = channels.size() - nchans;
2081                 
2082                 for (int i = 0; i < diff; ++i) {
2083                         remove_channel ();
2084                 }
2085         }
2086
2087         if ((prop = node.property ("playlist")) == 0) {
2088                 return -1;
2089         }
2090
2091         {
2092                 bool had_playlist = (_playlist != 0);
2093         
2094                 if (find_and_use_playlist (prop->value())) {
2095                         return -1;
2096                 }
2097
2098                 if (!had_playlist) {
2099                         _playlist->set_orig_diskstream_id (_id);
2100                 }
2101                 
2102                 if (!destructive() && capture_pending_node) {
2103                         /* destructive streams have one and only one source per channel,
2104                            and so they never end up in pending capture in any useful
2105                            sense.
2106                         */
2107                         use_pending_capture_data (*capture_pending_node);
2108                 }
2109
2110         }
2111
2112         if ((prop = node.property ("speed")) != 0) {
2113                 double sp = atof (prop->value().c_str());
2114
2115                 if (realtime_set_speed (sp, false)) {
2116                         non_realtime_set_speed ();
2117                 }
2118         }
2119
2120         _n_channels = channels.size();
2121
2122         in_set_state = false;
2123
2124         /* make sure this is clear before we do anything else */
2125
2126         capturing_sources.clear ();
2127
2128         /* write sources are handled when we handle the input set 
2129            up of the IO that owns this DS (::non_realtime_input_change())
2130         */
2131                 
2132         in_set_state = false;
2133
2134         return 0;
2135 }
2136
2137 int
2138 AudioDiskstream::use_new_write_source (uint32_t n)
2139 {
2140         if (!recordable()) {
2141                 return 1;
2142         }
2143
2144         if (n >= channels.size()) {
2145                 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2146                 return -1;
2147         }
2148
2149         ChannelInfo &chan = channels[n];
2150         
2151         if (chan.write_source) {
2152
2153                 if (AudioFileSource::is_empty (chan.write_source->path())) {
2154                         chan.write_source->mark_for_remove ();
2155                         chan.write_source->release();
2156                         delete chan.write_source;
2157                 } else {
2158                         chan.write_source->release();
2159                         chan.write_source = 0;
2160                 }
2161         }
2162
2163         try {
2164                 if ((chan.write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2165                         throw failed_constructor();
2166                 }
2167         } 
2168
2169         catch (failed_constructor &err) {
2170                 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2171                 chan.write_source = 0;
2172                 return -1;
2173         }
2174
2175         chan.write_source->use ();
2176
2177         /* do not remove destructive files even if they are empty */
2178
2179         chan.write_source->set_allow_remove_if_empty (!destructive());
2180
2181         return 0;
2182 }
2183
2184 void
2185 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2186 {
2187         ChannelList::iterator chan;
2188         uint32_t n;
2189
2190         if (!recordable()) {
2191                 return;
2192         }
2193         
2194         capturing_sources.clear ();
2195         
2196         for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2197                 if (!destructive()) {
2198
2199                         if ((*chan).write_source && mark_write_complete) {
2200                                 (*chan).write_source->mark_streaming_write_completed ();
2201                         }
2202                         use_new_write_source (n);
2203
2204                         if (record_enabled()) {
2205                                 capturing_sources.push_back ((*chan).write_source);
2206                         }
2207
2208                 } else {
2209                         if ((*chan).write_source == 0) {
2210                                 use_new_write_source (n);
2211                         }
2212                 }
2213         }
2214
2215         if (destructive()) {
2216
2217                 /* we now have all our write sources set up, so create the
2218                    playlist's single region.
2219                 */
2220
2221                 if (_playlist->empty()) {
2222                         setup_destructive_playlist ();
2223                 }
2224         }
2225 }
2226
2227 int
2228 AudioDiskstream::rename_write_sources ()
2229 {
2230         ChannelList::iterator chan;
2231         uint32_t n;
2232
2233         for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2234                 if ((*chan).write_source != 0) {
2235                         (*chan).write_source->set_name (_name, destructive());
2236                         /* XXX what to do if one of them fails ? */
2237                 }
2238         }
2239
2240         return 0;
2241 }
2242
2243 void
2244 AudioDiskstream::set_block_size (jack_nframes_t nframes)
2245 {
2246         if (_session.get_block_size() > speed_buffer_size) {
2247                 speed_buffer_size = _session.get_block_size();
2248
2249                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2250                         if ((*chan).speed_buffer) delete [] (*chan).speed_buffer;
2251                         (*chan).speed_buffer = new Sample[speed_buffer_size];
2252                 }
2253         }
2254         allocate_temporary_buffers ();
2255 }
2256
2257 void
2258 AudioDiskstream::allocate_temporary_buffers ()
2259 {
2260         /* make sure the wrap buffer is at least large enough to deal
2261            with the speeds up to 1.2, to allow for micro-variation
2262            when slaving to MTC, SMPTE etc.
2263         */
2264
2265         double sp = max (fabsf (_actual_speed), 1.2f);
2266         jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() * sp) + 1;
2267
2268         if (required_wrap_size > wrap_buffer_size) {
2269
2270                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2271                         if ((*chan).playback_wrap_buffer) delete [] (*chan).playback_wrap_buffer;
2272                         (*chan).playback_wrap_buffer = new Sample[required_wrap_size];  
2273                         if ((*chan).capture_wrap_buffer) delete [] (*chan).capture_wrap_buffer;
2274                         (*chan).capture_wrap_buffer = new Sample[required_wrap_size];   
2275                 }
2276
2277                 wrap_buffer_size = required_wrap_size;
2278         }
2279 }
2280
2281 void
2282 AudioDiskstream::monitor_input (bool yn)
2283 {
2284         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2285                 
2286                 if ((*chan).source) {
2287                         (*chan).source->request_monitor_input (yn);
2288                 }
2289         }
2290 }
2291
2292 void
2293 AudioDiskstream::set_capture_offset ()
2294 {
2295         if (_io == 0) {
2296                 /* can't capture, so forget it */
2297                 return;
2298         }
2299
2300         _capture_offset = _io->input_latency();
2301 }
2302
2303 void
2304 AudioDiskstream::set_persistent_align_style (AlignStyle a)
2305 {
2306         _persistent_alignment_style = a;
2307 }
2308
2309 void
2310 AudioDiskstream::set_align_style_from_io ()
2311 {
2312         bool have_physical = false;
2313
2314         if (_io == 0) {
2315                 return;
2316         }
2317
2318         get_input_sources ();
2319         
2320         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2321                 if ((*chan).source && (*chan).source->flags() & JackPortIsPhysical) {
2322                         have_physical = true;
2323                         break;
2324                 }
2325         }
2326
2327         if (have_physical) {
2328                 set_align_style (ExistingMaterial);
2329         } else {
2330                 set_align_style (CaptureTime);
2331         }
2332 }
2333
2334 void
2335 AudioDiskstream::set_align_style (AlignStyle a)
2336 {
2337         if (record_enabled() && _session.actively_recording()) {
2338                 return;
2339         }
2340
2341
2342         if (a != _alignment_style) {
2343                 _alignment_style = a;
2344                 AlignmentStyleChanged ();
2345         }
2346 }
2347
2348 int
2349 AudioDiskstream::add_channel ()
2350 {
2351         /* XXX need to take lock??? */
2352
2353         ChannelInfo chan;
2354
2355         init_channel (chan);
2356
2357         chan.speed_buffer = new Sample[speed_buffer_size];
2358         chan.playback_wrap_buffer = new Sample[wrap_buffer_size];
2359         chan.capture_wrap_buffer = new Sample[wrap_buffer_size];
2360
2361         channels.push_back (chan);
2362
2363         _n_channels = channels.size();
2364
2365         return 0;
2366 }
2367
2368 int
2369 AudioDiskstream::remove_channel ()
2370 {
2371         if (channels.size() > 1) {
2372                 /* XXX need to take lock??? */
2373                 ChannelInfo & chan = channels.back();
2374                 destroy_channel (chan);
2375                 channels.pop_back();
2376
2377                 _n_channels = channels.size();
2378                 return 0;
2379         }
2380
2381         return -1;
2382 }
2383
2384 float
2385 AudioDiskstream::playback_buffer_load () const
2386 {
2387         return (float) ((double) channels.front().playback_buf->read_space()/
2388                         (double) channels.front().playback_buf->bufsize());
2389 }
2390
2391 float
2392 AudioDiskstream::capture_buffer_load () const
2393 {
2394         return (float) ((double) channels.front().capture_buf->write_space()/
2395                         (double) channels.front().capture_buf->bufsize());
2396 }
2397
2398 int
2399 AudioDiskstream::set_loop (Location *location)
2400 {
2401         if (location) {
2402                 if (location->start() >= location->end()) {
2403                         error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
2404                         return -1;
2405                 }
2406         }
2407
2408         loop_location = location;
2409
2410          LoopSet (location); /* EMIT SIGNAL */
2411         return 0;
2412 }
2413
2414 jack_nframes_t
2415 AudioDiskstream::get_capture_start_frame (uint32_t n)
2416 {
2417         Glib::Mutex::Lock lm (capture_info_lock);
2418
2419         if (capture_info.size() > n) {
2420                 return capture_info[n]->start;
2421         }
2422         else {
2423                 return capture_start_frame;
2424         }
2425 }
2426
2427 jack_nframes_t
2428 AudioDiskstream::get_captured_frames (uint32_t n)
2429 {
2430         Glib::Mutex::Lock lm (capture_info_lock);
2431
2432         if (capture_info.size() > n) {
2433                 return capture_info[n]->frames;
2434         }
2435         else {
2436                 return capture_captured;
2437         }
2438 }
2439
2440 void
2441 AudioDiskstream::punch_in ()
2442 {
2443 }
2444
2445 void
2446 AudioDiskstream::punch_out ()
2447 {
2448 }
2449
2450 int
2451 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2452 {
2453         const XMLProperty* prop;
2454         XMLNodeList nlist = node.children();
2455         XMLNodeIterator niter;
2456         AudioFileSource* fs;
2457         AudioFileSource* first_fs = 0;
2458         AudioRegion::SourceList pending_sources;
2459         jack_nframes_t position;
2460
2461         if ((prop = node.property (X_("at"))) == 0) {
2462                 return -1;
2463         }
2464
2465         if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2466                 return -1;
2467         }
2468
2469         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2470                 if ((*niter)->name() == X_("file")) {
2471
2472                         if ((prop = (*niter)->property (X_("path"))) == 0) {
2473                                 continue;
2474                         }
2475
2476                         try {
2477                                 fs = new SndFileSource (prop->value(), 
2478                                                         Config->get_native_file_data_format(),
2479                                                         Config->get_native_file_header_format(),
2480                                                         _session.frame_rate());
2481                         }
2482
2483                         catch (failed_constructor& err) {
2484                                 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2485                                                   _name, prop->value())
2486                                       << endmsg;
2487                                 return -1;
2488                         }
2489
2490                         pending_sources.push_back (fs);
2491                         
2492                         if (first_fs == 0) {
2493                                 first_fs = fs;
2494                         }
2495
2496                         fs->set_captured_for (_name);
2497                 }
2498         }
2499
2500         if (pending_sources.size() == 0) {
2501                 /* nothing can be done */
2502                 return 1;
2503         }
2504
2505         if (pending_sources.size() != _n_channels) {
2506                 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2507                       << endmsg;
2508                 return -1;
2509         }
2510
2511         AudioRegion* region;
2512         
2513         try {
2514                 region = new AudioRegion (pending_sources, 0, first_fs->length(),
2515                                           region_name_from_path (first_fs->name()), 
2516                                           0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
2517                 
2518                 region->special_set_position (0);
2519         }
2520
2521         catch (failed_constructor& err) {
2522                 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2523                                   _name)
2524                       << endmsg;
2525                 
2526                 return -1;
2527         }
2528
2529         try {
2530                 region = new AudioRegion (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name()));
2531         }
2532
2533         catch (failed_constructor& err) {
2534                 error << string_compose (_("%1: cannot create region from pending capture sources"),
2535                                   _name)
2536                       << endmsg;
2537                 
2538                 return -1;
2539         }
2540
2541         _playlist->add_region (*region, position);
2542
2543         return 0;
2544 }
2545
2546 void
2547 AudioDiskstream::set_roll_delay (jack_nframes_t nframes)
2548 {
2549         _roll_delay = nframes;
2550 }
2551
2552 void
2553 AudioDiskstream::set_destructive (bool yn)
2554 {
2555         if (yn != destructive()) {
2556                 reset_write_sources (true, true);
2557                 if (yn) {
2558                         _flags |= Destructive;
2559                 } else {
2560                         _flags &= ~Destructive;
2561                 }
2562         }
2563 }