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