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