Comment.
[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         framecnt_t 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
647                         interpolation.set_speed (_target_speed);
648
649                         int channel = 0;
650                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
651                                 ChannelInfo* chaninfo (*chan);
652                                 
653                                 playback_distance = interpolation.interpolate (
654                                         channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
655                                 
656                                 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
657                         }
658                         
659                 } else {
660                         playback_distance = nframes;
661                 }
662
663                 _speed = _target_speed;
664         }
665
666         ret = 0;
667
668         if (commit (playback_distance)) {
669                 need_butler = true;
670         }
671
672   out:
673         return ret;
674 }
675
676 /** Update various things including playback_sample, read pointer on each channel's playback_buf
677  *  and write pointer on each channel's capture_buf.  Also wout whether the butler is needed.
678  *  @return true if the butler is required.
679  */
680 bool
681 AudioDiskstream::commit (framecnt_t playback_distance)
682 {
683         bool need_butler = false;
684
685         if (!_io || !_io->active()) {
686                 return false;
687         }
688
689         if (_actual_speed < 0.0) {
690                 playback_sample -= playback_distance;
691         } else {
692                 playback_sample += playback_distance;
693         }
694
695         boost::shared_ptr<ChannelList> c = channels.reader();
696         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
697
698                 (*chan)->playback_buf->increment_read_ptr (playback_distance);
699
700                 if (adjust_capture_position) {
701                         (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
702                 }
703         }
704
705         if (adjust_capture_position != 0) {
706                 capture_captured += adjust_capture_position;
707                 adjust_capture_position = 0;
708         }
709
710         if (c->empty()) {
711                 return false;
712         }
713
714         if (_slaved) {
715                 if (_io && _io->active()) {
716                         need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
717                 } else {
718                         need_butler = false;
719                 }
720         } else {
721                 if (_io && _io->active()) {
722                         need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
723                                 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
724                 } else {
725                         need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
726                 }
727         }
728
729         return need_butler;
730 }
731
732 void
733 AudioDiskstream::set_pending_overwrite (bool yn)
734 {
735         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
736
737         _pending_overwrite = yn;
738
739         overwrite_frame = playback_sample;
740
741         boost::shared_ptr<ChannelList> c = channels.reader ();
742         if (!c->empty ()) {
743                 overwrite_offset = c->front()->playback_buf->get_read_ptr();
744         }
745 }
746
747 int
748 AudioDiskstream::overwrite_existing_buffers ()
749 {
750         boost::shared_ptr<ChannelList> c = channels.reader();
751         if (c->empty ()) {
752                 _pending_overwrite = false;
753                 return 0;
754         }
755
756         Sample* mixdown_buffer;
757         float* gain_buffer;
758         int ret = -1;
759         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
760
761         overwrite_queued = false;
762
763         /* assume all are the same size */
764         framecnt_t size = c->front()->playback_buf->bufsize();
765
766         mixdown_buffer = new Sample[size];
767         gain_buffer = new float[size];
768
769         /* reduce size so that we can fill the buffer correctly (ringbuffers
770            can only handle size-1, otherwise they appear to be empty)
771         */
772         size--;
773
774         uint32_t n=0;
775         framepos_t start;
776
777         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
778
779                 start = overwrite_frame;
780                 framecnt_t cnt = size;
781
782                 /* to fill the buffer without resetting the playback sample, we need to
783                    do it one or two chunks (normally two).
784
785                    |----------------------------------------------------------------------|
786
787                                        ^
788                                        overwrite_offset
789                     |<- second chunk->||<----------------- first chunk ------------------>|
790
791                 */
792
793                 framecnt_t to_read = size - overwrite_offset;
794
795                 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
796                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
797                                                 id(), size, playback_sample) << endmsg;
798                         goto out;
799                 }
800
801                 if (cnt > to_read) {
802
803                         cnt -= to_read;
804
805                         if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
806                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
807                                                         id(), size, playback_sample) << endmsg;
808                                 goto out;
809                         }
810                 }
811         }
812
813         ret = 0;
814
815   out:
816         _pending_overwrite = false;
817         delete [] gain_buffer;
818         delete [] mixdown_buffer;
819         return ret;
820 }
821
822 int
823 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
824 {
825         uint32_t n;
826         int ret = -1;
827         ChannelList::iterator chan;
828         boost::shared_ptr<ChannelList> c = channels.reader();
829
830         Glib::Mutex::Lock lm (state_lock);
831
832         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
833                 (*chan)->playback_buf->reset ();
834                 (*chan)->capture_buf->reset ();
835         }
836
837         /* can't rec-enable in destructive mode if transport is before start */
838
839         if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
840                 disengage_record_enable ();
841         }
842
843         playback_sample = frame;
844         file_frame = frame;
845
846         if (complete_refill) {
847                 while ((ret = do_refill_with_alloc ()) > 0) ;
848         } else {
849                 ret = do_refill_with_alloc ();
850         }
851
852         return ret;
853 }
854
855 int
856 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
857 {
858         ChannelList::iterator chan;
859         boost::shared_ptr<ChannelList> c = channels.reader();
860
861         for (chan = c->begin(); chan != c->end(); ++chan) {
862                 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
863                         return false;
864                 }
865         }
866         return true;
867 }
868
869 int
870 AudioDiskstream::internal_playback_seek (framecnt_t distance)
871 {
872         ChannelList::iterator chan;
873         boost::shared_ptr<ChannelList> c = channels.reader();
874
875         for (chan = c->begin(); chan != c->end(); ++chan) {
876                 (*chan)->playback_buf->increment_read_ptr (distance);
877         }
878
879         if (first_recordable_frame < max_framepos) {
880                 first_recordable_frame += distance;
881         }
882         playback_sample += distance;
883
884         return 0;
885 }
886
887 /** Read some data for 1 channel from our playlist into a buffer.
888  *  @param buf Buffer to write to.
889  *  @param start Session frame to start reading from; updated to where we end up
890  *         after the read.
891  *  @param cnt Count of samples to read.
892  *  @param reversed true if we are running backwards, otherwise false.
893  */
894 int
895 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
896                        framepos_t& start, framecnt_t cnt,
897                        int channel, bool reversed)
898 {
899         framecnt_t this_read = 0;
900         bool reloop = false;
901         framepos_t loop_end = 0;
902         framepos_t loop_start = 0;
903         framecnt_t offset = 0;
904         Location *loc = 0;
905
906         /* XXX we don't currently play loops in reverse. not sure why */
907
908         if (!reversed) {
909
910                 framecnt_t loop_length = 0;
911
912                 /* Make the use of a Location atomic for this read operation.
913
914                    Note: Locations don't get deleted, so all we care about
915                    when I say "atomic" is that we are always pointing to
916                    the same one and using a start/length values obtained
917                    just once.
918                 */
919
920                 if ((loc = loop_location) != 0) {
921                         loop_start = loc->start();
922                         loop_end = loc->end();
923                         loop_length = loop_end - loop_start;
924                 }
925
926                 /* if we are looping, ensure that the first frame we read is at the correct
927                    position within the loop.
928                 */
929
930                 if (loc && start >= loop_end) {
931                         start = loop_start + ((start - loop_start) % loop_length);
932                 }
933         }
934
935         if (reversed) {
936                 start -= cnt;
937         }
938
939         /* We need this while loop in case we hit a loop boundary, in which case our read from
940            the playlist must be split into more than one section.
941         */
942
943         while (cnt) {
944
945                 /* take any loop into account. we can't read past the end of the loop. */
946
947                 if (loc && (loop_end - start < cnt)) {
948                         this_read = loop_end - start;
949                         reloop = true;
950                 } else {
951                         reloop = false;
952                         this_read = cnt;
953                 }
954
955                 if (this_read == 0) {
956                         break;
957                 }
958
959                 this_read = min(cnt,this_read);
960
961                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
962                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
963                                          start) << endmsg;
964                         return -1;
965                 }
966
967                 if (reversed) {
968
969                         swap_by_ptr (buf, buf + this_read - 1);
970
971                 } else {
972
973                         /* if we read to the end of the loop, go back to the beginning */
974
975                         if (reloop) {
976                                 start = loop_start;
977                         } else {
978                                 start += this_read;
979                         }
980                 }
981
982                 cnt -= this_read;
983                 offset += this_read;
984         }
985
986         return 0;
987 }
988
989 int
990 AudioDiskstream::do_refill_with_alloc ()
991 {
992         Sample* mix_buf  = new Sample[disk_io_chunk_frames];
993         float*  gain_buf = new float[disk_io_chunk_frames];
994
995         int ret = _do_refill(mix_buf, gain_buf);
996
997         delete [] mix_buf;
998         delete [] gain_buf;
999
1000         return ret;
1001 }
1002
1003 /** Get some more data from disk and put it in our channels' playback_bufs,
1004  *  if there is suitable space in them.
1005  */
1006 int
1007 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1008 {
1009         int32_t ret = 0;
1010         framecnt_t to_read;
1011         RingBufferNPT<Sample>::rw_vector vector;
1012         bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1013         framecnt_t total_space;
1014         framecnt_t zero_fill;
1015         uint32_t chan_n;
1016         ChannelList::iterator i;
1017         boost::shared_ptr<ChannelList> c = channels.reader();
1018         framecnt_t ts;
1019
1020         if (c->empty()) {
1021                 return 0;
1022         }
1023
1024         assert(mixdown_buffer);
1025         assert(gain_buffer);
1026
1027         vector.buf[0] = 0;
1028         vector.len[0] = 0;
1029         vector.buf[1] = 0;
1030         vector.len[1] = 0;
1031
1032         c->front()->playback_buf->get_write_vector (&vector);
1033
1034         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1035                 /* nowhere to write to */
1036                 return 0;
1037         }
1038
1039         /* if there are 2+ chunks of disk i/o possible for
1040            this track, let the caller know so that it can arrange
1041            for us to be called again, ASAP.
1042         */
1043
1044         if (total_space >= (_slaved ? 3 : 2) * disk_io_chunk_frames) {
1045                 ret = 1;
1046         }
1047
1048         /* if we're running close to normal speed and there isn't enough
1049            space to do disk_io_chunk_frames of I/O, then don't bother.
1050
1051            at higher speeds, just do it because the sync between butler
1052            and audio thread may not be good enough.
1053
1054            Note: it is a design assumption that disk_io_chunk_frames is smaller
1055            than the playback buffer size, so this check should never trip when
1056            the playback buffer is empty.
1057         */
1058
1059         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1060                 return 0;
1061         }
1062
1063         /* when slaved, don't try to get too close to the read pointer. this
1064            leaves space for the buffer reversal to have something useful to
1065            work with.
1066         */
1067
1068         if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1069                 return 0;
1070         }
1071
1072         /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1073
1074         total_space = min (disk_io_chunk_frames, total_space);
1075
1076         if (reversed) {
1077
1078                 if (file_frame == 0) {
1079
1080                         /* at start: nothing to do but fill with silence */
1081
1082                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1083
1084                                 ChannelInfo* chan (*i);
1085                                 chan->playback_buf->get_write_vector (&vector);
1086                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1087                                 if (vector.len[1]) {
1088                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1089                                 }
1090                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1091                         }
1092                         return 0;
1093                 }
1094
1095                 if (file_frame < total_space) {
1096
1097                         /* too close to the start: read what we can,
1098                            and then zero fill the rest
1099                         */
1100
1101                         zero_fill = total_space - file_frame;
1102                         total_space = file_frame;
1103
1104                 } else {
1105
1106                         zero_fill = 0;
1107                 }
1108
1109         } else {
1110
1111                 if (file_frame == max_framepos) {
1112
1113                         /* at end: nothing to do but fill with silence */
1114
1115                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1116
1117                                 ChannelInfo* chan (*i);
1118                                 chan->playback_buf->get_write_vector (&vector);
1119                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1120                                 if (vector.len[1]) {
1121                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1122                                 }
1123                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1124                         }
1125                         return 0;
1126                 }
1127
1128                 if (file_frame > max_framepos - total_space) {
1129
1130                         /* to close to the end: read what we can, and zero fill the rest */
1131
1132                         zero_fill = total_space - (max_framepos - file_frame);
1133                         total_space = max_framepos - file_frame;
1134
1135                 } else {
1136                         zero_fill = 0;
1137                 }
1138         }
1139
1140         framepos_t file_frame_tmp = 0;
1141
1142         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1143
1144                 ChannelInfo* chan (*i);
1145                 Sample* buf1;
1146                 Sample* buf2;
1147                 framecnt_t len1, len2;
1148
1149                 chan->playback_buf->get_write_vector (&vector);
1150
1151                 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1152
1153                         /* we're not going to fill the first chunk, so certainly do not bother with the
1154                            other part. it won't be connected with the part we do fill, as in:
1155
1156                            .... => writable space
1157                            ++++ => readable space
1158                            ^^^^ => 1 x disk_io_chunk_frames that would be filled
1159
1160                            |......|+++++++++++++|...............................|
1161                            buf1                buf0
1162                                                 ^^^^^^^^^^^^^^^
1163
1164
1165                            So, just pretend that the buf1 part isn't there.
1166
1167                         */
1168
1169                         vector.buf[1] = 0;
1170                         vector.len[1] = 0;
1171
1172                 }
1173
1174                 ts = total_space;
1175                 file_frame_tmp = file_frame;
1176
1177                 buf1 = vector.buf[0];
1178                 len1 = vector.len[0];
1179                 buf2 = vector.buf[1];
1180                 len2 = vector.len[1];
1181
1182                 to_read = min (ts, len1);
1183                 to_read = min (to_read, disk_io_chunk_frames);
1184
1185                 assert (to_read >= 0);
1186
1187                 if (to_read) {
1188
1189                         if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1190                                 ret = -1;
1191                                 goto out;
1192                         }
1193
1194                         chan->playback_buf->increment_write_ptr (to_read);
1195                         ts -= to_read;
1196                 }
1197
1198                 to_read = min (ts, len2);
1199
1200                 if (to_read) {
1201
1202                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1203                            so read some or all of vector.len[1] as well.
1204                         */
1205
1206                         if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1207                                 ret = -1;
1208                                 goto out;
1209                         }
1210
1211                         chan->playback_buf->increment_write_ptr (to_read);
1212                 }
1213
1214                 if (zero_fill) {
1215                         /* XXX: do something */
1216                 }
1217
1218         }
1219
1220         file_frame = file_frame_tmp;
1221         assert (file_frame >= 0);
1222
1223   out:
1224
1225         return ret;
1226 }
1227
1228 /** Flush pending data to disk.
1229  *
1230  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1231  * of data to disk. it will never write more than that.  If it writes that
1232  * much and there is more than that waiting to be written, it will return 1,
1233  * otherwise 0 on success or -1 on failure.
1234  *
1235  * If there is less than disk_io_chunk_frames to be written, no data will be
1236  * written at all unless @a force_flush is true.
1237  */
1238 int
1239 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1240 {
1241         uint32_t to_write;
1242         int32_t ret = 0;
1243         RingBufferNPT<Sample>::rw_vector vector;
1244         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1245         framecnt_t total;
1246
1247         transvec.buf[0] = 0;
1248         transvec.buf[1] = 0;
1249         vector.buf[0] = 0;
1250         vector.buf[1] = 0;
1251
1252         boost::shared_ptr<ChannelList> c = channels.reader();
1253         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1254
1255                 (*chan)->capture_buf->get_read_vector (&vector);
1256
1257                 total = vector.len[0] + vector.len[1];
1258
1259                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1260                         goto out;
1261                 }
1262
1263                 /* if there are 2+ chunks of disk i/o possible for
1264                    this track, let the caller know so that it can arrange
1265                    for us to be called again, ASAP.
1266
1267                    if we are forcing a flush, then if there is* any* extra
1268                    work, let the caller know.
1269
1270                    if we are no longer recording and there is any extra work,
1271                    let the caller know too.
1272                 */
1273
1274                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1275                         ret = 1;
1276                 }
1277
1278                 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1279
1280                 // check the transition buffer when recording destructive
1281                 // important that we get this after the capture buf
1282
1283                 if (destructive()) {
1284                         (*chan)->capture_transition_buf->get_read_vector(&transvec);
1285                         size_t transcount = transvec.len[0] + transvec.len[1];
1286                         size_t ti;
1287
1288                         for (ti=0; ti < transcount; ++ti) {
1289                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1290
1291                                 if (captrans.type == CaptureStart) {
1292                                         // by definition, the first data we got above represents the given capture pos
1293
1294                                         (*chan)->write_source->mark_capture_start (captrans.capture_val);
1295                                         (*chan)->curr_capture_cnt = 0;
1296
1297                                 } else if (captrans.type == CaptureEnd) {
1298
1299                                         // capture end, the capture_val represents total frames in capture
1300
1301                                         if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1302
1303                                                 // shorten to make the write a perfect fit
1304                                                 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1305
1306                                                 if (nto_write < to_write) {
1307                                                         ret = 1; // should we?
1308                                                 }
1309                                                 to_write = nto_write;
1310
1311                                                 (*chan)->write_source->mark_capture_end ();
1312
1313                                                 // increment past this transition, but go no further
1314                                                 ++ti;
1315                                                 break;
1316                                         }
1317                                         else {
1318                                                 // actually ends just beyond this chunk, so force more work
1319                                                 ret = 1;
1320                                                 break;
1321                                         }
1322                                 }
1323                         }
1324
1325                         if (ti > 0) {
1326                                 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1327                         }
1328                 }
1329
1330                 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1331                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1332                         return -1;
1333                 }
1334
1335                 (*chan)->capture_buf->increment_read_ptr (to_write);
1336                 (*chan)->curr_capture_cnt += to_write;
1337
1338                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1339
1340                         /* we wrote all of vector.len[0] but it wasn't an entire
1341                            disk_io_chunk_frames of data, so arrange for some part
1342                            of vector.len[1] to be flushed to disk as well.
1343                         */
1344
1345                         to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1346
1347                         if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1348                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1349                                 return -1;
1350                         }
1351
1352                         (*chan)->capture_buf->increment_read_ptr (to_write);
1353                         (*chan)->curr_capture_cnt += to_write;
1354                 }
1355         }
1356
1357   out:
1358         return ret;
1359 }
1360
1361 void
1362 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1363 {
1364         uint32_t buffer_position;
1365         bool more_work = true;
1366         int err = 0;
1367         boost::shared_ptr<AudioRegion> region;
1368         framecnt_t total_capture;
1369         SourceList srcs;
1370         SourceList::iterator src;
1371         ChannelList::iterator chan;
1372         vector<CaptureInfo*>::iterator ci;
1373         boost::shared_ptr<ChannelList> c = channels.reader();
1374         uint32_t n = 0;
1375         bool mark_write_completed = false;
1376
1377         finish_capture (c);
1378
1379         /* butler is already stopped, but there may be work to do
1380            to flush remaining data to disk.
1381         */
1382
1383         while (more_work && !err) {
1384                 switch (do_flush (TransportContext, true)) {
1385                 case 0:
1386                         more_work = false;
1387                         break;
1388                 case 1:
1389                         break;
1390                 case -1:
1391                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1392                         err++;
1393                 }
1394         }
1395
1396         /* XXX is there anything we can do if err != 0 ? */
1397         Glib::Mutex::Lock lm (capture_info_lock);
1398
1399         if (capture_info.empty()) {
1400                 return;
1401         }
1402
1403         if (abort_capture) {
1404
1405                 if (destructive()) {
1406                         goto outout;
1407                 }
1408
1409                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1410
1411                         if ((*chan)->write_source) {
1412
1413                                 (*chan)->write_source->mark_for_remove ();
1414                                 (*chan)->write_source->drop_references ();
1415                                 (*chan)->write_source.reset ();
1416                         }
1417
1418                         /* new source set up in "out" below */
1419                 }
1420
1421                 goto out;
1422         }
1423
1424         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1425                 total_capture += (*ci)->frames;
1426         }
1427
1428         /* figure out the name for this take */
1429
1430         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1431
1432                 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1433
1434                 if (s) {
1435                         srcs.push_back (s);
1436                         s->update_header (capture_info.front()->start, when, twhen);
1437                         s->set_captured_for (_name.val());
1438                         s->mark_immutable ();
1439
1440                         if (Config->get_auto_analyse_audio()) {
1441                                 Analyser::queue_source_for_analysis (s, true);
1442                         }
1443                 }
1444         }
1445
1446         /* destructive tracks have a single, never changing region */
1447
1448         if (destructive()) {
1449
1450                 /* send a signal that any UI can pick up to do the right thing. there is
1451                    a small problem here in that a UI may need the peak data to be ready
1452                    for the data that was recorded and this isn't interlocked with that
1453                    process. this problem is deferred to the UI.
1454                  */
1455
1456                 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1457
1458         } else {
1459
1460                 string whole_file_region_name;
1461                 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1462
1463                 /* Register a new region with the Session that
1464                    describes the entire source. Do this first
1465                    so that any sub-regions will obviously be
1466                    children of this one (later!)
1467                 */
1468
1469                 try {
1470                         PropertyList plist;
1471
1472                         plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1473                         plist.add (Properties::length, total_capture);
1474                         plist.add (Properties::name, whole_file_region_name);
1475                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1476                         rx->set_automatic (true);
1477                         rx->set_whole_file (true);
1478
1479                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1480                         region->special_set_position (capture_info.front()->start);
1481                 }
1482
1483
1484                 catch (failed_constructor& err) {
1485                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1486                         /* XXX what now? */
1487                 }
1488
1489                 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1490
1491                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1492
1493                 _playlist->clear_changes ();
1494                 _playlist->freeze ();
1495
1496                 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1497
1498                         string region_name;
1499
1500                         RegionFactory::region_name (region_name, whole_file_region_name, false);
1501
1502                         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1503                                                                               _name, (*ci)->start, (*ci)->frames, region_name));
1504
1505                         try {
1506
1507                                 PropertyList plist;
1508
1509                                 plist.add (Properties::start, buffer_position);
1510                                 plist.add (Properties::length, (*ci)->frames);
1511                                 plist.add (Properties::name, region_name);
1512
1513                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1514                                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1515                         }
1516
1517                         catch (failed_constructor& err) {
1518                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1519                                 continue; /* XXX is this OK? */
1520                         }
1521
1522                         i_am_the_modifier++;
1523
1524                         if (_playlist->explicit_relayering()) {
1525                                 /* We are in `explicit relayering' mode, so we must specify which layer this new region
1526                                    should end up on.  Put it at the top.
1527                                 */
1528                                 region->set_layer (_playlist->top_layer() + 1);
1529                                 region->set_pending_explicit_relayer (true);
1530                         }
1531
1532                         _playlist->add_region (region, (*ci)->start, 1, non_layered());
1533                         i_am_the_modifier--;
1534
1535                         buffer_position += (*ci)->frames;
1536                 }
1537
1538                 _playlist->thaw ();
1539                 _session.add_command (new StatefulDiffCommand (_playlist));
1540         }
1541
1542         mark_write_completed = true;
1543
1544   out:
1545         reset_write_sources (mark_write_completed);
1546
1547   outout:
1548
1549         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1550                 delete *ci;
1551         }
1552
1553         capture_info.clear ();
1554         capture_start_frame = 0;
1555 }
1556
1557 void
1558 AudioDiskstream::transport_looped (framepos_t transport_frame)
1559 {
1560         if (was_recording) {
1561                 // all we need to do is finish this capture, with modified capture length
1562                 boost::shared_ptr<ChannelList> c = channels.reader();
1563
1564                 // adjust the capture length knowing that the data will be recorded to disk
1565                 // only necessary after the first loop where we're recording
1566                 if (capture_info.size() == 0) {
1567                         capture_captured += _capture_offset;
1568
1569                         if (_alignment_style == ExistingMaterial) {
1570                                 capture_captured += _session.worst_output_latency();
1571                         } else {
1572                                 capture_captured += _roll_delay;
1573                         }
1574                 }
1575
1576                 finish_capture (c);
1577
1578                 // the next region will start recording via the normal mechanism
1579                 // we'll set the start position to the current transport pos
1580                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1581                 capture_start_frame = transport_frame;
1582                 first_recordable_frame = transport_frame; // mild lie
1583                 last_recordable_frame = max_framepos;
1584                 was_recording = true;
1585
1586                 if (recordable() && destructive()) {
1587                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1588
1589                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1590                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1591
1592                                 if (transvec.len[0] > 0) {
1593                                         transvec.buf[0]->type = CaptureStart;
1594                                         transvec.buf[0]->capture_val = capture_start_frame;
1595                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
1596                                 }
1597                                 else {
1598                                         // bad!
1599                                         fatal << X_("programming error: capture_transition_buf is full on rec loop!  inconceivable!")
1600                                               << endmsg;
1601                                 }
1602                         }
1603                 }
1604
1605         }
1606 }
1607
1608 void
1609 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1610 {
1611         was_recording = false;
1612         first_recordable_frame = max_framepos;
1613         last_recordable_frame = max_framepos;
1614
1615         if (capture_captured == 0) {
1616                 return;
1617         }
1618
1619         if (recordable() && destructive()) {
1620                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1621
1622                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1623                         (*chan)->capture_transition_buf->get_write_vector(&transvec);
1624
1625                         if (transvec.len[0] > 0) {
1626                                 transvec.buf[0]->type = CaptureEnd;
1627                                 transvec.buf[0]->capture_val = capture_captured;
1628                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
1629                         }
1630                         else {
1631                                 // bad!
1632                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1633                         }
1634                 }
1635         }
1636
1637
1638         CaptureInfo* ci = new CaptureInfo;
1639
1640         ci->start =  capture_start_frame;
1641         ci->frames = capture_captured;
1642
1643         /* XXX theoretical race condition here. Need atomic exchange ?
1644            However, the circumstances when this is called right
1645            now (either on record-disable or transport_stopped)
1646            mean that no actual race exists. I think ...
1647            We now have a capture_info_lock, but it is only to be used
1648            to synchronize in the transport_stop and the capture info
1649            accessors, so that invalidation will not occur (both non-realtime).
1650         */
1651
1652         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1653
1654         capture_info.push_back (ci);
1655         capture_captured = 0;
1656
1657         /* now we've finished a capture, reset first_recordable_frame for next time */
1658         first_recordable_frame = max_framepos;
1659 }
1660
1661 void
1662 AudioDiskstream::set_record_enabled (bool yn)
1663 {
1664         if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1665                 return;
1666         }
1667
1668         /* can't rec-enable in destructive mode if transport is before start */
1669
1670         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1671                 return;
1672         }
1673
1674         /* yes, i know that this not proof against race conditions, but its
1675            good enough. i think.
1676         */
1677
1678         if (record_enabled() != yn) {
1679                 if (yn) {
1680                         engage_record_enable ();
1681                 } else {
1682                         disengage_record_enable ();
1683                 }
1684         }
1685 }
1686
1687 void
1688 AudioDiskstream::engage_record_enable ()
1689 {
1690         bool rolling = _session.transport_speed() != 0.0f;
1691         boost::shared_ptr<ChannelList> c = channels.reader();
1692
1693         g_atomic_int_set (&_record_enabled, 1);
1694         capturing_sources.clear ();
1695
1696         if (Config->get_monitoring_model() == HardwareMonitoring) {
1697
1698                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1699                         (*chan)->source.ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1700                         capturing_sources.push_back ((*chan)->write_source);
1701                         (*chan)->write_source->mark_streaming_write_started ();
1702                 }
1703
1704         } else {
1705                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1706                         capturing_sources.push_back ((*chan)->write_source);
1707                         (*chan)->write_source->mark_streaming_write_started ();
1708                 }
1709         }
1710
1711         RecordEnableChanged (); /* EMIT SIGNAL */
1712 }
1713
1714 void
1715 AudioDiskstream::disengage_record_enable ()
1716 {
1717         g_atomic_int_set (&_record_enabled, 0);
1718         boost::shared_ptr<ChannelList> c = channels.reader();
1719         if (Config->get_monitoring_model() == HardwareMonitoring) {
1720                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1721                         (*chan)->source.ensure_monitor_input (false);
1722                 }
1723         }
1724         capturing_sources.clear ();
1725         RecordEnableChanged (); /* EMIT SIGNAL */
1726 }
1727
1728 XMLNode&
1729 AudioDiskstream::get_state ()
1730 {
1731         XMLNode& node (Diskstream::get_state());
1732         char buf[64] = "";
1733         LocaleGuard lg (X_("POSIX"));
1734
1735         boost::shared_ptr<ChannelList> c = channels.reader();
1736         snprintf (buf, sizeof(buf), "%zd", c->size());
1737         node.add_property ("channels", buf);
1738
1739         if (!capturing_sources.empty() && _session.get_record_enabled()) {
1740
1741                 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1742                 XMLNode* cs_grandchild;
1743
1744                 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1745                         cs_grandchild = new XMLNode (X_("file"));
1746                         cs_grandchild->add_property (X_("path"), (*i)->path());
1747                         cs_child->add_child_nocopy (*cs_grandchild);
1748                 }
1749
1750                 /* store the location where capture will start */
1751
1752                 Location* pi;
1753
1754                 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1755                         snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1756                 } else {
1757                         snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1758                 }
1759
1760                 cs_child->add_property (X_("at"), buf);
1761                 node.add_child_nocopy (*cs_child);
1762         }
1763
1764         return node;
1765 }
1766
1767 int
1768 AudioDiskstream::set_state (const XMLNode& node, int version)
1769 {
1770         const XMLProperty* prop;
1771         XMLNodeList nlist = node.children();
1772         XMLNodeIterator niter;
1773         uint32_t nchans = 1;
1774         XMLNode* capture_pending_node = 0;
1775         LocaleGuard lg (X_("POSIX"));
1776
1777         /* prevent write sources from being created */
1778
1779         in_set_state = true;
1780
1781         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1782                 if ((*niter)->name() == IO::state_node_name) {
1783                         deprecated_io_node = new XMLNode (**niter);
1784                 }
1785
1786                 if ((*niter)->name() == X_("CapturingSources")) {
1787                         capture_pending_node = *niter;
1788                 }
1789         }
1790
1791         if (Diskstream::set_state (node, version)) {
1792                 return -1;
1793         }
1794
1795         if ((prop = node.property ("channels")) != 0) {
1796                 nchans = atoi (prop->value().c_str());
1797         }
1798
1799         // create necessary extra channels
1800         // we are always constructed with one and we always need one
1801
1802         _n_channels.set(DataType::AUDIO, channels.reader()->size());
1803
1804         if (nchans > _n_channels.n_audio()) {
1805
1806                 add_channel (nchans - _n_channels.n_audio());
1807                 IO::PortCountChanged(_n_channels);
1808
1809         } else if (nchans < _n_channels.n_audio()) {
1810
1811                 remove_channel (_n_channels.n_audio() - nchans);
1812         }
1813
1814
1815
1816         if (!destructive() && capture_pending_node) {
1817                 /* destructive streams have one and only one source per channel,
1818                    and so they never end up in pending capture in any useful
1819                    sense.
1820                 */
1821                 use_pending_capture_data (*capture_pending_node);
1822         }
1823
1824         in_set_state = false;
1825
1826         /* make sure this is clear before we do anything else */
1827
1828         capturing_sources.clear ();
1829
1830         /* write sources are handled when we handle the input set
1831            up of the IO that owns this DS (::non_realtime_input_change())
1832         */
1833
1834         return 0;
1835 }
1836
1837 int
1838 AudioDiskstream::use_new_write_source (uint32_t n)
1839 {
1840         boost::shared_ptr<ChannelList> c = channels.reader();
1841
1842         if (!recordable()) {
1843                 return 1;
1844         }
1845
1846         if (n >= c->size()) {
1847                 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1848                 return -1;
1849         }
1850
1851         ChannelInfo* chan = (*c)[n];
1852
1853         try {
1854                 if ((chan->write_source = _session.create_audio_source_for_session (
1855                              n_channels().n_audio(), name(), n, destructive())) == 0) {
1856                         throw failed_constructor();
1857                 }
1858         }
1859
1860         catch (failed_constructor &err) {
1861                 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1862                 chan->write_source.reset ();
1863                 return -1;
1864         }
1865
1866         /* do not remove destructive files even if they are empty */
1867
1868         chan->write_source->set_allow_remove_if_empty (!destructive());
1869
1870         return 0;
1871 }
1872
1873 list<boost::shared_ptr<Source> >
1874 AudioDiskstream::steal_write_sources()
1875 {
1876         /* not possible to steal audio write sources */
1877         list<boost::shared_ptr<Source> > ret;
1878         return ret;
1879 }
1880
1881 void
1882 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1883 {
1884         ChannelList::iterator chan;
1885         boost::shared_ptr<ChannelList> c = channels.reader();
1886         uint32_t n;
1887
1888         if (!_session.writable() || !recordable()) {
1889                 return;
1890         }
1891
1892         capturing_sources.clear ();
1893
1894         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1895
1896                 if (!destructive()) {
1897
1898                         if ((*chan)->write_source) {
1899
1900                                 if (mark_write_complete) {
1901                                         (*chan)->write_source->mark_streaming_write_completed ();
1902                                         (*chan)->write_source->done_with_peakfile_writes ();
1903                                 }
1904
1905                                 if ((*chan)->write_source->removable()) {
1906                                         (*chan)->write_source->mark_for_remove ();
1907                                         (*chan)->write_source->drop_references ();
1908                                 }
1909
1910                                 (*chan)->write_source.reset ();
1911                         }
1912
1913                         use_new_write_source (n);
1914
1915                         if (record_enabled()) {
1916                                 capturing_sources.push_back ((*chan)->write_source);
1917                         }
1918
1919                 } else {
1920
1921                         if ((*chan)->write_source == 0) {
1922                                 use_new_write_source (n);
1923                         }
1924                 }
1925         }
1926
1927         if (destructive() && !c->empty ()) {
1928
1929                 /* we now have all our write sources set up, so create the
1930                    playlist's single region.
1931                 */
1932
1933                 if (_playlist->empty()) {
1934                         setup_destructive_playlist ();
1935                 }
1936         }
1937 }
1938
1939 void
1940 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1941 {
1942         if (_session.get_block_size() > speed_buffer_size) {
1943                 speed_buffer_size = _session.get_block_size();
1944                 boost::shared_ptr<ChannelList> c = channels.reader();
1945
1946                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1947                         if ((*chan)->speed_buffer)
1948                                 delete [] (*chan)->speed_buffer;
1949                         (*chan)->speed_buffer = new Sample[speed_buffer_size];
1950                 }
1951         }
1952         allocate_temporary_buffers ();
1953 }
1954
1955 void
1956 AudioDiskstream::allocate_temporary_buffers ()
1957 {
1958         /* make sure the wrap buffer is at least large enough to deal
1959            with the speeds up to 1.2, to allow for micro-variation
1960            when slaving to MTC, Timecode etc.
1961         */
1962
1963         double const sp = max (fabsf (_actual_speed), 1.2f);
1964         framecnt_t required_wrap_size = (framecnt_t) floor (_session.get_block_size() * sp) + 1;
1965
1966         if (required_wrap_size > wrap_buffer_size) {
1967
1968                 boost::shared_ptr<ChannelList> c = channels.reader();
1969
1970                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1971                         if ((*chan)->playback_wrap_buffer) {
1972                                 delete [] (*chan)->playback_wrap_buffer;
1973                         }
1974                         (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
1975                         if ((*chan)->capture_wrap_buffer) {
1976                                 delete [] (*chan)->capture_wrap_buffer;
1977                         }
1978                         (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
1979                 }
1980
1981                 wrap_buffer_size = required_wrap_size;
1982         }
1983 }
1984
1985 void
1986 AudioDiskstream::monitor_input (bool yn)
1987 {
1988         boost::shared_ptr<ChannelList> c = channels.reader();
1989
1990         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1991                 (*chan)->source.ensure_monitor_input (yn);
1992         }
1993 }
1994
1995 void
1996 AudioDiskstream::set_align_style_from_io ()
1997 {
1998         bool have_physical = false;
1999
2000         if (_alignment_choice != Automatic) {
2001                 return;
2002         }
2003
2004         if (_io == 0) {
2005                 return;
2006         }
2007
2008         get_input_sources ();
2009
2010         boost::shared_ptr<ChannelList> c = channels.reader();
2011
2012         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2013                 if ((*chan)->source.is_physical ()) {
2014                         have_physical = true;
2015                         break;
2016                 }
2017         }
2018
2019         if (have_physical) {
2020                 set_align_style (ExistingMaterial);
2021         } else {
2022                 set_align_style (CaptureTime);
2023         }
2024 }
2025
2026 int
2027 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2028 {
2029         while (how_many--) {
2030                 c->push_back (new ChannelInfo(
2031                                       _session.butler()->audio_diskstream_playback_buffer_size(),
2032                                       _session.butler()->audio_diskstream_capture_buffer_size(),
2033                                       speed_buffer_size, wrap_buffer_size));
2034                 interpolation.add_channel_to (
2035                         _session.butler()->audio_diskstream_playback_buffer_size(),
2036                         speed_buffer_size);
2037         }
2038
2039         _n_channels.set(DataType::AUDIO, c->size());
2040
2041         return 0;
2042 }
2043
2044 int
2045 AudioDiskstream::add_channel (uint32_t how_many)
2046 {
2047         RCUWriter<ChannelList> writer (channels);
2048         boost::shared_ptr<ChannelList> c = writer.get_copy();
2049
2050         return add_channel_to (c, how_many);
2051 }
2052
2053 int
2054 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2055 {
2056         while (how_many-- && !c->empty()) {
2057                 delete c->back();
2058                 c->pop_back();
2059                 interpolation.remove_channel_from ();
2060         }
2061
2062         _n_channels.set(DataType::AUDIO, c->size());
2063
2064         return 0;
2065 }
2066
2067 int
2068 AudioDiskstream::remove_channel (uint32_t how_many)
2069 {
2070         RCUWriter<ChannelList> writer (channels);
2071         boost::shared_ptr<ChannelList> c = writer.get_copy();
2072
2073         return remove_channel_from (c, how_many);
2074 }
2075
2076 float
2077 AudioDiskstream::playback_buffer_load () const
2078 {
2079         boost::shared_ptr<ChannelList> c = channels.reader();
2080
2081         if (c->empty ()) {
2082                 return 0;
2083         }
2084
2085         return (float) ((double) c->front()->playback_buf->read_space()/
2086                         (double) c->front()->playback_buf->bufsize());
2087 }
2088
2089 float
2090 AudioDiskstream::capture_buffer_load () const
2091 {
2092         boost::shared_ptr<ChannelList> c = channels.reader();
2093
2094         if (c->empty ()) {
2095                 return 0;
2096         }
2097
2098         return (float) ((double) c->front()->capture_buf->write_space()/
2099                         (double) c->front()->capture_buf->bufsize());
2100 }
2101
2102 int
2103 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2104 {
2105         const XMLProperty* prop;
2106         XMLNodeList nlist = node.children();
2107         XMLNodeIterator niter;
2108         boost::shared_ptr<AudioFileSource> fs;
2109         boost::shared_ptr<AudioFileSource> first_fs;
2110         SourceList pending_sources;
2111         framepos_t position;
2112
2113         if ((prop = node.property (X_("at"))) == 0) {
2114                 return -1;
2115         }
2116
2117         if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2118                 return -1;
2119         }
2120
2121         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2122                 if ((*niter)->name() == X_("file")) {
2123
2124                         if ((prop = (*niter)->property (X_("path"))) == 0) {
2125                                 continue;
2126                         }
2127
2128                         // This protects sessions from errant CapturingSources in stored sessions
2129                         struct stat sbuf;
2130                         if (stat (prop->value().c_str(), &sbuf)) {
2131                                 continue;
2132                         }
2133
2134                         try {
2135                                 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2136                                         SourceFactory::createWritable (
2137                                                 DataType::AUDIO, _session,
2138                                                 prop->value(), string(), false, _session.frame_rate()));
2139                         }
2140
2141                         catch (failed_constructor& err) {
2142                                 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2143                                                   _name, prop->value())
2144                                       << endmsg;
2145                                 return -1;
2146                         }
2147
2148                         pending_sources.push_back (fs);
2149
2150                         if (first_fs == 0) {
2151                                 first_fs = fs;
2152                         }
2153
2154                         fs->set_captured_for (_name.val());
2155                 }
2156         }
2157
2158         if (pending_sources.size() == 0) {
2159                 /* nothing can be done */
2160                 return 1;
2161         }
2162
2163         if (pending_sources.size() != _n_channels.n_audio()) {
2164                 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2165                       << endmsg;
2166                 return -1;
2167         }
2168
2169         boost::shared_ptr<AudioRegion> region;
2170
2171         try {
2172
2173                 PropertyList plist;
2174
2175                 plist.add (Properties::start, 0);
2176                 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2177                 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2178
2179                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2180
2181                 region->set_automatic (true);
2182                 region->set_whole_file (true);
2183                 region->special_set_position (0);
2184         }
2185
2186         catch (failed_constructor& err) {
2187                 error << string_compose (
2188                                 _("%1: cannot create whole-file region from pending capture sources"),
2189                                 _name) << endmsg;
2190
2191                 return -1;
2192         }
2193
2194         _playlist->add_region (region, position);
2195
2196         return 0;
2197 }
2198
2199 int
2200 AudioDiskstream::set_non_layered (bool yn)
2201 {
2202         if (yn != non_layered()) {
2203
2204                 if (yn) {
2205                         _flags = Flag (_flags | NonLayered);
2206                 } else {
2207                         _flags = Flag (_flags & ~NonLayered);
2208                 }
2209         }
2210
2211         return 0;
2212 }
2213
2214 int
2215 AudioDiskstream::set_destructive (bool yn)
2216 {
2217         if (yn != destructive()) {
2218
2219                 if (yn) {
2220                         bool bounce_ignored;
2221                         /* requestor should already have checked this and
2222                            bounced if necessary and desired
2223                         */
2224                         if (!can_become_destructive (bounce_ignored)) {
2225                                 return -1;
2226                         }
2227                         _flags = Flag (_flags | Destructive);
2228                         use_destructive_playlist ();
2229                 } else {
2230                         _flags = Flag (_flags & ~Destructive);
2231                         reset_write_sources (true, true);
2232                 }
2233         }
2234
2235         return 0;
2236 }
2237
2238 bool
2239 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2240 {
2241         if (!_playlist) {
2242                 requires_bounce = false;
2243                 return false;
2244         }
2245
2246         /* is there only one region ? */
2247
2248         if (_playlist->n_regions() != 1) {
2249                 requires_bounce = true;
2250                 return false;
2251         }
2252
2253         boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2254         if (!first) {
2255                 requires_bounce = false;
2256                 return true;
2257         }
2258
2259         /* do the source(s) for the region cover the session start position ? */
2260
2261         if (first->position() != _session.current_start_frame()) {
2262                 if (first->start() > _session.current_start_frame()) {
2263                         requires_bounce = true;
2264                         return false;
2265                 }
2266         }
2267
2268         /* is the source used by only 1 playlist ? */
2269
2270         boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2271
2272         assert (afirst);
2273
2274         if (_session.playlists->source_use_count (afirst->source()) > 1) {
2275                 requires_bounce = true;
2276                 return false;
2277         }
2278
2279         requires_bounce = false;
2280         return true;
2281 }
2282
2283 void
2284 AudioDiskstream::adjust_playback_buffering ()
2285 {
2286         boost::shared_ptr<ChannelList> c = channels.reader();
2287
2288         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2289                 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2290         }
2291 }
2292
2293 void
2294 AudioDiskstream::adjust_capture_buffering ()
2295 {
2296         boost::shared_ptr<ChannelList> c = channels.reader();
2297
2298         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2299                 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2300         }
2301 }
2302
2303 bool
2304 AudioDiskstream::ChannelSource::is_physical () const
2305 {
2306         if (name.empty()) {
2307                 return false;
2308         }
2309
2310         return AudioEngine::instance()->port_is_physical (name);
2311 }
2312
2313 void
2314 AudioDiskstream::ChannelSource::ensure_monitor_input (bool yn) const
2315 {
2316         if (name.empty()) {
2317                 return;
2318         }
2319
2320         return AudioEngine::instance()->ensure_monitor_input (name, yn);
2321 }
2322
2323 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2324 {
2325         current_capture_buffer = 0;
2326         current_playback_buffer = 0;
2327         curr_capture_cnt = 0;
2328
2329         speed_buffer = new Sample[speed_size];
2330         playback_wrap_buffer = new Sample[wrap_size];
2331         capture_wrap_buffer = new Sample[wrap_size];
2332
2333         playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2334         capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2335         capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2336
2337         /* touch the ringbuffer buffers, which will cause
2338            them to be mapped into locked physical RAM if
2339            we're running with mlockall(). this doesn't do
2340            much if we're not.
2341         */
2342
2343         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2344         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2345         memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2346 }
2347
2348 void
2349 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2350 {
2351         delete playback_buf;
2352         playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2353         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2354 }
2355
2356 void
2357 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2358 {
2359         delete capture_buf;
2360
2361         capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2362         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2363 }
2364
2365 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2366 {
2367         write_source.reset ();
2368
2369         delete [] speed_buffer;
2370         speed_buffer = 0;
2371
2372         delete [] playback_wrap_buffer;
2373         playback_wrap_buffer = 0;
2374
2375         delete [] capture_wrap_buffer;
2376         capture_wrap_buffer = 0;
2377
2378         delete playback_buf;
2379         playback_buf = 0;
2380
2381         delete capture_buf;
2382         capture_buf = 0;
2383
2384         delete capture_transition_buf;
2385         capture_transition_buf = 0;
2386 }
2387
2388
2389 bool
2390 AudioDiskstream::set_name (string const & name)
2391 {
2392         Diskstream::set_name (name);
2393
2394         /* get a new write source so that its name reflects the new diskstream name */
2395
2396         boost::shared_ptr<ChannelList> c = channels.reader();
2397         ChannelList::iterator i;
2398         int n = 0;
2399
2400         for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2401                 use_new_write_source (n);
2402         }
2403
2404         return true;
2405 }