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