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