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