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