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