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