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