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