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