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