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