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