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