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