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