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