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