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