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