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