Remove Diskstream member playback_distance that can be
[ardour.git] / libs / ardour / diskstream.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <fstream>
21 #include <cassert>
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
35 #include <glibmm/thread.h>
36
37 #include "pbd/error.h"
38 #include "pbd/basename.h"
39 #include "pbd/memento_command.h"
40 #include "pbd/xml++.h"
41 #include "pbd/stacktrace.h"
42
43 #include "ardour/ardour.h"
44 #include "ardour/audioengine.h"
45 #include "ardour/debug.h"
46 #include "ardour/diskstream.h"
47 #include "ardour/utils.h"
48 #include "ardour/configuration.h"
49 #include "ardour/audiofilesource.h"
50 #include "ardour/send.h"
51 #include "ardour/pannable.h"
52 #include "ardour/panner_shell.h"
53 #include "ardour/playlist.h"
54 #include "ardour/cycle_timer.h"
55 #include "ardour/region.h"
56 #include "ardour/panner.h"
57 #include "ardour/session.h"
58 #include "ardour/io.h"
59 #include "ardour/track.h"
60
61 #include "i18n.h"
62 #include <locale.h>
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67
68 /* XXX This goes uninitialized when there is no ~/.config/ardour3 directory.
69  * I can't figure out why, so this will do for now (just stole the
70  * default from configuration_vars.h).  0 is not a good value for
71  * allocating buffer sizes..
72  */
73 ARDOUR::framecnt_t Diskstream::disk_io_chunk_frames = 1024 * 256 / sizeof (Sample);
74
75 PBD::Signal0<void>                Diskstream::DiskOverrun;
76 PBD::Signal0<void>                Diskstream::DiskUnderrun;
77
78 Diskstream::Diskstream (Session &sess, const string &name, Flag flag)
79         : SessionObject(sess, name)
80         , i_am_the_modifier (0)
81         , _track (0)
82         , _record_enabled (0)
83         , _visible_speed (1.0f)
84         , _actual_speed (1.0f)
85         , _buffer_reallocation_required (false)
86         , _seek_required (false)
87         , force_refill (false)
88         , capture_start_frame (0)
89         , capture_captured (0)
90         , was_recording (false)
91         , adjust_capture_position (0)
92         , _capture_offset (0)
93         , _roll_delay (0)
94         , first_recordable_frame (max_framepos)
95         , last_recordable_frame (max_framepos)
96         , last_possibly_recording (0)
97         , _alignment_style (ExistingMaterial)
98         , _alignment_choice (Automatic)
99         , _scrubbing (false)
100         , _slaved (false)
101         , loop_location (0)
102         , overwrite_frame (0)
103         , overwrite_offset (0)
104         , _pending_overwrite (false)
105         , overwrite_queued (false)
106         , wrap_buffer_size (0)
107         , speed_buffer_size (0)
108         , _speed (1.0)
109         , _target_speed (_speed)
110         , file_frame (0)
111         , playback_sample (0)
112         , in_set_state (false)
113         , _flags (flag)
114         , deprecated_io_node (0)
115 {
116 }
117
118 Diskstream::Diskstream (Session& sess, const XMLNode& /*node*/)
119         : SessionObject(sess, "unnamed diskstream")
120         , i_am_the_modifier (0)
121         , _track (0)
122         , _record_enabled (0)
123         , _visible_speed (1.0f)
124         , _actual_speed (1.0f)
125         , _buffer_reallocation_required (false)
126         , _seek_required (false)
127         , force_refill (false)
128         , capture_start_frame (0)
129         , capture_captured (0)
130         , was_recording (false)
131         , adjust_capture_position (0)
132         , _capture_offset (0)
133         , _roll_delay (0)
134         , first_recordable_frame (max_framepos)
135         , last_recordable_frame (max_framepos)
136         , last_possibly_recording (0)
137         , _alignment_style (ExistingMaterial)
138         , _alignment_choice (Automatic)
139         , _scrubbing (false)
140         , _slaved (false)
141         , loop_location (0)
142         , overwrite_frame (0)
143         , overwrite_offset (0)
144         , _pending_overwrite (false)
145         , overwrite_queued (false)
146         , wrap_buffer_size (0)
147         , speed_buffer_size (0)
148         , _speed (1.0)
149         , _target_speed (_speed)
150         , file_frame (0)
151         , playback_sample (0)
152         , in_set_state (false)
153         , _flags (Recordable)
154         , deprecated_io_node (0)
155 {
156 }
157
158 Diskstream::~Diskstream ()
159 {
160         DEBUG_TRACE (DEBUG::Destruction, string_compose ("Diskstream %1 deleted\n", _name));
161
162         if (_playlist) {
163                 _playlist->release ();
164         }
165
166         delete deprecated_io_node;
167 }
168
169 void
170 Diskstream::set_track (Track* t)
171 {
172         _track = t;
173         _io = _track->input();
174
175         ic_connection.disconnect();
176         _io->changed.connect_same_thread (ic_connection, boost::bind (&Diskstream::handle_input_change, this, _1, _2));
177
178         if (_io->n_ports() != ChanCount::ZERO) {
179                 input_change_pending.type = IOChange::Type (IOChange::ConfigurationChanged|IOChange::ConnectionsChanged);
180                 non_realtime_input_change ();
181         }
182
183         _track->Destroyed.connect_same_thread (*this, boost::bind (&Diskstream::route_going_away, this));
184 }
185
186 void
187 Diskstream::handle_input_change (IOChange change, void * /*src*/)
188 {
189         Glib::Mutex::Lock lm (state_lock);
190
191         if (change.type & (IOChange::ConfigurationChanged|IOChange::ConnectionsChanged)) {
192
193                 /* rather than handle this here on a DS-by-DS basis we defer to the
194                    session transport/butler thread, and let it tackle
195                    as many diskstreams as need it in one shot. this avoids many repeated
196                    takings of the audioengine process lock.
197                 */
198
199                 if (!(input_change_pending.type & change.type)) {
200                         input_change_pending.type = IOChange::Type (input_change_pending.type | change.type);
201                         _session.request_input_change_handling ();
202                 }
203         }
204 }
205
206 void
207 Diskstream::non_realtime_set_speed ()
208 {
209         if (_buffer_reallocation_required)
210         {
211                 Glib::Mutex::Lock lm (state_lock);
212                 allocate_temporary_buffers ();
213
214                 _buffer_reallocation_required = false;
215         }
216
217         if (_seek_required) {
218                 if (speed() != 1.0f || speed() != -1.0f) {
219                         seek ((framepos_t) (_session.transport_frame() * (double) speed()), true);
220                 }
221                 else {
222                         seek (_session.transport_frame(), true);
223                 }
224
225                 _seek_required = false;
226         }
227 }
228
229 bool
230 Diskstream::realtime_set_speed (double sp, bool global)
231 {
232         bool changed = false;
233         double new_speed = sp * _session.transport_speed();
234
235         if (_visible_speed != sp) {
236                 _visible_speed = sp;
237                 changed = true;
238         }
239
240         if (new_speed != _actual_speed) {
241
242                 framecnt_t required_wrap_size = (framecnt_t) floor (_session.get_block_size() *
243                                                                   fabs (new_speed)) + 1;
244
245                 if (required_wrap_size > wrap_buffer_size) {
246                         _buffer_reallocation_required = true;
247                 }
248
249                 _actual_speed = new_speed;
250                 _target_speed = fabs(_actual_speed);
251         }
252
253         if (changed) {
254                 if (!global) {
255                         _seek_required = true;
256                 }
257                 SpeedChanged (); /* EMIT SIGNAL */
258         }
259
260         return _buffer_reallocation_required || _seek_required;
261 }
262
263 void
264 Diskstream::set_capture_offset ()
265 {
266         if (_io == 0) {
267                 /* can't capture, so forget it */
268                 return;
269         }
270
271         _capture_offset = _io->latency();
272         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: using IO latency, capture offset set to %2\n", name(), _capture_offset));
273 }
274
275
276 void
277 Diskstream::set_align_style (AlignStyle a, bool force)
278 {
279         if (record_enabled() && _session.actively_recording()) {
280                 return;
281         }
282
283         if ((a != _alignment_style) || force) {
284                 _alignment_style = a;
285                 AlignmentStyleChanged ();
286         }
287 }
288
289 void
290 Diskstream::set_align_choice (AlignChoice a, bool force)
291 {
292         if (record_enabled() && _session.actively_recording()) {
293                 return;
294         }
295
296         if ((a != _alignment_choice) || force) {
297                 _alignment_choice = a;
298
299                 switch (_alignment_choice) {
300                 case Automatic:
301                         set_align_style_from_io ();
302                         break;
303                 case UseExistingMaterial:
304                         set_align_style (ExistingMaterial);
305                         break;
306                 case UseCaptureTime:
307                         set_align_style (CaptureTime);
308                         break;
309                 }
310         }
311 }
312
313 int
314 Diskstream::set_loop (Location *location)
315 {
316         if (location) {
317                 if (location->start() >= location->end()) {
318                         error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
319                         return -1;
320                 }
321         }
322
323         loop_location = location;
324
325         LoopSet (location); /* EMIT SIGNAL */
326         return 0;
327 }
328
329 /** Get the start position (in session frames) of the nth capture in the current pass */
330 ARDOUR::framepos_t
331 Diskstream::get_capture_start_frame (uint32_t n) const
332 {
333         Glib::Mutex::Lock lm (capture_info_lock);
334
335         if (capture_info.size() > n) {
336                 /* this is a completed capture */
337                 return capture_info[n]->start;
338         } else {
339                 /* this is the currently in-progress capture */
340                 return capture_start_frame;
341         }
342 }
343
344 ARDOUR::framecnt_t
345 Diskstream::get_captured_frames (uint32_t n) const
346 {
347         Glib::Mutex::Lock lm (capture_info_lock);
348
349         if (capture_info.size() > n) {
350                 /* this is a completed capture */
351                 return capture_info[n]->frames;
352         } else {
353                 /* this is the currently in-progress capture */
354                 return capture_captured;
355         }
356 }
357
358 void
359 Diskstream::set_roll_delay (ARDOUR::framecnt_t nframes)
360 {
361         _roll_delay = nframes;
362 }
363
364 int
365 Diskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
366 {
367         if (!playlist) {
368                 return 0;
369         }
370
371         bool prior_playlist = false;
372
373         {
374                 Glib::Mutex::Lock lm (state_lock);
375
376                 if (playlist == _playlist) {
377                         return 0;
378                 }
379
380                 playlist_connections.drop_connections ();
381
382                 if (_playlist) {
383                         _playlist->release();
384                         prior_playlist = true;
385                 }
386
387                 _playlist = playlist;
388                 _playlist->use();
389
390                 if (!in_set_state && recordable()) {
391                         reset_write_sources (false);
392                 }
393
394                 _playlist->ContentsChanged.connect_same_thread (playlist_connections, boost::bind (&Diskstream::playlist_modified, this));
395                 _playlist->DropReferences.connect_same_thread (playlist_connections, boost::bind (&Diskstream::playlist_deleted, this, boost::weak_ptr<Playlist>(_playlist)));
396                 _playlist->RangesMoved.connect_same_thread (playlist_connections, boost::bind (&Diskstream::playlist_ranges_moved, this, _1, _2));
397         }
398
399         /* don't do this if we've already asked for it *or* if we are setting up
400            the diskstream for the very first time - the input changed handling will
401            take care of the buffer refill.
402         */
403
404         if (!overwrite_queued && prior_playlist) {
405                 _session.request_overwrite_buffer (_track);
406                 overwrite_queued = true;
407         }
408
409         PlaylistChanged (); /* EMIT SIGNAL */
410         _session.set_dirty ();
411
412         return 0;
413 }
414
415 void
416 Diskstream::playlist_changed (const PropertyChange&)
417 {
418         playlist_modified ();
419 }
420
421 void
422 Diskstream::playlist_modified ()
423 {
424         if (!i_am_the_modifier && !overwrite_queued) {
425                 _session.request_overwrite_buffer (_track);
426                 overwrite_queued = true;
427         }
428 }
429
430 void
431 Diskstream::playlist_deleted (boost::weak_ptr<Playlist> wpl)
432 {
433         boost::shared_ptr<Playlist> pl (wpl.lock());
434
435         if (pl == _playlist) {
436
437                 /* this catches an ordering issue with session destruction. playlists
438                    are destroyed before diskstreams. we have to invalidate any handles
439                    we have to the playlist.
440                 */
441
442                 if (_playlist) {
443                         _playlist.reset ();
444                 }
445         }
446 }
447
448 bool
449 Diskstream::set_name (const string& str)
450 {
451         if (_name != str) {
452                 assert(playlist());
453                 playlist()->set_name (str);
454                 SessionObject::set_name(str);
455         }
456         return true;
457 }
458
459 XMLNode&
460 Diskstream::get_state ()
461 {
462         XMLNode* node = new XMLNode ("Diskstream");
463         char buf[64];
464         LocaleGuard lg (X_("POSIX"));
465
466         node->add_property ("flags", enum_2_string (_flags));
467         node->add_property ("playlist", _playlist->name());
468         node->add_property("name", _name);
469         id().print (buf, sizeof (buf));
470         node->add_property("id", buf);
471         snprintf (buf, sizeof(buf), "%f", _visible_speed);
472         node->add_property ("speed", buf);
473         node->add_property ("capture-alignment", enum_2_string (_alignment_choice));
474
475         if (_extra_xml) {
476                 node->add_child_copy (*_extra_xml);
477         }
478
479         return *node;
480 }
481
482 int
483 Diskstream::set_state (const XMLNode& node, int /*version*/)
484 {
485         const XMLProperty* prop;
486
487         if ((prop = node.property ("name")) != 0) {
488                 _name = prop->value();
489         }
490
491         if (deprecated_io_node) {
492                 set_id (*deprecated_io_node);
493         } else {
494                 set_id (node);
495         }
496
497         if ((prop = node.property ("flags")) != 0) {
498                 _flags = Flag (string_2_enum (prop->value(), _flags));
499         }
500
501         if ((prop = node.property (X_("capture-alignment"))) != 0) {
502                 set_align_choice (AlignChoice (string_2_enum (prop->value(), _alignment_choice)), true);
503         } else {
504                 set_align_choice (Automatic, true);
505         }
506
507         if ((prop = node.property ("playlist")) == 0) {
508                 return -1;
509         }
510
511         {
512                 bool had_playlist = (_playlist != 0);
513
514                 if (find_and_use_playlist (prop->value())) {
515                         return -1;
516                 }
517
518                 if (!had_playlist) {
519                         _playlist->set_orig_diskstream_id (id());
520                 }
521         }
522
523         if ((prop = node.property ("speed")) != 0) {
524                 double sp = atof (prop->value().c_str());
525
526                 if (realtime_set_speed (sp, false)) {
527                         non_realtime_set_speed ();
528                 }
529         }
530
531         return 0;
532 }
533
534 void
535 Diskstream::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
536 {
537         /* If we're coming from an undo, it will have handled
538            automation undo (it must, since automation-follows-regions
539            can lose automation data).  Hence we can do nothing here.
540         */
541
542         if (from_undo) {
543                 return;
544         }
545
546         if (!_track || Config->get_automation_follows_regions () == false) {
547                 return;
548         }
549
550         list< Evoral::RangeMove<double> > movements;
551
552         for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
553              i != movements_frames.end();
554              ++i) {
555
556                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
557         }
558
559         /* move panner automation */
560         boost::shared_ptr<Pannable> pannable = _track->pannable();
561         Evoral::ControlSet::Controls& c (pannable->controls());
562
563         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
564                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
565                 if (!ac) {
566                         continue;
567                 }
568                 boost::shared_ptr<AutomationList> alist = ac->alist();
569
570                 XMLNode & before = alist->get_state ();
571                 bool const things_moved = alist->move_ranges (movements);
572                 if (things_moved) {
573                         _session.add_command (new MementoCommand<AutomationList> (
574                                                       *alist.get(), &before, &alist->get_state ()));
575                 }
576         }
577
578         /* move processor automation */
579         _track->foreach_processor (boost::bind (&Diskstream::move_processor_automation, this, _1, movements_frames));
580 }
581
582 void
583 Diskstream::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
584 {
585         boost::shared_ptr<Processor> processor (p.lock ());
586         if (!processor) {
587                 return;
588         }
589
590         list< Evoral::RangeMove<double> > movements;
591         for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
592                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
593         }
594
595         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
596
597         for (set<Evoral::Parameter>::iterator i = a.begin (); i != a.end (); ++i) {
598                 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
599                 XMLNode & before = al->get_state ();
600                 bool const things_moved = al->move_ranges (movements);
601                 if (things_moved) {
602                         _session.add_command (
603                                 new MementoCommand<AutomationList> (
604                                         *al.get(), &before, &al->get_state ()
605                                         )
606                                 );
607                 }
608         }
609 }
610
611 void
612 Diskstream::check_record_status (framepos_t transport_frame, bool can_record)
613 {
614         int possibly_recording;
615         int rolling;
616         int change;
617         const int transport_rolling = 0x4;
618         const int track_rec_enabled = 0x2;
619         const int global_rec_enabled = 0x1;
620         const int fully_rec_enabled = (transport_rolling|track_rec_enabled|global_rec_enabled);
621
622         /* merge together the 3 factors that affect record status, and compute
623            what has changed.
624         */
625
626         rolling = _session.transport_speed() != 0.0f;
627         possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
628         change = possibly_recording ^ last_possibly_recording;
629
630         if (possibly_recording == last_possibly_recording) {
631                 return;
632         }
633
634         framecnt_t existing_material_offset = _session.worst_playback_latency();
635
636         if (possibly_recording == fully_rec_enabled) {
637
638                 if (last_possibly_recording == fully_rec_enabled) {
639                         return;
640                 }
641
642                 capture_start_frame = _session.transport_frame();
643                 first_recordable_frame = capture_start_frame + _capture_offset;
644                 last_recordable_frame = max_framepos;
645
646                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: @ %7 (%9) FRF = %2 CSF = %4 CO = %5, EMO = %6 RD = %8 WOL %10 WTL %11\n",
647                                                                       name(), first_recordable_frame, last_recordable_frame, capture_start_frame,
648                                                                       _capture_offset,
649                                                                       existing_material_offset,
650                                                                       transport_frame,
651                                                                       _roll_delay,
652                                                                       _session.transport_frame(),
653                                                                       _session.worst_output_latency(),
654                                                                       _session.worst_track_latency()));
655
656
657                 if (_alignment_style == ExistingMaterial) {
658                         first_recordable_frame += existing_material_offset;
659                         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("\tshift FRF by EMO %1\n",
660                                                                               first_recordable_frame));
661                 }
662
663                 prepare_record_status (capture_start_frame);
664
665         } else {
666
667                 if (last_possibly_recording == fully_rec_enabled) {
668
669                         /* we were recording last time */
670
671                         if (change & transport_rolling) {
672
673                                 /* transport-change (stopped rolling): last_recordable_frame was set in ::prepare_to_stop(). We
674                                    had to set it there because we likely rolled past the stopping point to declick out,
675                                    and then backed up.
676                                  */
677
678                         } else {
679                                 /* punch out */
680
681                                 last_recordable_frame = _session.transport_frame() + _capture_offset;
682
683                                 if (_alignment_style == ExistingMaterial) {
684                                         last_recordable_frame += existing_material_offset;
685                                 }
686                         }
687                 }
688         }
689
690         last_possibly_recording = possibly_recording;
691 }
692
693 void
694 Diskstream::route_going_away ()
695 {
696         _io.reset ();
697 }
698
699 void
700 Diskstream::calculate_record_range(OverlapType ot, framepos_t transport_frame, framecnt_t nframes,
701                                    framecnt_t & rec_nframes, framecnt_t & rec_offset)
702 {
703         switch (ot) {
704         case OverlapNone:
705                 rec_nframes = 0;
706                 break;
707
708         case OverlapInternal:
709                 /*     ----------    recrange
710                          |---|       transrange
711                 */
712                 rec_nframes = nframes;
713                 rec_offset = 0;
714                 break;
715
716         case OverlapStart:
717                 /*    |--------|    recrange
718                 -----|          transrange
719                 */
720                 rec_nframes = transport_frame + nframes - first_recordable_frame;
721                 if (rec_nframes) {
722                         rec_offset = first_recordable_frame - transport_frame;
723                 }
724                 break;
725
726         case OverlapEnd:
727                 /*    |--------|    recrange
728                          |--------  transrange
729                 */
730                 rec_nframes = last_recordable_frame - transport_frame;
731                 rec_offset = 0;
732                 break;
733
734         case OverlapExternal:
735                 /*    |--------|    recrange
736                     --------------  transrange
737                 */
738                 rec_nframes = last_recordable_frame - first_recordable_frame;
739                 rec_offset = first_recordable_frame - transport_frame;
740                 break;
741         }
742
743         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 rec? %2 @ %3 (for %4) FRF %5 LRF %6 : rf %7 @ %8\n",
744                                                               _name, enum_2_string (ot), transport_frame, nframes,
745                                                               first_recordable_frame, last_recordable_frame, rec_nframes, rec_offset));
746 }
747
748 void
749 Diskstream::prepare_to_stop (framepos_t pos)
750 {
751         last_recordable_frame = pos + _capture_offset;
752 }