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