Fix broken whitespace. I'd apologize for the compile times if it was my fault :D
[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());
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 (ringbuffers
749            can only handle size-1, otherwise they appear to be empty)
750         */
751         size--;
752
753         uint32_t n=0;
754         framepos_t start;
755
756         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
757
758                 start = overwrite_frame;
759                 framecnt_t cnt = size;
760
761                 /* to fill the buffer without resetting the playback sample, we need to
762                    do it one or two chunks (normally two).
763
764                    |----------------------------------------------------------------------|
765
766                                        ^
767                                        overwrite_offset
768                     |<- second chunk->||<----------------- first chunk ------------------>|
769
770                 */
771
772                 framecnt_t to_read = size - overwrite_offset;
773
774                 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
775                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
776                                          _id, size, playback_sample) << endmsg;
777                         goto out;
778                 }
779
780                 if (cnt > to_read) {
781
782                         cnt -= to_read;
783
784                         if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
785                                   start, cnt, *chan, n, reversed)) {
786                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
787                                                  _id, size, playback_sample) << endmsg;
788                                 goto out;
789                         }
790                 }
791         }
792
793         ret = 0;
794
795   out:
796         _pending_overwrite = false;
797         delete [] gain_buffer;
798         delete [] mixdown_buffer;
799         return ret;
800 }
801
802 int
803 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
804 {
805         uint32_t n;
806         int ret = -1;
807         ChannelList::iterator chan;
808         boost::shared_ptr<ChannelList> c = channels.reader();
809
810         Glib::Mutex::Lock lm (state_lock);
811
812         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
813                 (*chan)->playback_buf->reset ();
814                 (*chan)->capture_buf->reset ();
815         }
816
817         /* can't rec-enable in destructive mode if transport is before start */
818
819         if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
820                 disengage_record_enable ();
821         }
822
823         playback_sample = frame;
824         file_frame = frame;
825
826         if (complete_refill) {
827                 while ((ret = do_refill_with_alloc ()) > 0) ;
828         } else {
829                 ret = do_refill_with_alloc ();
830         }
831
832         return ret;
833 }
834
835 int
836 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
837 {
838         ChannelList::iterator chan;
839         boost::shared_ptr<ChannelList> c = channels.reader();
840
841         for (chan = c->begin(); chan != c->end(); ++chan) {
842                 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
843                         return false;
844                 }
845         }
846         return true;
847 }
848
849 int
850 AudioDiskstream::internal_playback_seek (framecnt_t distance)
851 {
852         ChannelList::iterator chan;
853         boost::shared_ptr<ChannelList> c = channels.reader();
854
855         for (chan = c->begin(); chan != c->end(); ++chan) {
856                 (*chan)->playback_buf->increment_read_ptr (distance);
857         }
858
859         if (first_recordable_frame < max_framepos) {
860                 first_recordable_frame += distance;
861         }
862         playback_sample += distance;
863
864         return 0;
865 }
866
867 int
868 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
869                        framepos_t& start, framecnt_t cnt,
870                        ChannelInfo* /*channel_info*/, int channel, bool reversed)
871 {
872         framecnt_t this_read = 0;
873         bool reloop = false;
874         framepos_t loop_end = 0;
875         framepos_t loop_start = 0;
876         framecnt_t offset = 0;
877         Location *loc = 0;
878
879         /* XXX we don't currently play loops in reverse. not sure why */
880
881         if (!reversed) {
882
883                 framecnt_t loop_length = 0;
884
885                 /* Make the use of a Location atomic for this read operation.
886
887                    Note: Locations don't get deleted, so all we care about
888                    when I say "atomic" is that we are always pointing to
889                    the same one and using a start/length values obtained
890                    just once.
891                 */
892
893                 if ((loc = loop_location) != 0) {
894                         loop_start = loc->start();
895                         loop_end = loc->end();
896                         loop_length = loop_end - loop_start;
897                 }
898
899                 /* if we are looping, ensure that the first frame we read is at the correct
900                    position within the loop.
901                 */
902
903                 if (loc && start >= loop_end) {
904                         //cerr << "start adjusted from " << start;
905                         start = loop_start + ((start - loop_start) % loop_length);
906                         //cerr << "to " << start << endl;
907                 }
908
909                 //cerr << "start is " << start << "  loopstart: " << loop_start << "  loopend: " << loop_end << endl;
910         }
911
912         if (reversed) {
913                 start -= cnt;
914         }
915
916         while (cnt) {
917
918                 /* take any loop into account. we can't read past the end of the loop. */
919
920                 if (loc && (loop_end - start < cnt)) {
921                         this_read = loop_end - start;
922                         //cerr << "reloop true: thisread: " << this_read << "  cnt: " << cnt << endl;
923                         reloop = true;
924                 } else {
925                         reloop = false;
926                         this_read = cnt;
927                 }
928
929                 if (this_read == 0) {
930                         break;
931                 }
932
933                 this_read = min(cnt,this_read);
934
935                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
936                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
937                                          start) << endmsg;
938                         return -1;
939                 }
940
941                 _read_data_count = _playlist->read_data_count();
942
943                 if (reversed) {
944
945                         swap_by_ptr (buf, buf + this_read - 1);
946
947                 } else {
948
949                         /* if we read to the end of the loop, go back to the beginning */
950
951                         if (reloop) {
952                                 start = loop_start;
953                         } else {
954                                 start += this_read;
955                         }
956                 }
957
958                 cnt -= this_read;
959                 offset += this_read;
960         }
961
962         return 0;
963 }
964
965 int
966 AudioDiskstream::do_refill_with_alloc ()
967 {
968         Sample* mix_buf  = new Sample[disk_io_chunk_frames];
969         float*  gain_buf = new float[disk_io_chunk_frames];
970
971         int ret = _do_refill(mix_buf, gain_buf);
972
973         delete [] mix_buf;
974         delete [] gain_buf;
975
976         return ret;
977 }
978
979 int
980 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
981 {
982         int32_t ret = 0;
983         framecnt_t to_read;
984         RingBufferNPT<Sample>::rw_vector vector;
985         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
986         framecnt_t total_space;
987         framecnt_t zero_fill;
988         uint32_t chan_n;
989         ChannelList::iterator i;
990         boost::shared_ptr<ChannelList> c = channels.reader();
991         framecnt_t ts;
992
993         if (c->empty()) {
994                 return 0;
995         }
996
997         assert(mixdown_buffer);
998         assert(gain_buffer);
999
1000         vector.buf[0] = 0;
1001         vector.len[0] = 0;
1002         vector.buf[1] = 0;
1003         vector.len[1] = 0;
1004
1005         c->front()->playback_buf->get_write_vector (&vector);
1006
1007         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1008                 return 0;
1009         }
1010
1011         /* if there are 2+ chunks of disk i/o possible for
1012            this track, let the caller know so that it can arrange
1013            for us to be called again, ASAP.
1014         */
1015
1016         if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1017                 ret = 1;
1018         }
1019
1020         /* if we're running close to normal speed and there isn't enough
1021            space to do disk_io_chunk_frames of I/O, then don't bother.
1022
1023            at higher speeds, just do it because the sync between butler
1024            and audio thread may not be good enough.
1025         */
1026
1027         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1028                 return 0;
1029         }
1030
1031         /* when slaved, don't try to get too close to the read pointer. this
1032            leaves space for the buffer reversal to have something useful to
1033            work with.
1034         */
1035
1036         if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1037                 return 0;
1038         }
1039
1040         /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1041
1042         total_space = min (disk_io_chunk_frames, total_space);
1043
1044         if (reversed) {
1045
1046                 if (file_frame == 0) {
1047
1048                         /* at start: nothing to do but fill with silence */
1049
1050                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1051
1052                                 ChannelInfo* chan (*i);
1053                                 chan->playback_buf->get_write_vector (&vector);
1054                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1055                                 if (vector.len[1]) {
1056                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1057                                 }
1058                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1059                         }
1060                         return 0;
1061                 }
1062
1063                 if (file_frame < total_space) {
1064
1065                         /* too close to the start: read what we can,
1066                            and then zero fill the rest
1067                         */
1068
1069                         zero_fill = total_space - file_frame;
1070                         total_space = file_frame;
1071
1072                 } else {
1073
1074                         zero_fill = 0;
1075                 }
1076
1077         } else {
1078
1079                 if (file_frame == max_framepos) {
1080
1081                         /* at end: nothing to do but fill with silence */
1082
1083                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1084
1085                                 ChannelInfo* chan (*i);
1086                                 chan->playback_buf->get_write_vector (&vector);
1087                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1088                                 if (vector.len[1]) {
1089                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1090                                 }
1091                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1092                         }
1093                         return 0;
1094                 }
1095
1096                 if (file_frame > max_framepos - total_space) {
1097
1098                         /* to close to the end: read what we can, and zero fill the rest */
1099
1100                         zero_fill = total_space - (max_framepos - file_frame);
1101                         total_space = max_framepos - file_frame;
1102
1103                 } else {
1104                         zero_fill = 0;
1105                 }
1106         }
1107
1108         framepos_t file_frame_tmp = 0;
1109
1110         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1111
1112                 ChannelInfo* chan (*i);
1113                 Sample* buf1;
1114                 Sample* buf2;
1115                 framecnt_t len1, len2;
1116
1117                 chan->playback_buf->get_write_vector (&vector);
1118
1119                 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1120
1121                         /* we're not going to fill the first chunk, so certainly do not bother with the
1122                            other part. it won't be connected with the part we do fill, as in:
1123
1124                            .... => writable space
1125                            ++++ => readable space
1126                            ^^^^ => 1 x disk_io_chunk_frames that would be filled
1127
1128                            |......|+++++++++++++|...............................|
1129                            buf1                buf0
1130                                                 ^^^^^^^^^^^^^^^
1131
1132
1133                            So, just pretend that the buf1 part isn't there.
1134
1135                         */
1136
1137                         vector.buf[1] = 0;
1138                         vector.len[1] = 0;
1139
1140                 }
1141
1142                 ts = total_space;
1143                 file_frame_tmp = file_frame;
1144
1145                 buf1 = vector.buf[0];
1146                 len1 = vector.len[0];
1147                 buf2 = vector.buf[1];
1148                 len2 = vector.len[1];
1149
1150                 to_read = min (ts, len1);
1151                 to_read = min (to_read, disk_io_chunk_frames);
1152
1153                 assert (to_read >= 0);
1154
1155                 if (to_read) {
1156
1157                         if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1158                                 ret = -1;
1159                                 goto out;
1160                         }
1161
1162                         chan->playback_buf->increment_write_ptr (to_read);
1163                         ts -= to_read;
1164                 }
1165
1166                 to_read = min (ts, len2);
1167
1168                 if (to_read) {
1169
1170                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1171                            so read some or all of vector.len[1] as well.
1172                         */
1173
1174                         if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1175                                 ret = -1;
1176                                 goto out;
1177                         }
1178
1179                         chan->playback_buf->increment_write_ptr (to_read);
1180                 }
1181
1182                 if (zero_fill) {
1183                         /* do something */
1184                 }
1185
1186         }
1187
1188         file_frame = file_frame_tmp;
1189         assert (file_frame >= 0);
1190
1191   out:
1192
1193         return ret;
1194 }
1195
1196 /** Flush pending data to disk.
1197  *
1198  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1199  * of data to disk. it will never write more than that.  If it writes that
1200  * much and there is more than that waiting to be written, it will return 1,
1201  * otherwise 0 on success or -1 on failure.
1202  *
1203  * If there is less than disk_io_chunk_frames to be written, no data will be
1204  * written at all unless @a force_flush is true.
1205  */
1206 int
1207 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1208 {
1209         uint32_t to_write;
1210         int32_t ret = 0;
1211         RingBufferNPT<Sample>::rw_vector vector;
1212         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1213         framecnt_t total;
1214
1215         _write_data_count = 0;
1216
1217         transvec.buf[0] = 0;
1218         transvec.buf[1] = 0;
1219         vector.buf[0] = 0;
1220         vector.buf[1] = 0;
1221
1222         boost::shared_ptr<ChannelList> c = channels.reader();
1223         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1224
1225                 (*chan)->capture_buf->get_read_vector (&vector);
1226
1227                 total = vector.len[0] + vector.len[1];
1228
1229                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1230                         goto out;
1231                 }
1232
1233                 /* if there are 2+ chunks of disk i/o possible for
1234                    this track, let the caller know so that it can arrange
1235                    for us to be called again, ASAP.
1236
1237                    if we are forcing a flush, then if there is* any* extra
1238                    work, let the caller know.
1239
1240                    if we are no longer recording and there is any extra work,
1241                    let the caller know too.
1242                 */
1243
1244                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1245                         ret = 1;
1246                 }
1247
1248                 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1249
1250                 // check the transition buffer when recording destructive
1251                 // important that we get this after the capture buf
1252
1253                 if (destructive()) {
1254                         (*chan)->capture_transition_buf->get_read_vector(&transvec);
1255                         size_t transcount = transvec.len[0] + transvec.len[1];
1256                         bool have_start = false;
1257                         size_t ti;
1258
1259                         for (ti=0; ti < transcount; ++ti) {
1260                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1261
1262                                 if (captrans.type == CaptureStart) {
1263                                         // by definition, the first data we got above represents the given capture pos
1264
1265                                         (*chan)->write_source->mark_capture_start (captrans.capture_val);
1266                                         (*chan)->curr_capture_cnt = 0;
1267
1268                                         have_start = true;
1269                                 }
1270                                 else if (captrans.type == CaptureEnd) {
1271
1272                                         // capture end, the capture_val represents total frames in capture
1273
1274                                         if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1275
1276                                                 // shorten to make the write a perfect fit
1277                                                 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1278
1279                                                 if (nto_write < to_write) {
1280                                                         ret = 1; // should we?
1281                                                 }
1282                                                 to_write = nto_write;
1283
1284                                                 (*chan)->write_source->mark_capture_end ();
1285
1286                                                 // increment past this transition, but go no further
1287                                                 ++ti;
1288                                                 break;
1289                                         }
1290                                         else {
1291                                                 // actually ends just beyond this chunk, so force more work
1292                                                 ret = 1;
1293                                                 break;
1294                                         }
1295                                 }
1296                         }
1297
1298                         if (ti > 0) {
1299                                 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1300                         }
1301                 }
1302
1303                 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1304                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1305                         return -1;
1306                 }
1307
1308                 (*chan)->capture_buf->increment_read_ptr (to_write);
1309                 (*chan)->curr_capture_cnt += to_write;
1310
1311                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1312
1313                         /* we wrote all of vector.len[0] but it wasn't an entire
1314                            disk_io_chunk_frames of data, so arrange for some part
1315                            of vector.len[1] to be flushed to disk as well.
1316                         */
1317
1318                         to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1319
1320                         if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1321                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1322                                 return -1;
1323                         }
1324
1325                         _write_data_count += (*chan)->write_source->write_data_count();
1326
1327                         (*chan)->capture_buf->increment_read_ptr (to_write);
1328                         (*chan)->curr_capture_cnt += to_write;
1329                 }
1330         }
1331
1332   out:
1333         return ret;
1334 }
1335
1336 void
1337 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1338 {
1339         uint32_t buffer_position;
1340         bool more_work = true;
1341         int err = 0;
1342         boost::shared_ptr<AudioRegion> region;
1343         framecnt_t total_capture;
1344         SourceList srcs;
1345         SourceList::iterator src;
1346         ChannelList::iterator chan;
1347         vector<CaptureInfo*>::iterator ci;
1348         boost::shared_ptr<ChannelList> c = channels.reader();
1349         uint32_t n = 0;
1350         bool mark_write_completed = false;
1351
1352         finish_capture (true, c);
1353
1354         /* butler is already stopped, but there may be work to do
1355            to flush remaining data to disk.
1356         */
1357
1358         while (more_work && !err) {
1359                 switch (do_flush (TransportContext, true)) {
1360                 case 0:
1361                         more_work = false;
1362                         break;
1363                 case 1:
1364                         break;
1365                 case -1:
1366                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1367                         err++;
1368                 }
1369         }
1370
1371         /* XXX is there anything we can do if err != 0 ? */
1372         Glib::Mutex::Lock lm (capture_info_lock);
1373
1374         if (capture_info.empty()) {
1375                 return;
1376         }
1377
1378         if (abort_capture) {
1379
1380                 if (destructive()) {
1381                         goto outout;
1382                 }
1383
1384                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1385
1386                         if ((*chan)->write_source) {
1387
1388                                 (*chan)->write_source->mark_for_remove ();
1389                                 (*chan)->write_source->drop_references ();
1390                                 (*chan)->write_source.reset ();
1391                         }
1392
1393                         /* new source set up in "out" below */
1394                 }
1395
1396                 goto out;
1397         }
1398
1399         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1400                 total_capture += (*ci)->frames;
1401         }
1402
1403         /* figure out the name for this take */
1404
1405         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1406
1407                 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1408
1409                 if (s) {
1410                         srcs.push_back (s);
1411                         s->update_header (capture_info.front()->start, when, twhen);
1412                         s->set_captured_for (_name.val());
1413                         s->mark_immutable ();
1414
1415                         if (Config->get_auto_analyse_audio()) {
1416                                 Analyser::queue_source_for_analysis (s, true);
1417                         }
1418                 }
1419         }
1420
1421         /* destructive tracks have a single, never changing region */
1422
1423         if (destructive()) {
1424
1425                 /* send a signal that any UI can pick up to do the right thing. there is
1426                    a small problem here in that a UI may need the peak data to be ready
1427                    for the data that was recorded and this isn't interlocked with that
1428                    process. this problem is deferred to the UI.
1429                  */
1430
1431                 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1432
1433         } else {
1434
1435                 string whole_file_region_name;
1436                 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1437
1438                 /* Register a new region with the Session that
1439                    describes the entire source. Do this first
1440                    so that any sub-regions will obviously be
1441                    children of this one (later!)
1442                 */
1443
1444                 try {
1445                         PropertyList plist;
1446
1447                         plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1448                         plist.add (Properties::length, total_capture);
1449                         plist.add (Properties::name, whole_file_region_name);
1450                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1451                         rx->set_automatic (true);
1452                         rx->set_whole_file (true);
1453
1454                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1455                         region->special_set_position (capture_info.front()->start);
1456                 }
1457
1458
1459                 catch (failed_constructor& err) {
1460                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1461                         /* XXX what now? */
1462                 }
1463
1464                 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1465
1466                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1467
1468                 _playlist->clear_changes ();
1469                 _playlist->freeze ();
1470
1471                 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1472
1473                         string region_name;
1474
1475                         RegionFactory::region_name (region_name, whole_file_region_name, false);
1476
1477                         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1478                                                                               _name, (*ci)->start, (*ci)->frames, region_name));
1479
1480                         try {
1481
1482                                 PropertyList plist;
1483
1484                                 plist.add (Properties::start, buffer_position);
1485                                 plist.add (Properties::length, (*ci)->frames);
1486                                 plist.add (Properties::name, region_name);
1487
1488                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1489                                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1490                         }
1491
1492                         catch (failed_constructor& err) {
1493                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1494                                 continue; /* XXX is this OK? */
1495                         }
1496
1497                         i_am_the_modifier++;
1498
1499                         if (_playlist->explicit_relayering()) {
1500                                 /* We are in `explicit relayering' mode, so we must specify which layer this new region
1501                                    should end up on.  Put it at the top.
1502                                 */
1503                                 region->set_layer (_playlist->top_layer() + 1);
1504                                 region->set_pending_explicit_relayer (true);
1505                         }
1506
1507                         _playlist->add_region (region, (*ci)->start, 1, non_layered());
1508                         i_am_the_modifier--;
1509
1510                         buffer_position += (*ci)->frames;
1511                 }
1512
1513                 _playlist->thaw ();
1514                 _session.add_command (new StatefulDiffCommand (_playlist));
1515         }
1516
1517         mark_write_completed = true;
1518
1519   out:
1520         reset_write_sources (mark_write_completed);
1521
1522   outout:
1523
1524         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1525                 delete *ci;
1526         }
1527
1528         capture_info.clear ();
1529         capture_start_frame = 0;
1530 }
1531
1532 void
1533 AudioDiskstream::transport_looped (framepos_t transport_frame)
1534 {
1535         if (was_recording) {
1536                 // all we need to do is finish this capture, with modified capture length
1537                 boost::shared_ptr<ChannelList> c = channels.reader();
1538
1539                 // adjust the capture length knowing that the data will be recorded to disk
1540                 // only necessary after the first loop where we're recording
1541                 if (capture_info.size() == 0) {
1542                         capture_captured += _capture_offset;
1543
1544                         if (_alignment_style == ExistingMaterial) {
1545                                 capture_captured += _session.worst_output_latency();
1546                         } else {
1547                                 capture_captured += _roll_delay;
1548                         }
1549                 }
1550
1551                 finish_capture (true, c);
1552
1553                 // the next region will start recording via the normal mechanism
1554                 // we'll set the start position to the current transport pos
1555                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1556                 capture_start_frame = transport_frame;
1557                 first_recordable_frame = transport_frame; // mild lie
1558                 last_recordable_frame = max_framepos;
1559                 was_recording = true;
1560
1561                 if (recordable() && destructive()) {
1562                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1563
1564                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1565                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1566
1567                                 if (transvec.len[0] > 0) {
1568                                         transvec.buf[0]->type = CaptureStart;
1569                                         transvec.buf[0]->capture_val = capture_start_frame;
1570                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
1571                                 }
1572                                 else {
1573                                         // bad!
1574                                         fatal << X_("programming error: capture_transition_buf is full on rec loop!  inconceivable!")
1575                                               << endmsg;
1576                                 }
1577                         }
1578                 }
1579
1580         }
1581 }
1582
1583 void
1584 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1585 {
1586         was_recording = false;
1587         first_recordable_frame = max_framepos;
1588         last_recordable_frame = max_framepos;
1589
1590         if (capture_captured == 0) {
1591                 return;
1592         }
1593
1594         if (recordable() && destructive()) {
1595                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1596
1597                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1598                         (*chan)->capture_transition_buf->get_write_vector(&transvec);
1599
1600                         if (transvec.len[0] > 0) {
1601                                 transvec.buf[0]->type = CaptureEnd;
1602                                 transvec.buf[0]->capture_val = capture_captured;
1603                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
1604                         }
1605                         else {
1606                                 // bad!
1607                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1608                         }
1609                 }
1610         }
1611
1612
1613         CaptureInfo* ci = new CaptureInfo;
1614
1615         ci->start =  capture_start_frame;
1616         ci->frames = capture_captured;
1617
1618         /* XXX theoretical race condition here. Need atomic exchange ?
1619            However, the circumstances when this is called right
1620            now (either on record-disable or transport_stopped)
1621            mean that no actual race exists. I think ...
1622            We now have a capture_info_lock, but it is only to be used
1623            to synchronize in the transport_stop and the capture info
1624            accessors, so that invalidation will not occur (both non-realtime).
1625         */
1626
1627         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1628
1629         capture_info.push_back (ci);
1630         capture_captured = 0;
1631
1632         /* now we've finished a capture, reset first_recordable_frame for next time */
1633         first_recordable_frame = max_framepos;
1634 }
1635
1636 void
1637 AudioDiskstream::set_record_enabled (bool yn)
1638 {
1639         if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1640                 return;
1641         }
1642
1643         /* can't rec-enable in destructive mode if transport is before start */
1644
1645         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1646                 return;
1647         }
1648
1649         /* yes, i know that this not proof against race conditions, but its
1650            good enough. i think.
1651         */
1652
1653         if (record_enabled() != yn) {
1654                 if (yn) {
1655                         engage_record_enable ();
1656                 } else {
1657                         disengage_record_enable ();
1658                 }
1659         }
1660 }
1661
1662 void
1663 AudioDiskstream::engage_record_enable ()
1664 {
1665         bool rolling = _session.transport_speed() != 0.0f;
1666         boost::shared_ptr<ChannelList> c = channels.reader();
1667
1668         g_atomic_int_set (&_record_enabled, 1);
1669         capturing_sources.clear ();
1670
1671         if (Config->get_monitoring_model() == HardwareMonitoring) {
1672
1673                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1674                         (*chan)->source.ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1675                         capturing_sources.push_back ((*chan)->write_source);
1676                         (*chan)->write_source->mark_streaming_write_started ();
1677                 }
1678
1679         } else {
1680                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1681                         capturing_sources.push_back ((*chan)->write_source);
1682                         (*chan)->write_source->mark_streaming_write_started ();
1683                 }
1684         }
1685
1686         RecordEnableChanged (); /* EMIT SIGNAL */
1687 }
1688
1689 void
1690 AudioDiskstream::disengage_record_enable ()
1691 {
1692         g_atomic_int_set (&_record_enabled, 0);
1693         boost::shared_ptr<ChannelList> c = channels.reader();
1694         if (Config->get_monitoring_model() == HardwareMonitoring) {
1695                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1696                         (*chan)->source.ensure_monitor_input (false);
1697                 }
1698         }
1699         capturing_sources.clear ();
1700         RecordEnableChanged (); /* EMIT SIGNAL */
1701 }
1702
1703 XMLNode&
1704 AudioDiskstream::get_state ()
1705 {
1706         XMLNode& node (Diskstream::get_state());
1707         char buf[64] = "";
1708         LocaleGuard lg (X_("POSIX"));
1709
1710         boost::shared_ptr<ChannelList> c = channels.reader();
1711         snprintf (buf, sizeof(buf), "%zd", c->size());
1712         node.add_property ("channels", buf);
1713
1714         if (!capturing_sources.empty() && _session.get_record_enabled()) {
1715
1716                 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1717                 XMLNode* cs_grandchild;
1718
1719                 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1720                         cs_grandchild = new XMLNode (X_("file"));
1721                         cs_grandchild->add_property (X_("path"), (*i)->path());
1722                         cs_child->add_child_nocopy (*cs_grandchild);
1723                 }
1724
1725                 /* store the location where capture will start */
1726
1727                 Location* pi;
1728
1729                 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1730                         snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1731                 } else {
1732                         snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1733                 }
1734
1735                 cs_child->add_property (X_("at"), buf);
1736                 node.add_child_nocopy (*cs_child);
1737         }
1738
1739         return node;
1740 }
1741
1742 int
1743 AudioDiskstream::set_state (const XMLNode& node, int version)
1744 {
1745         const XMLProperty* prop;
1746         XMLNodeList nlist = node.children();
1747         XMLNodeIterator niter;
1748         uint32_t nchans = 1;
1749         XMLNode* capture_pending_node = 0;
1750         LocaleGuard lg (X_("POSIX"));
1751
1752         /* prevent write sources from being created */
1753
1754         in_set_state = true;
1755
1756         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1757                 if ((*niter)->name() == IO::state_node_name) {
1758                         deprecated_io_node = new XMLNode (**niter);
1759                 }
1760
1761                 if ((*niter)->name() == X_("CapturingSources")) {
1762                         capture_pending_node = *niter;
1763                 }
1764         }
1765
1766         if (Diskstream::set_state (node, version)) {
1767                 return -1;
1768         }
1769
1770         if ((prop = node.property ("channels")) != 0) {
1771                 nchans = atoi (prop->value().c_str());
1772         }
1773
1774         // create necessary extra channels
1775         // we are always constructed with one and we always need one
1776
1777         _n_channels.set(DataType::AUDIO, channels.reader()->size());
1778
1779         if (nchans > _n_channels.n_audio()) {
1780
1781                 add_channel (nchans - _n_channels.n_audio());
1782                 IO::PortCountChanged(_n_channels);
1783
1784         } else if (nchans < _n_channels.n_audio()) {
1785
1786                 remove_channel (_n_channels.n_audio() - nchans);
1787         }
1788
1789
1790
1791         if (!destructive() && capture_pending_node) {
1792                 /* destructive streams have one and only one source per channel,
1793                    and so they never end up in pending capture in any useful
1794                    sense.
1795                 */
1796                 use_pending_capture_data (*capture_pending_node);
1797         }
1798
1799         in_set_state = false;
1800
1801         /* make sure this is clear before we do anything else */
1802
1803         capturing_sources.clear ();
1804
1805         /* write sources are handled when we handle the input set
1806            up of the IO that owns this DS (::non_realtime_input_change())
1807         */
1808
1809         return 0;
1810 }
1811
1812 int
1813 AudioDiskstream::use_new_write_source (uint32_t n)
1814 {
1815         boost::shared_ptr<ChannelList> c = channels.reader();
1816
1817         if (!recordable()) {
1818                 return 1;
1819         }
1820
1821         if (n >= c->size()) {
1822                 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1823                 return -1;
1824         }
1825
1826         ChannelInfo* chan = (*c)[n];
1827
1828         try {
1829                 if ((chan->write_source = _session.create_audio_source_for_session (
1830                              n_channels().n_audio(), name(), n, destructive())) == 0) {
1831                         throw failed_constructor();
1832                 }
1833         }
1834
1835         catch (failed_constructor &err) {
1836                 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1837                 chan->write_source.reset ();
1838                 return -1;
1839         }
1840
1841         /* do not remove destructive files even if they are empty */
1842
1843         chan->write_source->set_allow_remove_if_empty (!destructive());
1844
1845         return 0;
1846 }
1847
1848 list<boost::shared_ptr<Source> >
1849 AudioDiskstream::steal_write_sources()
1850 {
1851         /* not possible to steal audio write sources */
1852         list<boost::shared_ptr<Source> > ret;
1853         return ret;
1854 }
1855
1856 void
1857 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1858 {
1859         ChannelList::iterator chan;
1860         boost::shared_ptr<ChannelList> c = channels.reader();
1861         uint32_t n;
1862
1863         if (!_session.writable() || !recordable()) {
1864                 return;
1865         }
1866
1867         capturing_sources.clear ();
1868
1869         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1870
1871                 if (!destructive()) {
1872
1873                         if ((*chan)->write_source) {
1874
1875                                 if (mark_write_complete) {
1876                                         (*chan)->write_source->mark_streaming_write_completed ();
1877                                         (*chan)->write_source->done_with_peakfile_writes ();
1878                                 }
1879
1880                                 if ((*chan)->write_source->removable()) {
1881                                         (*chan)->write_source->mark_for_remove ();
1882                                         (*chan)->write_source->drop_references ();
1883                                 }
1884
1885                                 (*chan)->write_source.reset ();
1886                         }
1887
1888                         use_new_write_source (n);
1889
1890                         if (record_enabled()) {
1891                                 capturing_sources.push_back ((*chan)->write_source);
1892                         }
1893
1894                 } else {
1895
1896                         if ((*chan)->write_source == 0) {
1897                                 use_new_write_source (n);
1898                         }
1899                 }
1900         }
1901
1902         if (destructive() && !c->empty ()) {
1903
1904                 /* we now have all our write sources set up, so create the
1905                    playlist's single region.
1906                 */
1907
1908                 if (_playlist->empty()) {
1909                         setup_destructive_playlist ();
1910                 }
1911         }
1912 }
1913
1914 void
1915 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1916 {
1917         if (_session.get_block_size() > speed_buffer_size) {
1918                 speed_buffer_size = _session.get_block_size();
1919                 boost::shared_ptr<ChannelList> c = channels.reader();
1920
1921                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1922                         if ((*chan)->speed_buffer)
1923                                 delete [] (*chan)->speed_buffer;
1924                         (*chan)->speed_buffer = new Sample[speed_buffer_size];
1925                 }
1926         }
1927         allocate_temporary_buffers ();
1928 }
1929
1930 void
1931 AudioDiskstream::allocate_temporary_buffers ()
1932 {
1933         /* make sure the wrap buffer is at least large enough to deal
1934            with the speeds up to 1.2, to allow for micro-variation
1935            when slaving to MTC, Timecode etc.
1936         */
1937
1938         double const sp = max (fabsf (_actual_speed), 1.2f);
1939         framecnt_t required_wrap_size = (framecnt_t) floor (_session.get_block_size() * sp) + 1;
1940
1941         if (required_wrap_size > wrap_buffer_size) {
1942
1943                 boost::shared_ptr<ChannelList> c = channels.reader();
1944
1945                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1946                         if ((*chan)->playback_wrap_buffer)
1947                                 delete [] (*chan)->playback_wrap_buffer;
1948                         (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
1949                         if ((*chan)->capture_wrap_buffer)
1950                                 delete [] (*chan)->capture_wrap_buffer;
1951                         (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
1952                 }
1953
1954                 wrap_buffer_size = required_wrap_size;
1955         }
1956 }
1957
1958 void
1959 AudioDiskstream::monitor_input (bool yn)
1960 {
1961         boost::shared_ptr<ChannelList> c = channels.reader();
1962
1963         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1964                 (*chan)->source.ensure_monitor_input (yn);
1965         }
1966 }
1967
1968 void
1969 AudioDiskstream::set_align_style_from_io ()
1970 {
1971         bool have_physical = false;
1972
1973         if (_alignment_choice != Automatic) {
1974                 return;
1975         }
1976
1977         if (_io == 0) {
1978                 return;
1979         }
1980
1981         get_input_sources ();
1982
1983         boost::shared_ptr<ChannelList> c = channels.reader();
1984
1985         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1986                 if ((*chan)->source.is_physical ()) {
1987                         have_physical = true;
1988                         break;
1989                 }
1990         }
1991
1992         if (have_physical) {
1993                 set_align_style (ExistingMaterial);
1994         } else {
1995                 set_align_style (CaptureTime);
1996         }
1997 }
1998
1999 int
2000 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2001 {
2002         while (how_many--) {
2003                 c->push_back (new ChannelInfo(
2004                                       _session.butler()->audio_diskstream_playback_buffer_size(),
2005                                       _session.butler()->audio_diskstream_capture_buffer_size(),
2006                                       speed_buffer_size, wrap_buffer_size));
2007                 interpolation.add_channel_to (
2008                         _session.butler()->audio_diskstream_playback_buffer_size(),
2009                         speed_buffer_size);
2010         }
2011
2012         _n_channels.set(DataType::AUDIO, c->size());
2013
2014         return 0;
2015 }
2016
2017 int
2018 AudioDiskstream::add_channel (uint32_t how_many)
2019 {
2020         RCUWriter<ChannelList> writer (channels);
2021         boost::shared_ptr<ChannelList> c = writer.get_copy();
2022
2023         return add_channel_to (c, how_many);
2024 }
2025
2026 int
2027 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2028 {
2029         while (how_many-- && !c->empty()) {
2030                 delete c->back();
2031                 c->pop_back();
2032                 interpolation.remove_channel_from ();
2033         }
2034
2035         _n_channels.set(DataType::AUDIO, c->size());
2036
2037         return 0;
2038 }
2039
2040 int
2041 AudioDiskstream::remove_channel (uint32_t how_many)
2042 {
2043         RCUWriter<ChannelList> writer (channels);
2044         boost::shared_ptr<ChannelList> c = writer.get_copy();
2045
2046         return remove_channel_from (c, how_many);
2047 }
2048
2049 float
2050 AudioDiskstream::playback_buffer_load () const
2051 {
2052         boost::shared_ptr<ChannelList> c = channels.reader();
2053
2054         if (c->empty ()) {
2055                 return 0;
2056         }
2057
2058         return (float) ((double) c->front()->playback_buf->read_space()/
2059                         (double) c->front()->playback_buf->bufsize());
2060 }
2061
2062 float
2063 AudioDiskstream::capture_buffer_load () const
2064 {
2065         boost::shared_ptr<ChannelList> c = channels.reader();
2066
2067         if (c->empty ()) {
2068                 return 0;
2069         }
2070
2071         return (float) ((double) c->front()->capture_buf->write_space()/
2072                         (double) c->front()->capture_buf->bufsize());
2073 }
2074
2075 int
2076 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2077 {
2078         const XMLProperty* prop;
2079         XMLNodeList nlist = node.children();
2080         XMLNodeIterator niter;
2081         boost::shared_ptr<AudioFileSource> fs;
2082         boost::shared_ptr<AudioFileSource> first_fs;
2083         SourceList pending_sources;
2084         framepos_t position;
2085
2086         if ((prop = node.property (X_("at"))) == 0) {
2087                 return -1;
2088         }
2089
2090         if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2091                 return -1;
2092         }
2093
2094         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2095                 if ((*niter)->name() == X_("file")) {
2096
2097                         if ((prop = (*niter)->property (X_("path"))) == 0) {
2098                                 continue;
2099                         }
2100
2101                         // This protects sessions from errant CapturingSources in stored sessions
2102                         struct stat sbuf;
2103                         if (stat (prop->value().c_str(), &sbuf)) {
2104                                 continue;
2105                         }
2106
2107                         try {
2108                                 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2109                                         SourceFactory::createWritable (
2110                                                 DataType::AUDIO, _session,
2111                                                 prop->value(), string(), false, _session.frame_rate()));
2112                         }
2113
2114                         catch (failed_constructor& err) {
2115                                 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2116                                                   _name, prop->value())
2117                                       << endmsg;
2118                                 return -1;
2119                         }
2120
2121                         pending_sources.push_back (fs);
2122
2123                         if (first_fs == 0) {
2124                                 first_fs = fs;
2125                         }
2126
2127                         fs->set_captured_for (_name.val());
2128                 }
2129         }
2130
2131         if (pending_sources.size() == 0) {
2132                 /* nothing can be done */
2133                 return 1;
2134         }
2135
2136         if (pending_sources.size() != _n_channels.n_audio()) {
2137                 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2138                       << endmsg;
2139                 return -1;
2140         }
2141
2142         boost::shared_ptr<AudioRegion> region;
2143
2144         try {
2145
2146                 PropertyList plist;
2147
2148                 plist.add (Properties::start, 0);
2149                 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2150                 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2151
2152                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2153
2154                 region->set_automatic (true);
2155                 region->set_whole_file (true);
2156                 region->special_set_position (0);
2157         }
2158
2159         catch (failed_constructor& err) {
2160                 error << string_compose (
2161                                 _("%1: cannot create whole-file region from pending capture sources"),
2162                                 _name) << endmsg;
2163
2164                 return -1;
2165         }
2166
2167         _playlist->add_region (region, position);
2168
2169         return 0;
2170 }
2171
2172 int
2173 AudioDiskstream::set_non_layered (bool yn)
2174 {
2175         if (yn != non_layered()) {
2176
2177                 if (yn) {
2178                         _flags = Flag (_flags | NonLayered);
2179                 } else {
2180                         _flags = Flag (_flags & ~NonLayered);
2181                 }
2182         }
2183
2184         return 0;
2185 }
2186
2187 int
2188 AudioDiskstream::set_destructive (bool yn)
2189 {
2190         if (yn != destructive()) {
2191
2192                 if (yn) {
2193                         bool bounce_ignored;
2194                         /* requestor should already have checked this and
2195                            bounced if necessary and desired
2196                         */
2197                         if (!can_become_destructive (bounce_ignored)) {
2198                                 return -1;
2199                         }
2200                         _flags = Flag (_flags | Destructive);
2201                         use_destructive_playlist ();
2202                 } else {
2203                         _flags = Flag (_flags & ~Destructive);
2204                         reset_write_sources (true, true);
2205                 }
2206         }
2207
2208         return 0;
2209 }
2210
2211 bool
2212 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2213 {
2214         if (!_playlist) {
2215                 requires_bounce = false;
2216                 return false;
2217         }
2218
2219         /* is there only one region ? */
2220
2221         if (_playlist->n_regions() != 1) {
2222                 requires_bounce = true;
2223                 return false;
2224         }
2225
2226         boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2227         if (!first) {
2228                 requires_bounce = false;
2229                 return true;
2230         }
2231
2232         /* do the source(s) for the region cover the session start position ? */
2233
2234         if (first->position() != _session.current_start_frame()) {
2235                 if (first->start() > _session.current_start_frame()) {
2236                         requires_bounce = true;
2237                         return false;
2238                 }
2239         }
2240
2241         /* is the source used by only 1 playlist ? */
2242
2243         boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2244
2245         assert (afirst);
2246
2247         if (_session.playlists->source_use_count (afirst->source()) > 1) {
2248                 requires_bounce = true;
2249                 return false;
2250         }
2251
2252         requires_bounce = false;
2253         return true;
2254 }
2255
2256 void
2257 AudioDiskstream::adjust_playback_buffering ()
2258 {
2259         boost::shared_ptr<ChannelList> c = channels.reader();
2260
2261         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2262                 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2263         }
2264 }
2265
2266 void
2267 AudioDiskstream::adjust_capture_buffering ()
2268 {
2269         boost::shared_ptr<ChannelList> c = channels.reader();
2270
2271         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2272                 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2273         }
2274 }
2275
2276 bool
2277 AudioDiskstream::ChannelSource::is_physical () const
2278 {
2279         if (name.empty()) {
2280                 return false;
2281         }
2282
2283         return AudioEngine::instance()->port_is_physical (name);
2284 }
2285
2286 void
2287 AudioDiskstream::ChannelSource::ensure_monitor_input (bool yn) const
2288 {
2289         if (name.empty()) {
2290                 return;
2291         }
2292
2293         return AudioEngine::instance()->ensure_monitor_input (name, yn);
2294 }
2295
2296 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2297 {
2298         peak_power = 0.0f;
2299         current_capture_buffer = 0;
2300         current_playback_buffer = 0;
2301         curr_capture_cnt = 0;
2302
2303         speed_buffer = new Sample[speed_size];
2304         playback_wrap_buffer = new Sample[wrap_size];
2305         capture_wrap_buffer = new Sample[wrap_size];
2306
2307         playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2308         capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2309         capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2310
2311         /* touch the ringbuffer buffers, which will cause
2312            them to be mapped into locked physical RAM if
2313            we're running with mlockall(). this doesn't do
2314            much if we're not.
2315         */
2316
2317         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2318         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2319         memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2320 }
2321
2322 void
2323 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2324 {
2325         delete playback_buf;
2326         playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2327         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2328 }
2329
2330 void
2331 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2332 {
2333         delete capture_buf;
2334
2335         capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2336         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2337 }
2338
2339 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2340 {
2341         write_source.reset ();
2342
2343         delete [] speed_buffer;
2344         speed_buffer = 0;
2345
2346         delete [] playback_wrap_buffer;
2347         playback_wrap_buffer = 0;
2348
2349         delete [] capture_wrap_buffer;
2350         capture_wrap_buffer = 0;
2351
2352         delete playback_buf;
2353         playback_buf = 0;
2354
2355         delete capture_buf;
2356         capture_buf = 0;
2357
2358         delete capture_transition_buf;
2359         capture_transition_buf = 0;
2360 }
2361
2362
2363 bool
2364 AudioDiskstream::set_name (string const & name)
2365 {
2366         Diskstream::set_name (name);
2367
2368         /* get a new write source so that its name reflects the new diskstream name */
2369
2370         boost::shared_ptr<ChannelList> c = channels.reader();
2371         ChannelList::iterator i;
2372         int n = 0;
2373
2374         for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2375                 use_new_write_source (n);
2376         }
2377
2378         return true;
2379 }