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