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