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