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