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