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