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