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