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