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