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