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