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