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