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