Take commit() out of process() in both types of
[ardour.git] / libs / ardour / audio_diskstream.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <fstream>
20 #include <cstdio>
21 #include <unistd.h>
22 #include <cmath>
23 #include <cerrno>
24 #include <cassert>
25 #include <string>
26 #include <climits>
27 #include <fcntl.h>
28 #include <cstdlib>
29 #include <ctime>
30 #include <sys/stat.h>
31 #include <sys/mman.h>
32
33 #include "pbd/error.h"
34 #include "pbd/xml++.h"
35 #include "pbd/memento_command.h"
36 #include "pbd/enumwriter.h"
37 #include "pbd/stateful_diff_command.h"
38
39 #include "ardour/analyser.h"
40 #include "ardour/ardour.h"
41 #include "ardour/audio_buffer.h"
42 #include "ardour/audio_diskstream.h"
43 #include "ardour/audio_port.h"
44 #include "ardour/audioengine.h"
45 #include "ardour/audiofilesource.h"
46
47 #include "ardour/audioplaylist.h"
48 #include "ardour/audioregion.h"
49 #include "ardour/butler.h"
50 #include "ardour/configuration.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/debug.h"
53 #include "ardour/io.h"
54 #include "ardour/playlist_factory.h"
55 #include "ardour/region_factory.h"
56 #include "ardour/send.h"
57 #include "ardour/session.h"
58 #include "ardour/source_factory.h"
59 #include "ardour/track.h"
60 #include "ardour/utils.h"
61 #include "ardour/session_playlists.h"
62 #include "ardour/route.h"
63
64 #include "i18n.h"
65 #include <locale.h>
66
67 using namespace std;
68 using namespace ARDOUR;
69 using namespace PBD;
70
71 size_t  AudioDiskstream::_working_buffers_size = 0;
72 Sample* AudioDiskstream::_mixdown_buffer       = 0;
73 gain_t* AudioDiskstream::_gain_buffer          = 0;
74
75 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
76         : Diskstream(sess, name, flag)
77         , channels (new ChannelList)
78 {
79         /* prevent any write sources from being created */
80
81         in_set_state = true;
82         use_new_playlist ();
83         in_set_state = false;
84 }
85
86 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
87         : Diskstream(sess, node)
88         , channels (new ChannelList)
89 {
90         in_set_state = true;
91         init ();
92
93         if (set_state (node, Stateful::loading_state_version)) {
94                 in_set_state = false;
95                 throw failed_constructor();
96         }
97
98         in_set_state = false;
99
100         if (destructive()) {
101                 use_destructive_playlist ();
102         }
103 }
104
105 void
106 AudioDiskstream::init ()
107 {
108         /* there are no channels at this point, so these
109            two calls just get speed_buffer_size and wrap_buffer
110            size setup without duplicating their code.
111         */
112
113         set_block_size (_session.get_block_size());
114         allocate_temporary_buffers ();
115 }
116
117 AudioDiskstream::~AudioDiskstream ()
118 {
119         DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
120
121         {
122                 RCUWriter<ChannelList> writer (channels);
123                 boost::shared_ptr<ChannelList> c = writer.get_copy();
124
125                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
126                         delete *chan;
127                 }
128
129                 c->clear();
130         }
131
132         channels.flush ();
133 }
134
135 void
136 AudioDiskstream::allocate_working_buffers()
137 {
138         assert(disk_io_frames() > 0);
139
140         _working_buffers_size = disk_io_frames();
141         _mixdown_buffer       = new Sample[_working_buffers_size];
142         _gain_buffer          = new gain_t[_working_buffers_size];
143 }
144
145 void
146 AudioDiskstream::free_working_buffers()
147 {
148         delete [] _mixdown_buffer;
149         delete [] _gain_buffer;
150         _working_buffers_size = 0;
151         _mixdown_buffer       = 0;
152         _gain_buffer          = 0;
153 }
154
155 void
156 AudioDiskstream::non_realtime_input_change ()
157 {
158         {
159                 Glib::Mutex::Lock lm (state_lock);
160
161                 if (input_change_pending.type == IOChange::NoChange) {
162                         return;
163                 }
164
165                 if (input_change_pending.type == IOChange::ConfigurationChanged) {
166                         RCUWriter<ChannelList> writer (channels);
167                         boost::shared_ptr<ChannelList> c = writer.get_copy();
168
169                         _n_channels.set(DataType::AUDIO, c->size());
170
171                         if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
172                                 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
173                         } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
174                                 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
175                         }
176                 }
177
178                 if (input_change_pending.type & IOChange::ConnectionsChanged) {
179                         get_input_sources ();
180                         set_capture_offset ();
181                         set_align_style_from_io ();
182                 }
183
184                 input_change_pending = IOChange::NoChange;
185
186                 /* implicit unlock */
187         }
188
189         /* reset capture files */
190
191         reset_write_sources (false);
192
193         /* now refill channel buffers */
194
195         if (speed() != 1.0f || speed() != -1.0f) {
196                 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
197         } else {
198                 seek (_session.transport_frame());
199         }
200 }
201
202 void
203 AudioDiskstream::non_realtime_locate (framepos_t location)
204 {
205         /* now refill channel buffers */
206
207         if (speed() != 1.0f || speed() != -1.0f) {
208                 seek ((framepos_t) (location * (double) speed()));
209         } else {
210                 seek (location);
211         }
212 }
213
214 void
215 AudioDiskstream::get_input_sources ()
216 {
217         boost::shared_ptr<ChannelList> c = channels.reader();
218
219         uint32_t n;
220         ChannelList::iterator chan;
221         uint32_t ni = _io->n_ports().n_audio();
222         vector<string> connections;
223
224         for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
225
226                 connections.clear ();
227
228                 if (_io->nth (n)->get_connections (connections) == 0) {
229                         if (!(*chan)->source.name.empty()) {
230                                 // _source->disable_metering ();
231                         }
232                         (*chan)->source.name = string();
233                 } else {
234                         (*chan)->source.name = connections[0];
235                 }
236         }
237 }
238
239 int
240 AudioDiskstream::find_and_use_playlist (const string& name)
241 {
242         boost::shared_ptr<AudioPlaylist> playlist;
243
244         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
245                 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
246         }
247
248         if (!playlist) {
249                 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
250                 return -1;
251         }
252
253         return use_playlist (playlist);
254 }
255
256 int
257 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
258 {
259         assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
260
261         Diskstream::use_playlist(playlist);
262
263         return 0;
264 }
265
266 int
267 AudioDiskstream::use_new_playlist ()
268 {
269         string newname;
270         boost::shared_ptr<AudioPlaylist> playlist;
271
272         if (!in_set_state && destructive()) {
273                 return 0;
274         }
275
276         if (_playlist) {
277                 newname = Playlist::bump_name (_playlist->name(), _session);
278         } else {
279                 newname = Playlist::bump_name (_name, _session);
280         }
281
282         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
283
284                 playlist->set_orig_diskstream_id (id());
285                 return use_playlist (playlist);
286
287         } else {
288                 return -1;
289         }
290 }
291
292 int
293 AudioDiskstream::use_copy_playlist ()
294 {
295         assert(audio_playlist());
296
297         if (destructive()) {
298                 return 0;
299         }
300
301         if (_playlist == 0) {
302                 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
303                 return -1;
304         }
305
306         string newname;
307         boost::shared_ptr<AudioPlaylist> playlist;
308
309         newname = Playlist::bump_name (_playlist->name(), _session);
310
311         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
312                 playlist->set_orig_diskstream_id (id());
313                 return use_playlist (playlist);
314         } else {
315                 return -1;
316         }
317 }
318
319 void
320 AudioDiskstream::setup_destructive_playlist ()
321 {
322         SourceList srcs;
323         boost::shared_ptr<ChannelList> c = channels.reader();
324
325         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
326                 srcs.push_back ((*chan)->write_source);
327         }
328
329         /* a single full-sized region */
330
331         assert (!srcs.empty ());
332
333         PropertyList plist;
334         plist.add (Properties::name, _name.val());
335         plist.add (Properties::start, 0);
336         plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
337
338         boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
339         _playlist->add_region (region, srcs.front()->natural_position());
340 }
341
342 void
343 AudioDiskstream::use_destructive_playlist ()
344 {
345         /* this is called from the XML-based constructor or ::set_destructive. when called,
346            we already have a playlist and a region, but we need to
347            set up our sources for write. we use the sources associated
348            with the (presumed single, full-extent) region.
349         */
350
351         boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
352
353         if (!rp) {
354                 reset_write_sources (false, true);
355                 return;
356         }
357
358         boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
359
360         if (region == 0) {
361                 throw failed_constructor();
362         }
363
364         /* be sure to stretch the region out to the maximum length */
365
366         region->set_length (max_framepos - region->position());
367
368         uint32_t n;
369         ChannelList::iterator chan;
370         boost::shared_ptr<ChannelList> c = channels.reader();
371
372         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
373                 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
374                 assert((*chan)->write_source);
375                 (*chan)->write_source->set_allow_remove_if_empty (false);
376
377                 /* this might be false if we switched modes, so force it */
378
379                 (*chan)->write_source->set_destructive (true);
380         }
381
382         /* the source list will never be reset for a destructive track */
383 }
384
385 void
386 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
387 {
388         if (recordable() && destructive()) {
389                 boost::shared_ptr<ChannelList> c = channels.reader();
390                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
391
392                         RingBufferNPT<CaptureTransition>::rw_vector transitions;
393                         (*chan)->capture_transition_buf->get_write_vector (&transitions);
394
395                         if (transitions.len[0] > 0) {
396                                 transitions.buf[0]->type = CaptureStart;
397                                 transitions.buf[0]->capture_val = capture_start_frame;
398                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
399                         } else {
400                                 // bad!
401                                 fatal << X_("programming error: capture_transition_buf is full on rec start!  inconceivable!")
402                                         << endmsg;
403                         }
404                 }
405         }
406 }
407
408
409 /** Do some record stuff [not described in this comment!]
410  *
411  *  Also:
412  *    - Setup playback_distance with the nframes, or nframes adjusted
413  *      for current varispeed, if appropriate.
414  *    - Setup current_playback_buffer in each ChannelInfo to point to data
415  *      that someone can read playback_distance worth of data from.
416  */
417 int
418 AudioDiskstream::process (framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance)
419 {
420         uint32_t n;
421         boost::shared_ptr<ChannelList> c = channels.reader();
422         ChannelList::iterator chan;
423         framecnt_t rec_offset = 0;
424         framecnt_t rec_nframes = 0;
425         bool collect_playback = false;
426         bool can_record = _session.actively_recording ();
427
428         playback_distance = 0;
429
430         if (!_io || !_io->active()) {
431                 return 0;
432         }
433
434         check_record_status (transport_frame, can_record);
435
436         if (nframes == 0) {
437                 return 0;
438         }
439
440         Glib::Mutex::Lock sm (state_lock, Glib::TRY_LOCK);
441
442         if (!sm.locked()) {
443                 return 1;
444         }
445
446         adjust_capture_position = 0;
447
448         for (chan = c->begin(); chan != c->end(); ++chan) {
449                 (*chan)->current_capture_buffer = 0;
450                 (*chan)->current_playback_buffer = 0;
451         }
452
453         // Safeguard against situations where process() goes haywire when autopunching
454         // and last_recordable_frame < first_recordable_frame
455
456         if (last_recordable_frame < first_recordable_frame) {
457                 last_recordable_frame = max_framepos;
458         }
459
460         if (record_enabled()) {
461
462                 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
463                 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
464
465                 if (rec_nframes && !was_recording) {
466                         capture_captured = 0;
467                         was_recording = true;
468                 }
469         }
470
471         if (can_record && !_last_capture_sources.empty()) {
472                 _last_capture_sources.clear ();
473         }
474
475         if (rec_nframes) {
476
477                 uint32_t limit = _io->n_ports ().n_audio();
478
479                 /* one or more ports could already have been removed from _io, but our
480                    channel setup hasn't yet been updated. prevent us from trying to
481                    use channels that correspond to missing ports. note that the
482                    process callback (from which this is called) is always atomic
483                    with respect to port removal/addition.
484                 */
485
486                 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
487
488                         ChannelInfo* chaninfo (*chan);
489
490                         chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
491
492                         if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
493
494                                 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
495
496                                 /* note: grab the entire port buffer, but only copy what we were supposed to
497                                    for recording, and use rec_offset
498                                 */
499
500                                 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
501                                 assert(ap);
502                                 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
503
504                                 Sample *buf = ap->get_audio_buffer (nframes).data (rec_offset);
505                                 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
506
507                         } else {
508
509                                 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
510
511                                 if (rec_nframes > total) {
512                                         DiskOverrun ();
513                                         return -1;
514                                 }
515
516                                 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
517                                 assert(ap);
518
519                                 Sample* buf = ap->get_audio_buffer(nframes).data (rec_offset);
520                                 framecnt_t first = chaninfo->capture_vector.len[0];
521
522                                 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
523                                 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
524                                 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
525                                 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
526
527                                 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
528                         }
529                 }
530
531         } else {
532
533                 if (was_recording) {
534                         finish_capture (c);
535                 }
536
537         }
538
539         if (rec_nframes) {
540
541                 /* data will be written to disk */
542
543                 if (rec_nframes == nframes && rec_offset == 0) {
544
545                         for (chan = c->begin(); chan != c->end(); ++chan) {
546                                 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
547                         }
548
549                         playback_distance = nframes;
550
551                 } else {
552
553
554                         /* we can't use the capture buffer as the playback buffer, because
555                            we recorded only a part of the current process' cycle data
556                            for capture.
557                         */
558
559                         collect_playback = true;
560                 }
561
562                 adjust_capture_position = rec_nframes;
563
564         } else if (can_record && record_enabled()) {
565
566                 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
567
568                 for (chan = c->begin(); chan != c->end(); ++chan) {
569                         (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
570                 }
571
572                 playback_distance = nframes;
573
574         } else {
575
576                 collect_playback = true;
577         }
578
579         if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
580                 
581                 /* we're doing playback */
582
583                 framecnt_t necessary_samples;
584
585                 /* no varispeed playback if we're recording, because the output .... TBD */
586
587                 if (rec_nframes == 0 && _actual_speed != 1.0f) {
588                         necessary_samples = (framecnt_t) floor ((nframes * fabs (_actual_speed))) + 1;
589                 } else {
590                         necessary_samples = nframes;
591                 }
592
593                 for (chan = c->begin(); chan != c->end(); ++chan) {
594                         (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
595                 }
596
597                 n = 0;
598
599                 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
600                    can read necessary_samples (== nframes at a transport speed of 1) worth of data
601                    from right now.
602                 */
603
604                 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
605
606                         ChannelInfo* chaninfo (*chan);
607
608                         if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
609                                 /* There are enough samples in the first part of the ringbuffer */
610                                 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
611
612                         } else {
613                                 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
614
615                                 if (necessary_samples > total) {
616                                         cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
617                                         cerr << "underrun for " << _name << endl;
618                                         DiskUnderrun ();
619                                         return -1;
620
621                                 } else {
622
623                                         /* We have enough samples, but not in one lump.  Coalesce the two parts
624                                            into one in playback_wrap_buffer in our ChannelInfo, and specify that
625                                            as our current_playback_buffer.
626                                         */
627
628                                         /* Copy buf[0] from playback_buf */
629                                         memcpy ((char *) chaninfo->playback_wrap_buffer,
630                                                         chaninfo->playback_vector.buf[0],
631                                                         chaninfo->playback_vector.len[0] * sizeof (Sample));
632                                         
633                                         /* Copy buf[1] from playback_buf */
634                                         memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
635                                                         chaninfo->playback_vector.buf[1],
636                                                         (necessary_samples - chaninfo->playback_vector.len[0])
637                                                                         * sizeof (Sample));
638
639                                         chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
640                                 }
641                         }
642                 }
643
644                 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
645
646                         interpolation.set_speed (_target_speed);
647
648                         int channel = 0;
649                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
650                                 ChannelInfo* chaninfo (*chan);
651                                 
652                                 playback_distance = interpolation.interpolate (
653                                         channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
654                                 
655                                 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
656                         }
657                         
658                 } else {
659                         playback_distance = nframes;
660                 }
661
662                 _speed = _target_speed;
663         }
664
665         return 0;
666 }
667
668 /** Update various things including playback_sample, read pointer on each channel's playback_buf
669  *  and write pointer on each channel's capture_buf.  Also wout whether the butler is needed.
670  *  @return true if the butler is required.
671  */
672 bool
673 AudioDiskstream::commit (framecnt_t playback_distance)
674 {
675         bool need_butler = false;
676
677         if (!_io || !_io->active()) {
678                 return false;
679         }
680
681         if (_actual_speed < 0.0) {
682                 playback_sample -= playback_distance;
683         } else {
684                 playback_sample += playback_distance;
685         }
686
687         boost::shared_ptr<ChannelList> c = channels.reader();
688         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
689
690                 (*chan)->playback_buf->increment_read_ptr (playback_distance);
691
692                 if (adjust_capture_position) {
693                         (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
694                 }
695         }
696
697         if (adjust_capture_position != 0) {
698                 capture_captured += adjust_capture_position;
699                 adjust_capture_position = 0;
700         }
701
702         if (c->empty()) {
703                 return false;
704         }
705
706         if (_slaved) {
707                 if (_io && _io->active()) {
708                         need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
709                 } else {
710                         need_butler = false;
711                 }
712         } else {
713                 if (_io && _io->active()) {
714                         need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
715                                 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
716                 } else {
717                         need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
718                 }
719         }
720
721         return need_butler;
722 }
723
724 void
725 AudioDiskstream::set_pending_overwrite (bool yn)
726 {
727         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
728
729         _pending_overwrite = yn;
730
731         overwrite_frame = playback_sample;
732
733         boost::shared_ptr<ChannelList> c = channels.reader ();
734         if (!c->empty ()) {
735                 overwrite_offset = c->front()->playback_buf->get_read_ptr();
736         }
737 }
738
739 int
740 AudioDiskstream::overwrite_existing_buffers ()
741 {
742         boost::shared_ptr<ChannelList> c = channels.reader();
743         if (c->empty ()) {
744                 _pending_overwrite = false;
745                 return 0;
746         }
747
748         Sample* mixdown_buffer;
749         float* gain_buffer;
750         int ret = -1;
751         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
752
753         overwrite_queued = false;
754
755         /* assume all are the same size */
756         framecnt_t size = c->front()->playback_buf->bufsize();
757
758         mixdown_buffer = new Sample[size];
759         gain_buffer = new float[size];
760
761         /* reduce size so that we can fill the buffer correctly (ringbuffers
762            can only handle size-1, otherwise they appear to be empty)
763         */
764         size--;
765
766         uint32_t n=0;
767         framepos_t start;
768
769         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
770
771                 start = overwrite_frame;
772                 framecnt_t cnt = size;
773
774                 /* to fill the buffer without resetting the playback sample, we need to
775                    do it one or two chunks (normally two).
776
777                    |----------------------------------------------------------------------|
778
779                                        ^
780                                        overwrite_offset
781                     |<- second chunk->||<----------------- first chunk ------------------>|
782
783                 */
784
785                 framecnt_t to_read = size - overwrite_offset;
786
787                 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
788                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
789                                                 id(), size, playback_sample) << endmsg;
790                         goto out;
791                 }
792
793                 if (cnt > to_read) {
794
795                         cnt -= to_read;
796
797                         if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
798                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
799                                                         id(), size, playback_sample) << endmsg;
800                                 goto out;
801                         }
802                 }
803         }
804
805         ret = 0;
806
807   out:
808         _pending_overwrite = false;
809         delete [] gain_buffer;
810         delete [] mixdown_buffer;
811         return ret;
812 }
813
814 int
815 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
816 {
817         uint32_t n;
818         int ret = -1;
819         ChannelList::iterator chan;
820         boost::shared_ptr<ChannelList> c = channels.reader();
821
822         Glib::Mutex::Lock lm (state_lock);
823
824         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
825                 (*chan)->playback_buf->reset ();
826                 (*chan)->capture_buf->reset ();
827         }
828
829         /* can't rec-enable in destructive mode if transport is before start */
830
831         if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
832                 disengage_record_enable ();
833         }
834
835         playback_sample = frame;
836         file_frame = frame;
837
838         if (complete_refill) {
839                 while ((ret = do_refill_with_alloc ()) > 0) ;
840         } else {
841                 ret = do_refill_with_alloc ();
842         }
843
844         return ret;
845 }
846
847 int
848 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
849 {
850         ChannelList::iterator chan;
851         boost::shared_ptr<ChannelList> c = channels.reader();
852
853         for (chan = c->begin(); chan != c->end(); ++chan) {
854                 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
855                         return false;
856                 }
857         }
858         return true;
859 }
860
861 int
862 AudioDiskstream::internal_playback_seek (framecnt_t distance)
863 {
864         ChannelList::iterator chan;
865         boost::shared_ptr<ChannelList> c = channels.reader();
866
867         for (chan = c->begin(); chan != c->end(); ++chan) {
868                 (*chan)->playback_buf->increment_read_ptr (distance);
869         }
870
871         if (first_recordable_frame < max_framepos) {
872                 first_recordable_frame += distance;
873         }
874         playback_sample += distance;
875
876         return 0;
877 }
878
879 /** Read some data for 1 channel from our playlist into a buffer.
880  *  @param buf Buffer to write to.
881  *  @param start Session frame to start reading from; updated to where we end up
882  *         after the read.
883  *  @param cnt Count of samples to read.
884  *  @param reversed true if we are running backwards, otherwise false.
885  */
886 int
887 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
888                        framepos_t& start, framecnt_t cnt,
889                        int channel, bool reversed)
890 {
891         framecnt_t this_read = 0;
892         bool reloop = false;
893         framepos_t loop_end = 0;
894         framepos_t loop_start = 0;
895         framecnt_t offset = 0;
896         Location *loc = 0;
897
898         /* XXX we don't currently play loops in reverse. not sure why */
899
900         if (!reversed) {
901
902                 framecnt_t loop_length = 0;
903
904                 /* Make the use of a Location atomic for this read operation.
905
906                    Note: Locations don't get deleted, so all we care about
907                    when I say "atomic" is that we are always pointing to
908                    the same one and using a start/length values obtained
909                    just once.
910                 */
911
912                 if ((loc = loop_location) != 0) {
913                         loop_start = loc->start();
914                         loop_end = loc->end();
915                         loop_length = loop_end - loop_start;
916                 }
917
918                 /* if we are looping, ensure that the first frame we read is at the correct
919                    position within the loop.
920                 */
921
922                 if (loc && start >= loop_end) {
923                         start = loop_start + ((start - loop_start) % loop_length);
924                 }
925         }
926
927         if (reversed) {
928                 start -= cnt;
929         }
930
931         /* We need this while loop in case we hit a loop boundary, in which case our read from
932            the playlist must be split into more than one section.
933         */
934
935         while (cnt) {
936
937                 /* take any loop into account. we can't read past the end of the loop. */
938
939                 if (loc && (loop_end - start < cnt)) {
940                         this_read = loop_end - start;
941                         reloop = true;
942                 } else {
943                         reloop = false;
944                         this_read = cnt;
945                 }
946
947                 if (this_read == 0) {
948                         break;
949                 }
950
951                 this_read = min(cnt,this_read);
952
953                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
954                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
955                                          start) << endmsg;
956                         return -1;
957                 }
958
959                 if (reversed) {
960
961                         swap_by_ptr (buf, buf + this_read - 1);
962
963                 } else {
964
965                         /* if we read to the end of the loop, go back to the beginning */
966
967                         if (reloop) {
968                                 start = loop_start;
969                         } else {
970                                 start += this_read;
971                         }
972                 }
973
974                 cnt -= this_read;
975                 offset += this_read;
976         }
977
978         return 0;
979 }
980
981 int
982 AudioDiskstream::do_refill_with_alloc ()
983 {
984         Sample* mix_buf  = new Sample[disk_io_chunk_frames];
985         float*  gain_buf = new float[disk_io_chunk_frames];
986
987         int ret = _do_refill(mix_buf, gain_buf);
988
989         delete [] mix_buf;
990         delete [] gain_buf;
991
992         return ret;
993 }
994
995 /** Get some more data from disk and put it in our channels' playback_bufs,
996  *  if there is suitable space in them.
997  */
998 int
999 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1000 {
1001         int32_t ret = 0;
1002         framecnt_t to_read;
1003         RingBufferNPT<Sample>::rw_vector vector;
1004         bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1005         framecnt_t total_space;
1006         framecnt_t zero_fill;
1007         uint32_t chan_n;
1008         ChannelList::iterator i;
1009         boost::shared_ptr<ChannelList> c = channels.reader();
1010         framecnt_t ts;
1011
1012         if (c->empty()) {
1013                 return 0;
1014         }
1015
1016         assert(mixdown_buffer);
1017         assert(gain_buffer);
1018
1019         vector.buf[0] = 0;
1020         vector.len[0] = 0;
1021         vector.buf[1] = 0;
1022         vector.len[1] = 0;
1023
1024         c->front()->playback_buf->get_write_vector (&vector);
1025
1026         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1027                 /* nowhere to write to */
1028                 return 0;
1029         }
1030
1031         /* if there are 2+ chunks of disk i/o possible for
1032            this track, let the caller know so that it can arrange
1033            for us to be called again, ASAP.
1034         */
1035
1036         if (total_space >= (_slaved ? 3 : 2) * disk_io_chunk_frames) {
1037                 ret = 1;
1038         }
1039
1040         /* if we're running close to normal speed and there isn't enough
1041            space to do disk_io_chunk_frames of I/O, then don't bother.
1042
1043            at higher speeds, just do it because the sync between butler
1044            and audio thread may not be good enough.
1045
1046            Note: it is a design assumption that disk_io_chunk_frames is smaller
1047            than the playback buffer size, so this check should never trip when
1048            the playback buffer is empty.
1049         */
1050
1051         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1052                 return 0;
1053         }
1054
1055         /* when slaved, don't try to get too close to the read pointer. this
1056            leaves space for the buffer reversal to have something useful to
1057            work with.
1058         */
1059
1060         if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1061                 return 0;
1062         }
1063
1064         /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1065
1066         total_space = min (disk_io_chunk_frames, total_space);
1067
1068         if (reversed) {
1069
1070                 if (file_frame == 0) {
1071
1072                         /* at start: nothing to do but fill with silence */
1073
1074                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1075
1076                                 ChannelInfo* chan (*i);
1077                                 chan->playback_buf->get_write_vector (&vector);
1078                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1079                                 if (vector.len[1]) {
1080                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1081                                 }
1082                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1083                         }
1084                         return 0;
1085                 }
1086
1087                 if (file_frame < total_space) {
1088
1089                         /* too close to the start: read what we can,
1090                            and then zero fill the rest
1091                         */
1092
1093                         zero_fill = total_space - file_frame;
1094                         total_space = file_frame;
1095
1096                 } else {
1097
1098                         zero_fill = 0;
1099                 }
1100
1101         } else {
1102
1103                 if (file_frame == max_framepos) {
1104
1105                         /* at end: nothing to do but fill with silence */
1106
1107                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1108
1109                                 ChannelInfo* chan (*i);
1110                                 chan->playback_buf->get_write_vector (&vector);
1111                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1112                                 if (vector.len[1]) {
1113                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1114                                 }
1115                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1116                         }
1117                         return 0;
1118                 }
1119
1120                 if (file_frame > max_framepos - total_space) {
1121
1122                         /* to close to the end: read what we can, and zero fill the rest */
1123
1124                         zero_fill = total_space - (max_framepos - file_frame);
1125                         total_space = max_framepos - file_frame;
1126
1127                 } else {
1128                         zero_fill = 0;
1129                 }
1130         }
1131
1132         framepos_t file_frame_tmp = 0;
1133
1134         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1135
1136                 ChannelInfo* chan (*i);
1137                 Sample* buf1;
1138                 Sample* buf2;
1139                 framecnt_t len1, len2;
1140
1141                 chan->playback_buf->get_write_vector (&vector);
1142
1143                 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1144
1145                         /* we're not going to fill the first chunk, so certainly do not bother with the
1146                            other part. it won't be connected with the part we do fill, as in:
1147
1148                            .... => writable space
1149                            ++++ => readable space
1150                            ^^^^ => 1 x disk_io_chunk_frames that would be filled
1151
1152                            |......|+++++++++++++|...............................|
1153                            buf1                buf0
1154                                                 ^^^^^^^^^^^^^^^
1155
1156
1157                            So, just pretend that the buf1 part isn't there.
1158
1159                         */
1160
1161                         vector.buf[1] = 0;
1162                         vector.len[1] = 0;
1163
1164                 }
1165
1166                 ts = total_space;
1167                 file_frame_tmp = file_frame;
1168
1169                 buf1 = vector.buf[0];
1170                 len1 = vector.len[0];
1171                 buf2 = vector.buf[1];
1172                 len2 = vector.len[1];
1173
1174                 to_read = min (ts, len1);
1175                 to_read = min (to_read, disk_io_chunk_frames);
1176
1177                 assert (to_read >= 0);
1178
1179                 if (to_read) {
1180
1181                         if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1182                                 ret = -1;
1183                                 goto out;
1184                         }
1185
1186                         chan->playback_buf->increment_write_ptr (to_read);
1187                         ts -= to_read;
1188                 }
1189
1190                 to_read = min (ts, len2);
1191
1192                 if (to_read) {
1193
1194                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1195                            so read some or all of vector.len[1] as well.
1196                         */
1197
1198                         if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1199                                 ret = -1;
1200                                 goto out;
1201                         }
1202
1203                         chan->playback_buf->increment_write_ptr (to_read);
1204                 }
1205
1206                 if (zero_fill) {
1207                         /* XXX: do something */
1208                 }
1209
1210         }
1211
1212         file_frame = file_frame_tmp;
1213         assert (file_frame >= 0);
1214
1215   out:
1216
1217         return ret;
1218 }
1219
1220 /** Flush pending data to disk.
1221  *
1222  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1223  * of data to disk. it will never write more than that.  If it writes that
1224  * much and there is more than that waiting to be written, it will return 1,
1225  * otherwise 0 on success or -1 on failure.
1226  *
1227  * If there is less than disk_io_chunk_frames to be written, no data will be
1228  * written at all unless @a force_flush is true.
1229  */
1230 int
1231 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1232 {
1233         uint32_t to_write;
1234         int32_t ret = 0;
1235         RingBufferNPT<Sample>::rw_vector vector;
1236         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1237         framecnt_t total;
1238
1239         transvec.buf[0] = 0;
1240         transvec.buf[1] = 0;
1241         vector.buf[0] = 0;
1242         vector.buf[1] = 0;
1243
1244         boost::shared_ptr<ChannelList> c = channels.reader();
1245         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1246
1247                 (*chan)->capture_buf->get_read_vector (&vector);
1248
1249                 total = vector.len[0] + vector.len[1];
1250
1251                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1252                         goto out;
1253                 }
1254
1255                 /* if there are 2+ chunks of disk i/o possible for
1256                    this track, let the caller know so that it can arrange
1257                    for us to be called again, ASAP.
1258
1259                    if we are forcing a flush, then if there is* any* extra
1260                    work, let the caller know.
1261
1262                    if we are no longer recording and there is any extra work,
1263                    let the caller know too.
1264                 */
1265
1266                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1267                         ret = 1;
1268                 }
1269
1270                 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1271
1272                 // check the transition buffer when recording destructive
1273                 // important that we get this after the capture buf
1274
1275                 if (destructive()) {
1276                         (*chan)->capture_transition_buf->get_read_vector(&transvec);
1277                         size_t transcount = transvec.len[0] + transvec.len[1];
1278                         size_t ti;
1279
1280                         for (ti=0; ti < transcount; ++ti) {
1281                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1282
1283                                 if (captrans.type == CaptureStart) {
1284                                         // by definition, the first data we got above represents the given capture pos
1285
1286                                         (*chan)->write_source->mark_capture_start (captrans.capture_val);
1287                                         (*chan)->curr_capture_cnt = 0;
1288
1289                                 } else if (captrans.type == CaptureEnd) {
1290
1291                                         // capture end, the capture_val represents total frames in capture
1292
1293                                         if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1294
1295                                                 // shorten to make the write a perfect fit
1296                                                 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1297
1298                                                 if (nto_write < to_write) {
1299                                                         ret = 1; // should we?
1300                                                 }
1301                                                 to_write = nto_write;
1302
1303                                                 (*chan)->write_source->mark_capture_end ();
1304
1305                                                 // increment past this transition, but go no further
1306                                                 ++ti;
1307                                                 break;
1308                                         }
1309                                         else {
1310                                                 // actually ends just beyond this chunk, so force more work
1311                                                 ret = 1;
1312                                                 break;
1313                                         }
1314                                 }
1315                         }
1316
1317                         if (ti > 0) {
1318                                 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1319                         }
1320                 }
1321
1322                 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1323                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1324                         return -1;
1325                 }
1326
1327                 (*chan)->capture_buf->increment_read_ptr (to_write);
1328                 (*chan)->curr_capture_cnt += to_write;
1329
1330                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1331
1332                         /* we wrote all of vector.len[0] but it wasn't an entire
1333                            disk_io_chunk_frames of data, so arrange for some part
1334                            of vector.len[1] to be flushed to disk as well.
1335                         */
1336
1337                         to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1338
1339                         if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1340                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1341                                 return -1;
1342                         }
1343
1344                         (*chan)->capture_buf->increment_read_ptr (to_write);
1345                         (*chan)->curr_capture_cnt += to_write;
1346                 }
1347         }
1348
1349   out:
1350         return ret;
1351 }
1352
1353 void
1354 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1355 {
1356         uint32_t buffer_position;
1357         bool more_work = true;
1358         int err = 0;
1359         boost::shared_ptr<AudioRegion> region;
1360         framecnt_t total_capture;
1361         SourceList srcs;
1362         SourceList::iterator src;
1363         ChannelList::iterator chan;
1364         vector<CaptureInfo*>::iterator ci;
1365         boost::shared_ptr<ChannelList> c = channels.reader();
1366         uint32_t n = 0;
1367         bool mark_write_completed = false;
1368
1369         finish_capture (c);
1370
1371         /* butler is already stopped, but there may be work to do
1372            to flush remaining data to disk.
1373         */
1374
1375         while (more_work && !err) {
1376                 switch (do_flush (TransportContext, true)) {
1377                 case 0:
1378                         more_work = false;
1379                         break;
1380                 case 1:
1381                         break;
1382                 case -1:
1383                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1384                         err++;
1385                 }
1386         }
1387
1388         /* XXX is there anything we can do if err != 0 ? */
1389         Glib::Mutex::Lock lm (capture_info_lock);
1390
1391         if (capture_info.empty()) {
1392                 return;
1393         }
1394
1395         if (abort_capture) {
1396
1397                 if (destructive()) {
1398                         goto outout;
1399                 }
1400
1401                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1402
1403                         if ((*chan)->write_source) {
1404
1405                                 (*chan)->write_source->mark_for_remove ();
1406                                 (*chan)->write_source->drop_references ();
1407                                 (*chan)->write_source.reset ();
1408                         }
1409
1410                         /* new source set up in "out" below */
1411                 }
1412
1413                 goto out;
1414         }
1415
1416         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1417                 total_capture += (*ci)->frames;
1418         }
1419
1420         /* figure out the name for this take */
1421
1422         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1423
1424                 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1425
1426                 if (s) {
1427                         srcs.push_back (s);
1428                         s->update_header (capture_info.front()->start, when, twhen);
1429                         s->set_captured_for (_name.val());
1430                         s->mark_immutable ();
1431
1432                         if (Config->get_auto_analyse_audio()) {
1433                                 Analyser::queue_source_for_analysis (s, true);
1434                         }
1435                 }
1436         }
1437
1438         /* destructive tracks have a single, never changing region */
1439
1440         if (destructive()) {
1441
1442                 /* send a signal that any UI can pick up to do the right thing. there is
1443                    a small problem here in that a UI may need the peak data to be ready
1444                    for the data that was recorded and this isn't interlocked with that
1445                    process. this problem is deferred to the UI.
1446                  */
1447
1448                 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1449
1450         } else {
1451
1452                 string whole_file_region_name;
1453                 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1454
1455                 /* Register a new region with the Session that
1456                    describes the entire source. Do this first
1457                    so that any sub-regions will obviously be
1458                    children of this one (later!)
1459                 */
1460
1461                 try {
1462                         PropertyList plist;
1463
1464                         plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1465                         plist.add (Properties::length, total_capture);
1466                         plist.add (Properties::name, whole_file_region_name);
1467                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1468                         rx->set_automatic (true);
1469                         rx->set_whole_file (true);
1470
1471                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1472                         region->special_set_position (capture_info.front()->start);
1473                 }
1474
1475
1476                 catch (failed_constructor& err) {
1477                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1478                         /* XXX what now? */
1479                 }
1480
1481                 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1482
1483                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1484
1485                 _playlist->clear_changes ();
1486                 _playlist->freeze ();
1487
1488                 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1489
1490                         string region_name;
1491
1492                         RegionFactory::region_name (region_name, whole_file_region_name, false);
1493
1494                         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1495                                                                               _name, (*ci)->start, (*ci)->frames, region_name));
1496
1497                         try {
1498
1499                                 PropertyList plist;
1500
1501                                 plist.add (Properties::start, buffer_position);
1502                                 plist.add (Properties::length, (*ci)->frames);
1503                                 plist.add (Properties::name, region_name);
1504
1505                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1506                                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1507                         }
1508
1509                         catch (failed_constructor& err) {
1510                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1511                                 continue; /* XXX is this OK? */
1512                         }
1513
1514                         i_am_the_modifier++;
1515
1516                         if (_playlist->explicit_relayering()) {
1517                                 /* We are in `explicit relayering' mode, so we must specify which layer this new region
1518                                    should end up on.  Put it at the top.
1519                                 */
1520                                 region->set_layer (_playlist->top_layer() + 1);
1521                                 region->set_pending_explicit_relayer (true);
1522                         }
1523
1524                         _playlist->add_region (region, (*ci)->start, 1, non_layered());
1525                         i_am_the_modifier--;
1526
1527                         buffer_position += (*ci)->frames;
1528                 }
1529
1530                 _playlist->thaw ();
1531                 _session.add_command (new StatefulDiffCommand (_playlist));
1532         }
1533
1534         mark_write_completed = true;
1535
1536   out:
1537         reset_write_sources (mark_write_completed);
1538
1539   outout:
1540
1541         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1542                 delete *ci;
1543         }
1544
1545         capture_info.clear ();
1546         capture_start_frame = 0;
1547 }
1548
1549 void
1550 AudioDiskstream::transport_looped (framepos_t transport_frame)
1551 {
1552         if (was_recording) {
1553                 // all we need to do is finish this capture, with modified capture length
1554                 boost::shared_ptr<ChannelList> c = channels.reader();
1555
1556                 // adjust the capture length knowing that the data will be recorded to disk
1557                 // only necessary after the first loop where we're recording
1558                 if (capture_info.size() == 0) {
1559                         capture_captured += _capture_offset;
1560
1561                         if (_alignment_style == ExistingMaterial) {
1562                                 capture_captured += _session.worst_output_latency();
1563                         } else {
1564                                 capture_captured += _roll_delay;
1565                         }
1566                 }
1567
1568                 finish_capture (c);
1569
1570                 // the next region will start recording via the normal mechanism
1571                 // we'll set the start position to the current transport pos
1572                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1573                 capture_start_frame = transport_frame;
1574                 first_recordable_frame = transport_frame; // mild lie
1575                 last_recordable_frame = max_framepos;
1576                 was_recording = true;
1577
1578                 if (recordable() && destructive()) {
1579                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1580
1581                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1582                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1583
1584                                 if (transvec.len[0] > 0) {
1585                                         transvec.buf[0]->type = CaptureStart;
1586                                         transvec.buf[0]->capture_val = capture_start_frame;
1587                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
1588                                 }
1589                                 else {
1590                                         // bad!
1591                                         fatal << X_("programming error: capture_transition_buf is full on rec loop!  inconceivable!")
1592                                               << endmsg;
1593                                 }
1594                         }
1595                 }
1596
1597         }
1598 }
1599
1600 void
1601 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1602 {
1603         was_recording = false;
1604         first_recordable_frame = max_framepos;
1605         last_recordable_frame = max_framepos;
1606
1607         if (capture_captured == 0) {
1608                 return;
1609         }
1610
1611         if (recordable() && destructive()) {
1612                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1613
1614                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1615                         (*chan)->capture_transition_buf->get_write_vector(&transvec);
1616
1617                         if (transvec.len[0] > 0) {
1618                                 transvec.buf[0]->type = CaptureEnd;
1619                                 transvec.buf[0]->capture_val = capture_captured;
1620                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
1621                         }
1622                         else {
1623                                 // bad!
1624                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1625                         }
1626                 }
1627         }
1628
1629
1630         CaptureInfo* ci = new CaptureInfo;
1631
1632         ci->start =  capture_start_frame;
1633         ci->frames = capture_captured;
1634
1635         /* XXX theoretical race condition here. Need atomic exchange ?
1636            However, the circumstances when this is called right
1637            now (either on record-disable or transport_stopped)
1638            mean that no actual race exists. I think ...
1639            We now have a capture_info_lock, but it is only to be used
1640            to synchronize in the transport_stop and the capture info
1641            accessors, so that invalidation will not occur (both non-realtime).
1642         */
1643
1644         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1645
1646         capture_info.push_back (ci);
1647         capture_captured = 0;
1648
1649         /* now we've finished a capture, reset first_recordable_frame for next time */
1650         first_recordable_frame = max_framepos;
1651 }
1652
1653 void
1654 AudioDiskstream::set_record_enabled (bool yn)
1655 {
1656         if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1657                 return;
1658         }
1659
1660         /* can't rec-enable in destructive mode if transport is before start */
1661
1662         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1663                 return;
1664         }
1665
1666         /* yes, i know that this not proof against race conditions, but its
1667            good enough. i think.
1668         */
1669
1670         if (record_enabled() != yn) {
1671                 if (yn) {
1672                         engage_record_enable ();
1673                 } else {
1674                         disengage_record_enable ();
1675                 }
1676         }
1677 }
1678
1679 void
1680 AudioDiskstream::engage_record_enable ()
1681 {
1682         bool rolling = _session.transport_speed() != 0.0f;
1683         boost::shared_ptr<ChannelList> c = channels.reader();
1684
1685         g_atomic_int_set (&_record_enabled, 1);
1686         capturing_sources.clear ();
1687
1688         if (Config->get_monitoring_model() == HardwareMonitoring) {
1689
1690                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1691                         (*chan)->source.ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1692                         capturing_sources.push_back ((*chan)->write_source);
1693                         (*chan)->write_source->mark_streaming_write_started ();
1694                 }
1695
1696         } else {
1697                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1698                         capturing_sources.push_back ((*chan)->write_source);
1699                         (*chan)->write_source->mark_streaming_write_started ();
1700                 }
1701         }
1702
1703         RecordEnableChanged (); /* EMIT SIGNAL */
1704 }
1705
1706 void
1707 AudioDiskstream::disengage_record_enable ()
1708 {
1709         g_atomic_int_set (&_record_enabled, 0);
1710         boost::shared_ptr<ChannelList> c = channels.reader();
1711         if (Config->get_monitoring_model() == HardwareMonitoring) {
1712                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1713                         (*chan)->source.ensure_monitor_input (false);
1714                 }
1715         }
1716         capturing_sources.clear ();
1717         RecordEnableChanged (); /* EMIT SIGNAL */
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::monitor_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.ensure_monitor_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::ensure_monitor_input (bool yn) const
2307 {
2308         if (name.empty()) {
2309                 return;
2310         }
2311
2312         return AudioEngine::instance()->ensure_monitor_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 }