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