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