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