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