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