add tempo adjustment
[ardour.git] / libs / ardour / automation_list.cc
1 /*
2     Copyright (C) 2002 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 <set>
21 #include <climits>
22 #include <float.h>
23 #include <cmath>
24 #include <sstream>
25 #include <algorithm>
26 #include "ardour/automation_list.h"
27 #include "ardour/beats_frames_converter.h"
28 #include "ardour/event_type_map.h"
29 #include "ardour/parameter_descriptor.h"
30 #include "ardour/parameter_types.h"
31 #include "ardour/evoral_types_convert.h"
32 #include "ardour/types_convert.h"
33 #include "evoral/Curve.hpp"
34 #include "pbd/memento_command.h"
35 #include "pbd/stacktrace.h"
36 #include "pbd/enumwriter.h"
37 #include "pbd/types_convert.h"
38
39 #include "pbd/i18n.h"
40
41 using namespace std;
42 using namespace ARDOUR;
43 using namespace PBD;
44
45 PBD::Signal1<void,AutomationList *> AutomationList::AutomationListCreated;
46
47 #if 0
48 static void dumpit (const AutomationList& al, string prefix = "")
49 {
50         cerr << prefix << &al << endl;
51         for (AutomationList::const_iterator i = al.begin(); i != al.end(); ++i) {
52                 cerr << prefix << '\t' << (*i)->when << ',' << (*i)->value << endl;
53         }
54         cerr << "\n";
55 }
56 #endif
57 AutomationList::AutomationList (const Evoral::Parameter& id, const Evoral::ParameterDescriptor& desc)
58         : ControlList(id, desc)
59         , _before (0)
60 {
61         _state = Off;
62         g_atomic_int_set (&_touching, 0);
63         _interpolation = default_interpolation ();
64
65         create_curve_if_necessary();
66
67         assert(_parameter.type() != NullAutomation);
68         AutomationListCreated(this);
69 }
70
71 AutomationList::AutomationList (const Evoral::Parameter& id)
72         : ControlList(id, ARDOUR::ParameterDescriptor(id))
73         , _before (0)
74 {
75         _state = Off;
76         g_atomic_int_set (&_touching, 0);
77         _interpolation = default_interpolation ();
78
79         create_curve_if_necessary();
80
81         assert(_parameter.type() != NullAutomation);
82         AutomationListCreated(this);
83 }
84
85 AutomationList::AutomationList (const AutomationList& other)
86         : ControlList(other)
87         , StatefulDestructible()
88         , _before (0)
89 {
90         _state = other._state;
91         g_atomic_int_set (&_touching, other.touching());
92
93         create_curve_if_necessary();
94
95         assert(_parameter.type() != NullAutomation);
96         AutomationListCreated(this);
97 }
98
99 AutomationList::AutomationList (const AutomationList& other, double start, double end)
100         : ControlList(other, start, end)
101         , _before (0)
102 {
103         _state = other._state;
104         g_atomic_int_set (&_touching, other.touching());
105
106         create_curve_if_necessary();
107
108         assert(_parameter.type() != NullAutomation);
109         AutomationListCreated(this);
110 }
111
112 /** @param id is used for legacy sessions where the type is not present
113  * in or below the AutomationList node.  It is used if @param id is non-null.
114  */
115 AutomationList::AutomationList (const XMLNode& node, Evoral::Parameter id)
116         : ControlList(id, ARDOUR::ParameterDescriptor(id))
117         , _before (0)
118 {
119         g_atomic_int_set (&_touching, 0);
120         _interpolation = default_interpolation ();
121         _state = Off;
122
123         set_state (node, Stateful::loading_state_version);
124
125         if (id) {
126                 _parameter = id;
127         }
128
129         create_curve_if_necessary();
130
131         assert(_parameter.type() != NullAutomation);
132         AutomationListCreated(this);
133 }
134
135 AutomationList::~AutomationList()
136 {
137         delete _before;
138 }
139
140 boost::shared_ptr<Evoral::ControlList>
141 AutomationList::create(const Evoral::Parameter&           id,
142                        const Evoral::ParameterDescriptor& desc)
143 {
144         return boost::shared_ptr<Evoral::ControlList>(new AutomationList(id, desc));
145 }
146
147 void
148 AutomationList::create_curve_if_necessary()
149 {
150         switch (_parameter.type()) {
151         case GainAutomation:
152         case TrimAutomation:
153         case PanAzimuthAutomation:
154         case PanElevationAutomation:
155         case PanWidthAutomation:
156         case FadeInAutomation:
157         case FadeOutAutomation:
158         case EnvelopeAutomation:
159                 create_curve();
160                 break;
161         default:
162                 break;
163         }
164
165         WritePassStarted.connect_same_thread (_writepass_connection, boost::bind (&AutomationList::snapshot_history, this, false));
166 }
167
168 AutomationList&
169 AutomationList::operator= (const AutomationList& other)
170 {
171         if (this != &other) {
172                 ControlList::freeze ();
173                 /* ControlList::operator= calls copy_events() which calls
174                  * mark_dirty() and maybe_signal_changed()
175                  */
176                 ControlList::operator= (other);
177                 _state = other._state;
178                 _touching = other._touching;
179                 ControlList::thaw ();
180         }
181
182         return *this;
183 }
184
185 void
186 AutomationList::maybe_signal_changed ()
187 {
188         ControlList::maybe_signal_changed ();
189
190         if (!ControlList::frozen()) {
191                 StateChanged (); /* EMIT SIGNAL */
192         }
193 }
194
195 void
196 AutomationList::set_automation_state (AutoState s)
197 {
198         if (s == _state) {
199                 return;
200         }
201         _state = s;
202         if (s == Write && _desc.toggled) {
203                 snapshot_history (true);
204         }
205         automation_state_changed (s); /* EMIT SIGNAL */
206 }
207
208 Evoral::ControlList::InterpolationStyle
209 AutomationList::default_interpolation () const
210 {
211         switch (_parameter.type()) {
212                 case GainAutomation:
213                 case BusSendLevel:
214                 case EnvelopeAutomation:
215 #ifndef XXX_NEW_INTERPOLATON__BREAK_SESSION_FORMAT_XXX
216                         /* use old, wrong linear gain interpolation */
217                         return ControlList::Linear;
218 #endif
219                         return ControlList::Exponential;
220                         break;
221                 case TrimAutomation:
222                         return ControlList::Logarithmic;
223                         break;
224                 default:
225                         break;
226         }
227         /* based on Evoral::ParameterDescriptor log,toggle,.. */
228         return ControlList::default_interpolation ();
229 }
230
231 void
232 AutomationList::start_write_pass (double when)
233 {
234         snapshot_history (true);
235         ControlList::start_write_pass (when);
236 }
237
238 void
239 AutomationList::write_pass_finished (double when, double thinning_factor)
240 {
241         ControlList::write_pass_finished (when, thinning_factor);
242 }
243
244 void
245 AutomationList::start_touch (double when)
246 {
247         if (_state == Touch) {
248                 start_write_pass (when);
249         }
250
251         g_atomic_int_set (&_touching, 1);
252 }
253
254 void
255 AutomationList::stop_touch (double)
256 {
257         if (g_atomic_int_get (&_touching) == 0) {
258                 /* this touch has already been stopped (probably by Automatable::transport_stopped),
259                    so we've nothing to do.
260                 */
261                 return;
262         }
263
264         g_atomic_int_set (&_touching, 0);
265 }
266
267 /* _before may be owned by the undo stack,
268  * so we have to be careful about doing this.
269  *
270  * ::before () transfers ownership, setting _before to 0
271  */
272 void
273 AutomationList::clear_history ()
274 {
275         delete _before;
276         _before = 0;
277 }
278
279 void
280 AutomationList::snapshot_history (bool need_lock)
281 {
282         if (!in_new_write_pass ()) {
283                 return;
284         }
285         delete _before;
286         _before = &state (true, need_lock);
287 }
288
289
290 void
291 AutomationList::thaw ()
292 {
293         ControlList::thaw();
294
295         if (_changed_when_thawed) {
296                 _changed_when_thawed = false;
297                 StateChanged(); /* EMIT SIGNAL */
298         }
299 }
300
301 bool
302 AutomationList::paste (const ControlList& alist, double pos, DoubleBeatsFramesConverter const& bfc)
303 {
304         AutomationType src_type = (AutomationType)alist.parameter().type();
305         AutomationType dst_type = (AutomationType)_parameter.type();
306
307         if (parameter_is_midi (src_type) == parameter_is_midi (dst_type)) {
308                 return ControlList::paste (alist, pos);
309         }
310         bool to_frame = parameter_is_midi (src_type);
311
312         ControlList cl (alist);
313         cl.clear ();
314         for (const_iterator i = alist.begin ();i != alist.end (); ++i) {
315                 double when = (*i)->when;
316                 if (to_frame) {
317                         when = bfc.to ((*i)->when);
318                 } else {
319                         when = bfc.from ((*i)->when);
320                 }
321                 cl.fast_simple_add (when, (*i)->value);
322         }
323         return ControlList::paste (cl, pos);
324 }
325
326 Command*
327 AutomationList::memento_command (XMLNode* before, XMLNode* after)
328 {
329         return new MementoCommand<AutomationList> (*this, before, after);
330 }
331
332 XMLNode&
333 AutomationList::get_state ()
334 {
335         return state (true, true);
336 }
337
338 XMLNode&
339 AutomationList::state (bool full, bool need_lock)
340 {
341         XMLNode* root = new XMLNode (X_("AutomationList"));
342
343         root->set_property ("automation-id", EventTypeMap::instance().to_symbol(_parameter));
344         root->set_property ("id", id());
345
346 #ifndef XXX_NEW_INTERPOLATON__BREAK_SESSION_FORMAT_XXX
347         /* force new enums to existing ones in session-file */
348         Evoral::ControlList::InterpolationStyle is = _interpolation;
349         switch (is) {
350                 case ControlList::Exponential:
351                 case ControlList::Logarithmic:
352                         is = ControlList::Linear;
353                         break;
354                 default:
355                         break;
356         }
357         root->set_property ("interpolation-style", is);
358 #else
359         root->set_property ("interpolation-style", _interpolation);
360 #endif
361
362         if (full) {
363                 /* never serialize state with Write enabled - too dangerous
364                    for the user's data
365                 */
366                 if (_state != Write) {
367                         root->set_property ("state", _state);
368                 } else {
369                         if (_events.empty ()) {
370                                 root->set_property ("state", Off);
371                         } else {
372                                 root->set_property ("state", Touch);
373                         }
374                 }
375         } else {
376                 /* never save anything but Off for automation state to a template */
377                 root->set_property ("state", Off);
378         }
379
380         if (!_events.empty()) {
381                 root->add_child_nocopy (serialize_events (need_lock));
382         }
383
384         return *root;
385 }
386
387 XMLNode&
388 AutomationList::serialize_events (bool need_lock)
389 {
390         XMLNode* node = new XMLNode (X_("events"));
391         stringstream str;
392
393         Glib::Threads::RWLock::ReaderLock lm (Evoral::ControlList::_lock, Glib::Threads::NOT_LOCK);
394         if (need_lock) {
395                 lm.acquire ();
396         }
397         for (iterator xx = _events.begin(); xx != _events.end(); ++xx) {
398                 str << PBD::to_string ((*xx)->when);
399                 str << ' ';
400                 str << PBD::to_string ((*xx)->value);
401                 str << '\n';
402         }
403
404         /* XML is a bit wierd */
405
406         XMLNode* content_node = new XMLNode (X_("foo")); /* it gets renamed by libxml when we set content */
407         content_node->set_content (str.str());
408
409         node->add_child_nocopy (*content_node);
410
411         return *node;
412 }
413
414 int
415 AutomationList::deserialize_events (const XMLNode& node)
416 {
417         if (node.children().empty()) {
418                 return -1;
419         }
420
421         XMLNode* content_node = node.children().front();
422
423         if (content_node->content().empty()) {
424                 return -1;
425         }
426
427         ControlList::freeze ();
428         clear ();
429
430         stringstream str (content_node->content());
431
432         std::string x_str;
433         std::string y_str;
434         double x;
435         double y;
436         bool ok = true;
437
438         while (str) {
439                 str >> x_str;
440                 if (!str || !PBD::string_to<double> (x_str, x)) {
441                         break;
442                 }
443                 str >> y_str;
444                 if (!str || !PBD::string_to<double> (y_str, y)) {
445                         ok = false;
446                         break;
447                 }
448                 y = std::min ((double)_desc.upper, std::max ((double)_desc.lower, y));
449                 fast_simple_add (x, y);
450         }
451
452         if (!ok) {
453                 clear ();
454                 error << _("automation list: cannot load coordinates from XML, all points ignored") << endmsg;
455         } else {
456                 mark_dirty ();
457                 maybe_signal_changed ();
458         }
459
460         thaw ();
461
462         return 0;
463 }
464
465 int
466 AutomationList::set_state (const XMLNode& node, int version)
467 {
468         XMLNodeList nlist = node.children();
469         XMLNode* nsos;
470         XMLNodeIterator niter;
471
472         if (node.name() == X_("events")) {
473                 /* partial state setting*/
474                 return deserialize_events (node);
475         }
476
477         if (node.name() == X_("Envelope") || node.name() == X_("FadeOut") || node.name() == X_("FadeIn")) {
478
479                 if ((nsos = node.child (X_("AutomationList")))) {
480                         /* new school in old school clothing */
481                         return set_state (*nsos, version);
482                 }
483
484                 /* old school */
485
486                 const XMLNodeList& elist = node.children();
487                 XMLNodeConstIterator i;
488
489                 ControlList::freeze ();
490                 clear ();
491
492                 for (i = elist.begin(); i != elist.end(); ++i) {
493
494                         pframes_t x;
495                         if (!(*i)->get_property ("x", x)) {
496                                 error << _("automation list: no x-coordinate stored for control point (point ignored)") << endmsg;
497                                 continue;
498                         }
499
500                         double y;
501                         if (!(*i)->get_property ("y", y)) {
502                                 error << _("automation list: no y-coordinate stored for control point (point ignored)") << endmsg;
503                                 continue;
504                         }
505
506                         y = std::min ((double)_desc.upper, std::max ((double)_desc.lower, y));
507                         fast_simple_add (x, y);
508                 }
509
510                 thaw ();
511
512                 return 0;
513         }
514
515         if (node.name() != X_("AutomationList") ) {
516                 error << string_compose (_("AutomationList: passed XML node called %1, not \"AutomationList\" - ignored"), node.name()) << endmsg;
517                 return -1;
518         }
519
520         if (set_id (node)) {
521                 /* update session AL list */
522                 AutomationListCreated(this);
523         }
524
525         std::string value;
526         if (node.get_property (X_("automation-id"), value)) {
527                 _parameter = EventTypeMap::instance().from_symbol(value);
528         } else {
529                 warning << "Legacy session: automation list has no automation-id property." << endmsg;
530         }
531
532         if (!node.get_property (X_("interpolation-style"), _interpolation)) {
533                 _interpolation = default_interpolation ();
534         }
535 #ifndef XXX_NEW_INTERPOLATON__BREAK_SESSION_FORMAT_XXX
536         /* internally force logarithmic and Trim params to use Log-scale */
537         if (_desc.logarithmic || _parameter.type() == TrimAutomation) {
538                 _interpolation = ControlList::Logarithmic;
539         }
540 #endif
541
542         if (node.get_property (X_("state"), _state)) {
543                 if (_state == Write) {
544                         _state = Off;
545                 }
546                 automation_state_changed (_state);
547         } else {
548                 _state = Off;
549         }
550
551         bool have_events = false;
552
553         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
554                 if ((*niter)->name() == X_("events")) {
555                         deserialize_events (*(*niter));
556                         have_events = true;
557                 }
558         }
559
560         if (!have_events) {
561                 /* there was no Events child node; clear any current events */
562                 freeze ();
563                 clear ();
564                 mark_dirty ();
565                 maybe_signal_changed ();
566                 thaw ();
567         }
568
569         return 0;
570 }
571
572 bool
573 AutomationList::operator!= (AutomationList const & other) const
574 {
575         return (
576                 static_cast<ControlList const &> (*this) != static_cast<ControlList const &> (other) ||
577                 _state != other._state ||
578                 _touching != other._touching
579                 );
580 }
581
582 PBD::PropertyBase *
583 AutomationListProperty::clone () const
584 {
585         return new AutomationListProperty (
586                 this->property_id(),
587                 boost::shared_ptr<AutomationList> (new AutomationList (*this->_old.get())),
588                 boost::shared_ptr<AutomationList> (new AutomationList (*this->_current.get()))
589                 );
590 }
591