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