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