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