allow to set custom file name for each diststream
[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), "%u", (unsigned int) 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(), write_source_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 void
1930 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1931 {
1932         ChannelList::iterator chan;
1933         boost::shared_ptr<ChannelList> c = channels.reader();
1934         uint32_t n;
1935
1936         if (!_session.writable() || !recordable()) {
1937                 return;
1938         }
1939
1940         capturing_sources.clear ();
1941
1942         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1943
1944                 if (!destructive()) {
1945
1946                         if ((*chan)->write_source) {
1947
1948                                 if (mark_write_complete) {
1949                                         (*chan)->write_source->mark_streaming_write_completed ();
1950                                         (*chan)->write_source->done_with_peakfile_writes ();
1951                                 }
1952
1953                                 if ((*chan)->write_source->removable()) {
1954                                         (*chan)->write_source->mark_for_remove ();
1955                                         (*chan)->write_source->drop_references ();
1956                                 }
1957
1958                                 (*chan)->write_source.reset ();
1959                         }
1960
1961                         use_new_write_source (n);
1962
1963                         if (record_enabled()) {
1964                                 capturing_sources.push_back ((*chan)->write_source);
1965                         }
1966
1967                 } else {
1968
1969                         if ((*chan)->write_source == 0) {
1970                                 use_new_write_source (n);
1971                         }
1972                 }
1973         }
1974
1975         if (destructive() && !c->empty ()) {
1976
1977                 /* we now have all our write sources set up, so create the
1978                    playlist's single region.
1979                 */
1980
1981                 if (_playlist->empty()) {
1982                         setup_destructive_playlist ();
1983                 }
1984         }
1985 }
1986
1987 void
1988 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1989 {
1990         if (_session.get_block_size() > speed_buffer_size) {
1991                 speed_buffer_size = _session.get_block_size();
1992                 boost::shared_ptr<ChannelList> c = channels.reader();
1993
1994                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1995                         if ((*chan)->speed_buffer)
1996                                 delete [] (*chan)->speed_buffer;
1997                         (*chan)->speed_buffer = new Sample[speed_buffer_size];
1998                 }
1999         }
2000         allocate_temporary_buffers ();
2001 }
2002
2003 void
2004 AudioDiskstream::allocate_temporary_buffers ()
2005 {
2006         /* make sure the wrap buffer is at least large enough to deal
2007            with the speeds up to 1.2, to allow for micro-variation
2008            when slaving to MTC, Timecode etc.
2009         */
2010
2011         double const sp = max (fabsf (_actual_speed), 1.2f);
2012         framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2013
2014         if (required_wrap_size > wrap_buffer_size) {
2015
2016                 boost::shared_ptr<ChannelList> c = channels.reader();
2017
2018                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2019                         if ((*chan)->playback_wrap_buffer) {
2020                                 delete [] (*chan)->playback_wrap_buffer;
2021                         }
2022                         (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2023                         if ((*chan)->capture_wrap_buffer) {
2024                                 delete [] (*chan)->capture_wrap_buffer;
2025                         }
2026                         (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2027                 }
2028
2029                 wrap_buffer_size = required_wrap_size;
2030         }
2031 }
2032
2033 void
2034 AudioDiskstream::request_input_monitoring (bool yn)
2035 {
2036         boost::shared_ptr<ChannelList> c = channels.reader();
2037
2038         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2039                 (*chan)->source.request_input_monitoring (yn);
2040         }
2041 }
2042
2043 void
2044 AudioDiskstream::set_align_style_from_io ()
2045 {
2046         bool have_physical = false;
2047
2048         if (_alignment_choice != Automatic) {
2049                 return;
2050         }
2051
2052         if (_io == 0) {
2053                 return;
2054         }
2055
2056         get_input_sources ();
2057
2058         boost::shared_ptr<ChannelList> c = channels.reader();
2059
2060         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2061                 if ((*chan)->source.is_physical ()) {
2062                         have_physical = true;
2063                         break;
2064                 }
2065         }
2066
2067         if (have_physical) {
2068                 set_align_style (ExistingMaterial);
2069         } else {
2070                 set_align_style (CaptureTime);
2071         }
2072 }
2073
2074 int
2075 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2076 {
2077         while (how_many--) {
2078                 c->push_back (new ChannelInfo(
2079                                       _session.butler()->audio_diskstream_playback_buffer_size(),
2080                                       _session.butler()->audio_diskstream_capture_buffer_size(),
2081                                       speed_buffer_size, wrap_buffer_size));
2082                 interpolation.add_channel_to (
2083                         _session.butler()->audio_diskstream_playback_buffer_size(),
2084                         speed_buffer_size);
2085         }
2086
2087         _n_channels.set(DataType::AUDIO, c->size());
2088
2089         return 0;
2090 }
2091
2092 int
2093 AudioDiskstream::add_channel (uint32_t how_many)
2094 {
2095         RCUWriter<ChannelList> writer (channels);
2096         boost::shared_ptr<ChannelList> c = writer.get_copy();
2097
2098         return add_channel_to (c, how_many);
2099 }
2100
2101 int
2102 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2103 {
2104         while (how_many-- && !c->empty()) {
2105                 delete c->back();
2106                 c->pop_back();
2107                 interpolation.remove_channel_from ();
2108         }
2109
2110         _n_channels.set(DataType::AUDIO, c->size());
2111
2112         return 0;
2113 }
2114
2115 int
2116 AudioDiskstream::remove_channel (uint32_t how_many)
2117 {
2118         RCUWriter<ChannelList> writer (channels);
2119         boost::shared_ptr<ChannelList> c = writer.get_copy();
2120
2121         return remove_channel_from (c, how_many);
2122 }
2123
2124 float
2125 AudioDiskstream::playback_buffer_load () const
2126 {
2127         boost::shared_ptr<ChannelList> c = channels.reader();
2128
2129         if (c->empty ()) {
2130                 return 0;
2131         }
2132
2133         return (float) ((double) c->front()->playback_buf->read_space()/
2134                         (double) c->front()->playback_buf->bufsize());
2135 }
2136
2137 float
2138 AudioDiskstream::capture_buffer_load () const
2139 {
2140         boost::shared_ptr<ChannelList> c = channels.reader();
2141
2142         if (c->empty ()) {
2143                 return 0;
2144         }
2145
2146         return (float) ((double) c->front()->capture_buf->write_space()/
2147                         (double) c->front()->capture_buf->bufsize());
2148 }
2149
2150 int
2151 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2152 {
2153         const XMLProperty* prop;
2154         XMLNodeList nlist = node.children();
2155         XMLNodeIterator niter;
2156         boost::shared_ptr<AudioFileSource> fs;
2157         boost::shared_ptr<AudioFileSource> first_fs;
2158         SourceList pending_sources;
2159         framepos_t position;
2160
2161         if ((prop = node.property (X_("at"))) == 0) {
2162                 return -1;
2163         }
2164
2165         if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2166                 return -1;
2167         }
2168
2169         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2170                 if ((*niter)->name() == X_("file")) {
2171
2172                         if ((prop = (*niter)->property (X_("path"))) == 0) {
2173                                 continue;
2174                         }
2175
2176                         // This protects sessions from errant CapturingSources in stored sessions
2177                         struct stat sbuf;
2178                         if (stat (prop->value().c_str(), &sbuf)) {
2179                                 continue;
2180                         }
2181
2182                         /* XXX as of June 2014, we always record to mono
2183                            files. Since this Source is being created as part of
2184                            crash recovery, we know that we need the first
2185                            channel (the final argument to the SourceFactory
2186                            call below). If we ever support non-mono files for
2187                            capture, this will need rethinking.
2188                         */
2189
2190                         try {
2191                                 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2192                         }
2193
2194                         catch (failed_constructor& err) {
2195                                 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2196                                                   _name, prop->value())
2197                                       << endmsg;
2198                                 return -1;
2199                         }
2200
2201                         pending_sources.push_back (fs);
2202
2203                         if (first_fs == 0) {
2204                                 first_fs = fs;
2205                         }
2206
2207                         fs->set_captured_for (_name.val());
2208                 }
2209         }
2210
2211         if (pending_sources.size() == 0) {
2212                 /* nothing can be done */
2213                 return 1;
2214         }
2215
2216         if (pending_sources.size() != _n_channels.n_audio()) {
2217                 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2218                       << endmsg;
2219                 return -1;
2220         }
2221
2222         try {
2223
2224                 boost::shared_ptr<AudioRegion> wf_region;
2225                 boost::shared_ptr<AudioRegion> region;
2226                 
2227                 /* First create the whole file region */
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                 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2236
2237                 wf_region->set_automatic (true);
2238                 wf_region->set_whole_file (true);
2239                 wf_region->special_set_position (position);
2240
2241                 /* Now create a region that isn't the whole file for adding to
2242                  * the playlist */
2243
2244                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2245                 
2246                 _playlist->add_region (region, position);
2247         }
2248
2249         catch (failed_constructor& err) {
2250                 error << string_compose (
2251                                 _("%1: cannot create whole-file region from pending capture sources"),
2252                                 _name) << endmsg;
2253
2254                 return -1;
2255         }
2256
2257
2258         return 0;
2259 }
2260
2261 int
2262 AudioDiskstream::set_non_layered (bool yn)
2263 {
2264         if (yn != non_layered()) {
2265
2266                 if (yn) {
2267                         _flags = Flag (_flags | NonLayered);
2268                 } else {
2269                         _flags = Flag (_flags & ~NonLayered);
2270                 }
2271         }
2272
2273         return 0;
2274 }
2275
2276 int
2277 AudioDiskstream::set_destructive (bool yn)
2278 {
2279         if (yn != destructive()) {
2280
2281                 if (yn) {
2282                         bool bounce_ignored;
2283                         /* requestor should already have checked this and
2284                            bounced if necessary and desired
2285                         */
2286                         if (!can_become_destructive (bounce_ignored)) {
2287                                 return -1;
2288                         }
2289                         _flags = Flag (_flags | Destructive);
2290                         use_destructive_playlist ();
2291                 } else {
2292                         _flags = Flag (_flags & ~Destructive);
2293                         reset_write_sources (true, true);
2294                 }
2295         }
2296
2297         return 0;
2298 }
2299
2300 bool
2301 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2302 {
2303         if (!_playlist) {
2304                 requires_bounce = false;
2305                 return false;
2306         }
2307
2308         /* is there only one region ? */
2309
2310         if (_playlist->n_regions() != 1) {
2311                 requires_bounce = true;
2312                 return false;
2313         }
2314
2315         boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2316         if (!first) {
2317                 requires_bounce = false;
2318                 return true;
2319         }
2320
2321         /* do the source(s) for the region cover the session start position ? */
2322
2323         if (first->position() != _session.current_start_frame()) {
2324                 if (first->start() > _session.current_start_frame()) {
2325                         requires_bounce = true;
2326                         return false;
2327                 }
2328         }
2329
2330         /* is the source used by only 1 playlist ? */
2331
2332         boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2333
2334         assert (afirst);
2335
2336         if (_session.playlists->source_use_count (afirst->source()) > 1) {
2337                 requires_bounce = true;
2338                 return false;
2339         }
2340
2341         requires_bounce = false;
2342         return true;
2343 }
2344
2345 void
2346 AudioDiskstream::adjust_playback_buffering ()
2347 {
2348         boost::shared_ptr<ChannelList> c = channels.reader();
2349
2350         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2351                 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2352         }
2353 }
2354
2355 void
2356 AudioDiskstream::adjust_capture_buffering ()
2357 {
2358         boost::shared_ptr<ChannelList> c = channels.reader();
2359
2360         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2361                 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2362         }
2363 }
2364
2365 bool
2366 AudioDiskstream::ChannelSource::is_physical () const
2367 {
2368         if (name.empty()) {
2369                 return false;
2370         }
2371
2372         return AudioEngine::instance()->port_is_physical (name);
2373 }
2374
2375 void
2376 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2377 {
2378         if (name.empty()) {
2379                 return;
2380         }
2381
2382         return AudioEngine::instance()->request_input_monitoring (name, yn);
2383 }
2384
2385 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2386 {
2387         current_capture_buffer = 0;
2388         current_playback_buffer = 0;
2389         curr_capture_cnt = 0;
2390
2391         speed_buffer = new Sample[speed_size];
2392         playback_wrap_buffer = new Sample[wrap_size];
2393         capture_wrap_buffer = new Sample[wrap_size];
2394
2395         playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2396         capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2397         capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2398
2399         /* touch the ringbuffer buffers, which will cause
2400            them to be mapped into locked physical RAM if
2401            we're running with mlockall(). this doesn't do
2402            much if we're not.
2403         */
2404
2405         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2406         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2407         memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2408 }
2409
2410 void
2411 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2412 {
2413         delete playback_buf;
2414         playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2415         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2416 }
2417
2418 void
2419 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2420 {
2421         delete capture_buf;
2422
2423         capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2424         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2425 }
2426
2427 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2428 {
2429         write_source.reset ();
2430
2431         delete [] speed_buffer;
2432         speed_buffer = 0;
2433
2434         delete [] playback_wrap_buffer;
2435         playback_wrap_buffer = 0;
2436
2437         delete [] capture_wrap_buffer;
2438         capture_wrap_buffer = 0;
2439
2440         delete playback_buf;
2441         playback_buf = 0;
2442
2443         delete capture_buf;
2444         capture_buf = 0;
2445
2446         delete capture_transition_buf;
2447         capture_transition_buf = 0;
2448 }
2449
2450
2451 bool
2452 AudioDiskstream::set_name (string const & name)
2453 {
2454         if (_name == name) {
2455                 return true;
2456         }
2457         Diskstream::set_name (name);
2458
2459         /* get a new write source so that its name reflects the new diskstream name */
2460
2461         boost::shared_ptr<ChannelList> c = channels.reader();
2462         ChannelList::iterator i;
2463         int n = 0;
2464
2465         for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2466                 use_new_write_source (n);
2467         }
2468
2469         return true;
2470 }
2471
2472 bool
2473 AudioDiskstream::set_write_source_name (const std::string& str) {
2474         if (_write_source_name == str) {
2475                 return true;
2476         }
2477
2478         Diskstream::set_write_source_name (str);
2479
2480         if (_write_source_name == name()) {
2481                 return true;
2482         }
2483         boost::shared_ptr<ChannelList> c = channels.reader();
2484         ChannelList::iterator i;
2485         int n = 0;
2486
2487         for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2488                 use_new_write_source (n);
2489         }
2490         return true;
2491 }