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