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