the big Route structure refactor. !!!! THIS WILL ***NOT LOAD*** PRIOR 3.0 or 2.X...
[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 #include <sigc++/bind.h>
35
36 #include "pbd/error.h"
37 #include "pbd/basename.h"
38 #include <glibmm/thread.h>
39 #include "pbd/xml++.h"
40 #include "pbd/memento_command.h"
41
42 #include "ardour/ardour.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/diskstream.h"
45 #include "ardour/utils.h"
46 #include "ardour/configuration.h"
47 #include "ardour/audiofilesource.h"
48 #include "ardour/send.h"
49 #include "ardour/playlist.h"
50 #include "ardour/cycle_timer.h"
51 #include "ardour/region.h"
52 #include "ardour/panner.h"
53 #include "ardour/session.h"
54 #include "ardour/io.h"
55 #include "ardour/route.h"
56
57 #include "i18n.h"
58 #include <locale.h>
59
60 using namespace std;
61 using namespace ARDOUR;
62 using namespace PBD;
63
64 /* XXX This goes uninitialized when there is no ~/.ardour3 directory.
65  * I can't figure out why, so this will do for now (just stole the
66  * default from configuration_vars.h).  0 is not a good value for
67  * allocating buffer sizes..
68  */
69 ARDOUR::nframes_t Diskstream::disk_io_chunk_frames = 1024 * 256;
70
71 sigc::signal<void>                Diskstream::DiskOverrun;
72 sigc::signal<void>                Diskstream::DiskUnderrun;
73
74 Diskstream::Diskstream (Session &sess, const string &name, Flag flag)
75         : SessionObject(sess, name)
76 {
77         init (flag);
78 }
79         
80 Diskstream::Diskstream (Session& sess, const XMLNode& node)
81         : SessionObject(sess, "unnamed diskstream")
82 {
83         init (Recordable);
84 }
85
86 void
87 Diskstream::init (Flag f)
88 {
89         _flags = f;
90         _io = 0;
91         _alignment_style = ExistingMaterial;
92         _persistent_alignment_style = ExistingMaterial;
93         first_input_change = true;
94         i_am_the_modifier = 0;
95         g_atomic_int_set (&_record_enabled, 0);
96         was_recording = false;
97         capture_start_frame = 0;
98         capture_captured = 0;
99         _visible_speed = 1.0f;
100         _actual_speed = 1.0f;
101         _buffer_reallocation_required = false;
102         _seek_required = false;
103         first_recordable_frame = max_frames;
104         last_recordable_frame = max_frames;
105         _roll_delay = 0;
106         _capture_offset = 0;
107         _processed = false;
108         _slaved = false;
109         adjust_capture_position = 0;
110         last_possibly_recording = 0;
111         loop_location = 0;
112         wrap_buffer_size = 0;
113         speed_buffer_size = 0;
114         last_phase = 0;
115         // speed = 1 in 40.24 fixed point math
116         phi = (uint64_t) (0x1000000);
117         target_phi = phi;
118         file_frame = 0;
119         playback_sample = 0;
120         playback_distance = 0;
121         _read_data_count = 0;
122         _write_data_count = 0;
123         commit_should_unlock = false;
124
125         pending_overwrite = false;
126         overwrite_frame = 0;
127         overwrite_queued = false;
128         input_change_pending = NoChange;
129 }
130
131 Diskstream::~Diskstream ()
132 {
133         if (_playlist)
134                 _playlist->release ();
135 }
136
137 void
138 Diskstream::set_io (IO& io)
139 {
140         _io = &io;
141         input_change_pending = ConfigurationChanged;
142         non_realtime_input_change ();
143         set_align_style_from_io ();
144 }
145
146 void
147 Diskstream::handle_input_change (IOChange change, void *src)
148 {
149         Glib::Mutex::Lock lm (state_lock);
150
151         if (!(input_change_pending & change)) {
152                 input_change_pending = IOChange (input_change_pending|change);
153                 _session.request_input_change_handling ();
154         }
155 }
156
157 void
158 Diskstream::non_realtime_set_speed ()
159 {
160         if (_buffer_reallocation_required)
161         {
162                 Glib::Mutex::Lock lm (state_lock);
163                 allocate_temporary_buffers ();
164
165                 _buffer_reallocation_required = false;
166         }
167
168         if (_seek_required) {
169                 if (speed() != 1.0f || speed() != -1.0f) {
170                         seek ((nframes_t) (_session.transport_frame() * (double) speed()), true);
171                 }
172                 else {
173                         seek (_session.transport_frame(), true);
174                 }
175
176                 _seek_required = false;
177         }
178 }
179
180 bool
181 Diskstream::realtime_set_speed (double sp, bool global)
182 {
183         bool changed = false;
184         double new_speed = sp * _session.transport_speed();
185         
186         if (_visible_speed != sp) {
187                 _visible_speed = sp;
188                 changed = true;
189         }
190         
191         if (new_speed != _actual_speed) {
192                 
193                 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * 
194                                                                             fabs (new_speed)) + 1;
195                 
196                 if (required_wrap_size > wrap_buffer_size) {
197                         _buffer_reallocation_required = true;
198                 }
199                 
200                 _actual_speed = new_speed;
201                 target_phi = (uint64_t) (0x1000000 * fabs(_actual_speed));
202         }
203
204         if (changed) {
205                 if (!global) {
206                         _seek_required = true;
207                 }
208                 SpeedChanged (); /* EMIT SIGNAL */
209         }
210
211         return _buffer_reallocation_required || _seek_required;
212 }
213
214 void
215 Diskstream::prepare ()
216 {
217         _processed = false;
218         playback_distance = 0;
219 }
220
221 void
222 Diskstream::recover ()
223 {
224         if (commit_should_unlock) {
225                 state_lock.unlock();
226         }
227         _processed = false;
228 }
229
230 void
231 Diskstream::set_capture_offset ()
232 {
233         if (_io == 0) {
234                 /* can't capture, so forget it */
235                 return;
236         }
237
238         _capture_offset = _io->latency();
239 }
240
241 void
242 Diskstream::set_align_style (AlignStyle a)
243 {
244         if (record_enabled() && _session.actively_recording()) {
245                 return;
246         }
247
248         if (a != _alignment_style) {
249                 _alignment_style = a;
250                 AlignmentStyleChanged ();
251         }
252 }
253
254 int
255 Diskstream::set_loop (Location *location)
256 {
257         if (location) {
258                 if (location->start() >= location->end()) {
259                         error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
260                         return -1;
261                 }
262         }
263
264         loop_location = location;
265
266          LoopSet (location); /* EMIT SIGNAL */
267         return 0;
268 }
269
270 ARDOUR::nframes_t
271 Diskstream::get_capture_start_frame (uint32_t n)
272 {
273         Glib::Mutex::Lock lm (capture_info_lock);
274
275         if (capture_info.size() > n) {
276                 return capture_info[n]->start;
277         }
278         else {
279                 return capture_start_frame;
280         }
281 }
282
283 ARDOUR::nframes_t
284 Diskstream::get_captured_frames (uint32_t n)
285 {
286         Glib::Mutex::Lock lm (capture_info_lock);
287
288         if (capture_info.size() > n) {
289                 return capture_info[n]->frames;
290         }
291         else {
292                 return capture_captured;
293         }
294 }
295
296 void
297 Diskstream::set_roll_delay (ARDOUR::nframes_t nframes)
298 {
299         _roll_delay = nframes;
300 }
301
302 void
303 Diskstream::set_speed (double sp)
304 {
305         _session.request_diskstream_speed (*this, sp);
306
307         /* to force a rebuffering at the right place */
308         playlist_modified();
309 }
310
311 int
312 Diskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
313 {
314         {
315                 Glib::Mutex::Lock lm (state_lock);
316
317                 if (playlist == _playlist) {
318                         return 0;
319                 }
320
321                 plmod_connection.disconnect ();
322                 plgone_connection.disconnect ();
323                 plregion_connection.disconnect ();
324
325                 if (_playlist) {
326                         _playlist->release();
327                 }
328                         
329                 _playlist = playlist;
330                 _playlist->use();
331
332                 if (!in_set_state && recordable()) {
333                         reset_write_sources (false);
334                 }
335                 
336                 plmod_connection = _playlist->Modified.connect (mem_fun (*this, &Diskstream::playlist_modified));
337                 plgone_connection = _playlist->GoingAway.connect (bind (mem_fun (*this, &Diskstream::playlist_deleted), boost::weak_ptr<Playlist>(_playlist)));
338                 plregion_connection = _playlist->RangesMoved.connect (mem_fun (*this, &Diskstream::playlist_ranges_moved));
339         }
340
341         /* don't do this if we've already asked for it *or* if we are setting up
342            the diskstream for the very first time - the input changed handling will
343            take care of the buffer refill.
344         */
345
346         if (!overwrite_queued && !(_session.state_of_the_state() & Session::CannotSave)) {
347                 _session.request_overwrite_buffer (this);
348                 overwrite_queued = true;
349         }
350         
351         PlaylistChanged (); /* EMIT SIGNAL */
352         _session.set_dirty ();
353
354         return 0;
355 }
356
357 void
358 Diskstream::playlist_changed (Change ignored)
359 {
360         playlist_modified ();
361 }
362
363 void
364 Diskstream::playlist_modified ()
365 {
366         if (!i_am_the_modifier && !overwrite_queued) {
367                 _session.request_overwrite_buffer (this);
368                 overwrite_queued = true;
369         } 
370 }
371
372 void
373 Diskstream::playlist_deleted (boost::weak_ptr<Playlist> wpl)
374 {
375         boost::shared_ptr<Playlist> pl (wpl.lock());
376
377         if (pl == _playlist) {
378
379                 /* this catches an ordering issue with session destruction. playlists 
380                    are destroyed before diskstreams. we have to invalidate any handles
381                    we have to the playlist.
382                 */
383                 
384                 if (_playlist) {
385                         _playlist.reset ();
386                 } 
387         }
388 }
389
390 bool
391 Diskstream::set_name (const string& str)
392 {
393         if (str != _name) {
394                 assert(playlist());
395                 playlist()->set_name (str);
396                 
397                 SessionObject::set_name(str);
398                 
399                 if (!in_set_state && recordable()) {
400                         /* rename existing capture files so that they have the correct name */
401                         return rename_write_sources ();
402                 } else {
403                         return false;
404                 }
405         }
406
407         return true;
408 }
409
410 void
411 Diskstream::remove_region_from_last_capture (boost::weak_ptr<Region> wregion)
412 {
413         boost::shared_ptr<Region> region (wregion.lock());
414
415         if (!region) {
416                 return;
417         }
418         
419         _last_capture_regions.remove (region);
420 }
421
422 void
423 Diskstream::playlist_ranges_moved (list< Evoral::RangeMove<nframes_t> > const & movements_frames)
424 {
425 #if 0
426         
427         XXX THIS HAS TO BE FIXED FOR 3.0
428
429
430         if (Config->get_automation_follows_regions () == false) {
431                 return;
432         }
433         
434         list< Evoral::RangeMove<double> > movements;
435         for (list< Evoral::RangeMove<nframes_t> >::const_iterator i = movements_frames.begin();
436                    i != movements_frames.end(); ++i) {
437                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
438         }
439         
440         /* move gain automation */
441         boost::shared_ptr<AutomationList> gain_alist = _io->gain_control()->list();
442         XMLNode & before = gain_alist->get_state ();
443         gain_alist->move_ranges (movements);
444         _session.add_command (
445                 new MementoCommand<AutomationList> (
446                         *gain_alist.get(), &before, &gain_alist->get_state ()
447                         )
448                 );
449         
450         /* move panner automation */
451         boost::shared_ptr<Panner> p = _io->panner ();
452         if (p) {
453                 for (uint32_t i = 0; i < p->npanners (); ++i) {
454                         boost::shared_ptr<AutomationList> pan_alist = p->streampanner(i).pan_control()->alist();
455                         XMLNode & before = pan_alist->get_state ();
456                         pan_alist->move_ranges (movements);
457                         _session.add_command (new MementoCommand<AutomationList> (
458                                         *pan_alist.get(), &before, &pan_alist->get_state ()));
459                 }
460         }
461
462         /* move processor automation */
463         /* XXX: ewww */
464         Route * route = dynamic_cast<Route*> (_io);
465         if (route) {
466                 route->foreach_processor (sigc::bind (sigc::mem_fun (*this, &Diskstream::move_processor_automation), movements_frames));
467         }
468 #endif
469 }
470
471 void
472 Diskstream::move_processor_automation (boost::weak_ptr<Processor> p,
473                                        list< Evoral::RangeMove<nframes_t> > const & movements_frames)
474 {
475         boost::shared_ptr<Processor> processor (p.lock ());
476         if (!processor) {
477                 return;
478         }
479         
480         list< Evoral::RangeMove<double> > movements;
481         for (list< Evoral::RangeMove<nframes_t> >::const_iterator i = movements_frames.begin();
482                    i != movements_frames.end(); ++i) {
483                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
484         }
485         
486         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
487
488         for (set<Evoral::Parameter>::iterator i = a.begin (); i != a.end (); ++i) {
489                 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
490                 XMLNode & before = al->get_state ();
491                 al->move_ranges (movements);
492                 _session.add_command (
493                         new MementoCommand<AutomationList> (
494                                 *al.get(), &before, &al->get_state ()
495                                 )
496                         );
497         }
498 }
499