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