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