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