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