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