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