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