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