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