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