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