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