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