Fix use of invalidated iterator (#4822).
[ardour.git] / libs / ardour / crossfade.cc
1 /*
2     Copyright (C) 2003-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 "ardour/debug.h"
21 #include "ardour/types.h"
22 #include "ardour/crossfade.h"
23 #include "ardour/audioregion.h"
24 #include "ardour/playlist.h"
25 #include "ardour/utils.h"
26 #include "ardour/session.h"
27 #include "ardour/source.h"
28 #include "ardour/region_factory.h"
29
30 #include "i18n.h"
31 #include <locale.h>
32
33 using namespace std;
34 using namespace ARDOUR;
35 using namespace PBD;
36
37 framecnt_t Crossfade::_short_xfade_length = 0;
38
39 /* XXX if and when we ever implement parallel processing of the process()
40    callback, these will need to be handled on a per-thread basis.
41 */
42
43 Sample* Crossfade::crossfade_buffer_out = 0;
44 Sample* Crossfade::crossfade_buffer_in = 0;
45
46
47 #define CROSSFADE_DEFAULT_PROPERTIES \
48         _active (Properties::active, _session.config.get_xfades_active ()) \
49         , _follow_overlap (Properties::follow_overlap, false)
50
51
52 namespace ARDOUR {
53         namespace Properties {
54                 PropertyDescriptor<bool> follow_overlap;
55         }
56 }
57
58 void
59 Crossfade::make_property_quarks ()
60 {
61         Properties::follow_overlap.property_id = g_quark_from_static_string (X_("follow-overlap"));
62         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for follow-overlap = %1\n",      Properties::follow_overlap.property_id));
63 }
64
65 void
66 Crossfade::set_buffer_size (framecnt_t sz)
67 {
68         delete [] crossfade_buffer_out;
69         crossfade_buffer_out = 0;
70
71         delete [] crossfade_buffer_in;
72         crossfade_buffer_in = 0;
73
74         if (sz) {
75                 crossfade_buffer_out = new Sample[sz];
76                 crossfade_buffer_in = new Sample[sz];
77         }
78 }
79
80 bool
81 Crossfade::operator== (const Crossfade& other)
82 {
83         return (_in == other._in) && (_out == other._out);
84 }
85
86 Crossfade::Crossfade (boost::shared_ptr<AudioRegion> in, boost::shared_ptr<AudioRegion> out,
87                       framecnt_t length,
88                       AnchorPoint ap)
89         : AudioRegion (in->session(), 0, length, in->name() + string ("<>") + out->name())
90         , CROSSFADE_DEFAULT_PROPERTIES
91         , _fade_in (Evoral::Parameter(FadeInAutomation)) // linear (gain coefficient) => -inf..+6dB
92         , _fade_out (Evoral::Parameter(FadeOutAutomation)) // linear (gain coefficient) => -inf..+6dB
93
94 {
95         register_properties ();
96
97         _in = in;
98         _out = out;
99         _anchor_point = ap;
100         _fixed = true;
101         _follow_overlap = false;
102
103         initialize ();
104 }
105
106 Crossfade::Crossfade (boost::shared_ptr<AudioRegion> a, boost::shared_ptr<AudioRegion> b, CrossfadeModel model, bool act)
107         : AudioRegion (a->session(), 0, 0, a->name() + string ("<>") + b->name())
108         , CROSSFADE_DEFAULT_PROPERTIES
109         , _fade_in (Evoral::Parameter(FadeInAutomation)) // linear (gain coefficient) => -inf..+6dB
110         , _fade_out (Evoral::Parameter(FadeOutAutomation)) // linear (gain coefficient) => -inf..+6dB
111 {
112         register_properties ();
113         
114         _in_update = false;
115         _fixed = false;
116         _follow_overlap = false;
117
118         if (compute (a, b, model)) {
119                 throw failed_constructor();
120         }
121
122         _active = act;
123
124         initialize ();
125 }
126
127 Crossfade::Crossfade (const Playlist& playlist, XMLNode const & node)
128         : AudioRegion (playlist.session(), 0, 0, "unnamed crossfade")
129         , CROSSFADE_DEFAULT_PROPERTIES
130         , _fade_in (Evoral::Parameter(FadeInAutomation)) // linear (gain coefficient) => -inf..+6dB
131         , _fade_out (Evoral::Parameter(FadeOutAutomation)) // linear (gain coefficient) => -inf..+6dB
132
133 {
134         register_properties ();
135         
136         boost::shared_ptr<Region> r;
137         XMLProperty const * prop;
138         LocaleGuard lg (X_("POSIX"));
139
140         /* we have to find the in/out regions before we can do anything else */
141
142         if ((prop = node.property ("in")) == 0) {
143                 error << _("Crossfade: no \"in\" region in state") << endmsg;
144                 throw failed_constructor();
145         }
146
147         PBD::ID id (prop->value());
148
149         r = playlist.find_region (id);
150
151         if (!r) {
152                 /* the `in' region is not in a playlist, which probably means that this crossfade
153                    is in the undo record, so we have to find the region in the global region map.
154                 */
155                 r = RegionFactory::region_by_id (id);
156         }
157
158         if (!r) {
159                 error << string_compose (_("Crossfade: no \"in\" region %1 found in playlist %2 nor in region map"), id, playlist.name())
160                       << endmsg;
161                 throw failed_constructor();
162         }
163
164         if ((_in = boost::dynamic_pointer_cast<AudioRegion> (r)) == 0) {
165                 throw failed_constructor();
166         }
167
168         if ((prop = node.property ("out")) == 0) {
169                 error << _("Crossfade: no \"out\" region in state") << endmsg;
170                 throw failed_constructor();
171         }
172
173         PBD::ID id2 (prop->value());
174
175         r = playlist.find_region (id2);
176
177         if (!r) {
178                 r = RegionFactory::region_by_id (id2);
179         }
180
181         if (!r) {
182                 error << string_compose (_("Crossfade: no \"out\" region %1 found in playlist %2 nor in region map"), id2, playlist.name())
183                       << endmsg;
184                 throw failed_constructor();
185         }
186
187         if ((_out = boost::dynamic_pointer_cast<AudioRegion> (r)) == 0) {
188                 throw failed_constructor();
189         }
190
191         _length = 0;
192         initialize();
193         _active = true;
194
195         if (set_state (node, Stateful::loading_state_version)) {
196                 throw failed_constructor();
197         }
198 }
199
200 Crossfade::Crossfade (boost::shared_ptr<Crossfade> orig, boost::shared_ptr<AudioRegion> newin, boost::shared_ptr<AudioRegion> newout)
201         : AudioRegion (boost::dynamic_pointer_cast<const AudioRegion> (orig), 0)
202         , CROSSFADE_DEFAULT_PROPERTIES
203         , _fade_in (orig->_fade_in)
204         , _fade_out (orig->_fade_out)
205 {
206         register_properties ();
207         
208         _active           = orig->_active;
209         _in_update        = orig->_in_update;
210         _anchor_point     = orig->_anchor_point;
211         _follow_overlap   = orig->_follow_overlap;
212         _fixed            = orig->_fixed;
213         _position         = orig->_position;
214
215         _in = newin;
216         _out = newout;
217
218         // copied from Crossfade::initialize()
219         _in_update = false;
220
221         _out->suspend_fade_out ();
222         _in->suspend_fade_in ();
223
224         overlap_type = _in->coverage (_out->position(), _out->last_frame());
225         layer_relation = (int32_t) (_in->layer() - _out->layer());
226
227         // Let's make sure the fade isn't too long
228         set_xfade_length(_length);
229 }
230
231
232 Crossfade::~Crossfade ()
233 {
234 }
235
236 void
237 Crossfade::register_properties ()
238 {
239         add_property (_active);
240         add_property (_follow_overlap);
241 }
242
243 void
244 Crossfade::initialize ()
245 {
246         /* merge source lists from regions */
247
248         _sources = _in->sources();
249         _sources.insert (_sources.end(), _out->sources().begin(), _out->sources().end());
250
251         for (SourceList::iterator i = _sources.begin(); i != _sources.end(); ++i) {
252                 (*i)->inc_use_count ();
253         }
254
255         _master_sources = _in->master_sources();
256         _master_sources.insert(_master_sources.end(), _out->master_sources().begin(), _out->master_sources().end());
257
258         for (SourceList::iterator i = _master_sources.begin(); i != _master_sources.end(); ++i) {
259                 (*i)->inc_use_count ();
260         }
261
262         _in_update = false;
263
264         _out->suspend_fade_out ();
265         _in->suspend_fade_in ();
266
267         _fade_out.freeze ();
268         _fade_out.clear ();
269
270 #define EQUAL_POWER_MINUS_3DB
271 #ifdef  EQUAL_POWER_MINUS_3DB
272
273         _fade_out.add ((_length * 0.000000), 1.000000);
274         _fade_out.add ((_length * 0.166667), 0.948859);
275         _fade_out.add ((_length * 0.333333), 0.851507);
276         _fade_out.add ((_length * 0.500000), 0.707946);
277         _fade_out.add ((_length * 0.666667), 0.518174);
278         _fade_out.add ((_length * 0.833333), 0.282192);
279         _fade_out.add ((_length * 1.000000), 0.000000);
280
281 #else // EQUAL_POWER_MINUS_6DB
282
283         _fade_out.add ((_length * 0.000000), 1.000000);
284         _fade_out.add ((_length * 0.166667), 0.833033);
285         _fade_out.add ((_length * 0.333333), 0.666186);
286         _fade_out.add ((_length * 0.500000), 0.499459);
287         _fade_out.add ((_length * 0.666667), 0.332853);
288         _fade_out.add ((_length * 0.833333), 0.166366);
289         _fade_out.add ((_length * 1.000000), 0.000000);
290 #endif
291
292         _fade_out.thaw ();
293
294         _fade_in.freeze ();
295         _fade_in.clear ();
296
297 #define EQUAL_POWER_MINUS_3DB
298 #ifdef  EQUAL_POWER_MINUS_3DB
299
300         _fade_in.add ((_length * 0.000000), 0.000000);
301         _fade_in.add ((_length * 0.166667), 0.282192);
302         _fade_in.add ((_length * 0.333333), 0.518174);
303         _fade_in.add ((_length * 0.500000), 0.707946);
304         _fade_in.add ((_length * 0.666667), 0.851507);
305         _fade_in.add ((_length * 0.833333), 0.948859);
306         _fade_in.add ((_length * 1.000000), 1.000000);
307
308 #else // EQUAL_POWER_MINUS_SIX_DB
309
310         _fade_in.add ((_length * 0.000000), 0.000000);
311         _fade_in.add ((_length * 0.166667), 0.166366);
312         _fade_in.add ((_length * 0.333333), 0.332853);
313         _fade_in.add ((_length * 0.500000), 0.499459);
314         _fade_in.add ((_length * 0.666667), 0.666186);
315         _fade_in.add ((_length * 0.833333), 0.833033);
316         _fade_in.add ((_length * 1.000000), 1.000000);
317
318 #endif
319
320         _fade_in.thaw ();
321
322         overlap_type = _in->coverage (_out->position(), _out->last_frame());
323         layer_relation = (int32_t) (_in->layer() - _out->layer());
324 }
325
326 framecnt_t
327 Crossfade::read_raw_internal (Sample* buf, framecnt_t start, framecnt_t cnt, int channel) const
328 {
329         Sample* mixdown = new Sample[cnt];
330         float* gain = new float[cnt];
331         framecnt_t ret;
332
333         ret = read_at (buf, mixdown, gain, start, cnt, channel);
334
335         delete [] mixdown;
336         delete [] gain;
337
338         return ret;
339 }
340
341 framecnt_t
342 Crossfade::read_at (Sample *buf, Sample *mixdown_buffer,
343                     float *gain_buffer, framepos_t start, framecnt_t cnt, uint32_t chan_n) const
344 {
345         frameoffset_t offset;
346         framecnt_t to_write;
347
348         if (!_active) {
349                 return 0;
350         }
351
352         if (start < _position) {
353
354                 /* handle an initial section of the read area that we do not
355                    cover.
356                 */
357
358                 offset = _position - start;
359
360                 if (offset < cnt) {
361                         cnt -= offset;
362                 } else {
363                         return 0;
364                 }
365
366                 start = _position;
367                 buf += offset;
368                 to_write = min (_length.val(), cnt);
369
370         } else {
371
372                 to_write = min ((_length - (start - _position)), cnt);
373
374         }
375
376         offset = start - _position;
377
378         /* Prevent data from piling up inthe crossfade buffers when reading a transparent region */
379         if (!(_out->opaque())) {
380                 memset (crossfade_buffer_out, 0, sizeof (Sample) * to_write);
381         } else if (!(_in->opaque())) {
382                 memset (crossfade_buffer_in, 0, sizeof (Sample) * to_write);
383         }
384
385         _out->read_at (crossfade_buffer_out, mixdown_buffer, gain_buffer, start, to_write, chan_n);
386         _in->read_at (crossfade_buffer_in, mixdown_buffer, gain_buffer, start, to_write, chan_n);
387
388         float* fiv = new float[to_write];
389         float* fov = new float[to_write];
390
391         _fade_in.curve().get_vector (offset, offset+to_write, fiv, to_write);
392         _fade_out.curve().get_vector (offset, offset+to_write, fov, to_write);
393
394         /* note: although we have not explicitly taken into account the return values
395            from _out->read_at() or _in->read_at(), the length() function does this
396            implicitly. why? because it computes a value based on the in+out regions'
397            position and length, and so we know precisely how much data they could return.
398         */
399
400         for (framecnt_t n = 0; n < to_write; ++n) {
401                 buf[n] = (crossfade_buffer_out[n] * fov[n]) + (crossfade_buffer_in[n] * fiv[n]);
402         }
403
404         delete [] fov;
405         delete [] fiv;
406
407         return to_write;
408 }
409
410 OverlapType
411 Crossfade::coverage (framepos_t start, framepos_t end) const
412 {
413         framepos_t my_end = _position + _length;
414
415         if ((start >= _position) && (end <= my_end)) {
416                 return OverlapInternal;
417         }
418         if ((end >= _position) && (end <= my_end)) {
419                 return OverlapStart;
420         }
421         if ((start >= _position) && (start <= my_end)) {
422                 return OverlapEnd;
423         }
424         if ((_position >= start) && (_position <= end) && (my_end <= end)) {
425                 return OverlapExternal;
426         }
427         return OverlapNone;
428 }
429
430 void
431 Crossfade::set_active (bool yn)
432 {
433         if (_active != yn) {
434                 _active = yn;
435                 PropertyChanged (PropertyChange (Properties::active));
436         }
437 }
438
439 bool
440 Crossfade::refresh ()
441 {
442         /* crossfades must be between non-muted regions */
443
444         if (_out->muted() || _in->muted()) {
445                 Invalidated (shared_from_this ());
446                 return false;
447         }
448
449         /* Top layer shouldn't be transparent */
450
451         if (!((layer_relation > 0 ? _in : _out)->opaque())) {
452                 Invalidated (shared_from_this());
453                 return false;
454         }
455
456         /* regions must cannot be identically sized and placed */
457
458         if (_in->position() == _out->position() && _in->length() == _out->length()) {
459                 Invalidated (shared_from_this());
460                 return false;
461         }
462
463         /* layer ordering cannot change */
464
465         int32_t new_layer_relation = (int32_t) (_in->layer() - _out->layer());
466
467         if (new_layer_relation * layer_relation < 0) { // different sign, layers rotated
468                 Invalidated (shared_from_this ());
469                 return false;
470         }
471
472         OverlapType ot = _in->coverage (_out->first_frame(), _out->last_frame());
473
474         if (ot == OverlapNone) {
475                 Invalidated (shared_from_this ());
476                 return false;
477         }
478
479         bool send_signal;
480
481         if (ot != overlap_type) {
482
483                 if (_follow_overlap) {
484
485                         try {
486                                 compute (_in, _out, _session.config.get_xfade_model());
487                         }
488
489                         catch (NoCrossfadeHere& err) {
490                                 Invalidated (shared_from_this ());
491                                 return false;
492                         }
493
494                         send_signal = true;
495
496                 } else {
497                         Invalidated (shared_from_this ());
498                         return false;
499                 }
500
501         } else {
502
503                 send_signal = update ();
504         }
505
506         if (send_signal) {
507                 PropertyChange bounds;
508                 bounds.add (Properties::start);
509                 bounds.add (Properties::position);
510                 bounds.add (Properties::length);
511                 PropertyChanged (bounds); /* EMIT SIGNAL */
512         }
513
514         _in_update = false;
515
516         return true;
517 }
518
519 bool
520 Crossfade::update ()
521 {
522         framecnt_t newlen;
523
524         if (_follow_overlap) {
525                 newlen = _out->first_frame() + _out->length() - _in->first_frame();
526         } else {
527                 newlen = _length;
528         }
529
530         if (newlen == 0) {
531                 Invalidated (shared_from_this ());
532                 return false;
533         }
534
535         _in_update = true;
536
537         if ((_follow_overlap && newlen != _length) || (_length > newlen)) {
538
539                 double factor =  newlen / (double) _length;
540
541                 _fade_out.x_scale (factor);
542                 _fade_in.x_scale (factor);
543
544                 _length = newlen;
545         }
546
547         switch (_anchor_point) {
548         case StartOfIn:
549                 _position = _in->first_frame();
550                 break;
551
552         case EndOfIn:
553                 _position = _in->last_frame() - _length;
554                 break;
555
556         case EndOfOut:
557                 _position = _out->last_frame() - _length;
558         }
559
560         return true;
561 }
562
563 int
564 Crossfade::compute (boost::shared_ptr<AudioRegion> a, boost::shared_ptr<AudioRegion> b, CrossfadeModel model)
565 {
566         boost::shared_ptr<AudioRegion> top;
567         boost::shared_ptr<AudioRegion> bottom;
568         framecnt_t short_xfade_length;
569
570         short_xfade_length = _short_xfade_length;
571
572         if (a->layer() < b->layer()) {
573                 top = b;
574                 bottom = a;
575         } else {
576                 top = a;
577                 bottom = b;
578         }
579
580         /* first check for matching ends */
581
582         if (top->first_frame() == bottom->first_frame()) {
583
584                 /* Both regions start at the same point */
585
586                 if (top->last_frame() < bottom->last_frame()) {
587
588                         /* top ends before bottom, so put an xfade
589                            in at the end of top.
590                         */
591
592                         /* [-------- top ---------- ]
593                          * {====== bottom =====================}
594                          */
595
596                         _in = bottom;
597                         _out = top;
598
599                         if (top->last_frame() < short_xfade_length) {
600                                 _position = 0;
601                         } else {
602                                 _position = top->last_frame() - short_xfade_length;
603                         }
604                         
605                         set_xfade_length (min (short_xfade_length, top->length()));
606                         _follow_overlap = false;
607                         _anchor_point = EndOfIn;
608                         _active = true;
609                         _fixed = true;
610
611                 } else {
612                         /* top ends after (or same time) as bottom - no xfade
613                          */
614
615                         /* [-------- top ------------------------ ]
616                          * {====== bottom =====================}
617                          */
618
619                         throw NoCrossfadeHere();
620                 }
621
622         } else if (top->last_frame() == bottom->last_frame()) {
623
624                 /* Both regions end at the same point */
625
626                 if (top->first_frame() > bottom->first_frame()) {
627
628                         /* top starts after bottom, put an xfade in at the
629                            start of top
630                         */
631
632                         /*            [-------- top ---------- ]
633                          * {====== bottom =====================}
634                          */
635
636                         _in = top;
637                         _out = bottom;
638                         _position = top->first_frame();
639                         set_xfade_length (min (short_xfade_length, top->length()));
640                         _follow_overlap = false;
641                         _anchor_point = StartOfIn;
642                         _active = true;
643                         _fixed = true;
644
645                 } else {
646                         /* top starts before bottom - no xfade
647                          */
648
649                         /* [-------- top ------------------------ ]
650                          *    {====== bottom =====================}
651                          */
652
653                         throw NoCrossfadeHere();
654                 }
655
656         } else {
657
658                 /* OK, time to do more regular overlapping */
659
660                 OverlapType ot = top->coverage (bottom->first_frame(), bottom->last_frame());
661
662                 switch (ot) {
663                 case OverlapNone:
664                         /* should be NOTREACHED as a precondition of creating
665                            a new crossfade, but we need to handle it here.
666                         */
667                         throw NoCrossfadeHere();
668                         break;
669
670                 case OverlapInternal:
671                 case OverlapExternal:
672                         /* should be NOTREACHED because of tests above */
673                         throw NoCrossfadeHere();
674                         break;
675
676                 case OverlapEnd: /* top covers start of bottom but ends within it */
677
678                         /* [---- top ------------------------]
679                          *                { ==== bottom ============ }
680                          */
681
682                         _in = bottom;
683                         _out = top;
684                         _anchor_point = EndOfOut;
685
686                         if (model == FullCrossfade) {
687                                 _position = bottom->first_frame(); // "{"
688                                 set_xfade_length (_out->first_frame() + _out->length() - _in->first_frame());
689                                 /* leave active alone */
690                                 _follow_overlap = true;
691                         } else {
692                                 set_xfade_length (min (short_xfade_length, top->length()));
693                                 _position = top->last_frame() - _length;  // "]" - length
694                                 _active = true;
695                                 _follow_overlap = false;
696
697                         }
698                         break;
699
700                 case OverlapStart:   /* top starts within bottom but covers bottom's end */
701
702                         /*                   { ==== top ============ }
703                          *   [---- bottom -------------------]
704                          */
705
706                         _in = top;
707                         _out = bottom;
708                         _position = top->first_frame();
709                         _anchor_point = StartOfIn;
710
711                         if (model == FullCrossfade) {
712                                 set_xfade_length (_out->first_frame() + _out->length() - _in->first_frame());
713                                 /* leave active alone */
714                                 _follow_overlap = true;
715                         } else {
716                                 set_xfade_length (min (short_xfade_length, top->length()));
717                                 _active = true;
718                                 _follow_overlap = false;
719
720                         }
721
722                         break;
723                 }
724         }
725
726         return 0;
727 }
728
729 XMLNode&
730 Crossfade::get_state ()
731 {
732         XMLNode* node = new XMLNode (X_("Crossfade"));
733         XMLNode* child;
734         char buf[64];
735         LocaleGuard lg (X_("POSIX"));
736
737         id().print (buf, sizeof (buf));
738         node->add_property ("id", buf);
739         _out->id().print (buf, sizeof (buf));
740         node->add_property ("out", buf);
741         _in->id().print (buf, sizeof (buf));
742         node->add_property ("in", buf);
743         node->add_property ("active", (_active ? "yes" : "no"));
744         node->add_property ("follow-overlap", (_follow_overlap ? "yes" : "no"));
745         node->add_property ("fixed", (_fixed ? "yes" : "no"));
746         snprintf (buf, sizeof(buf), "%" PRId64, _length.val());
747         node->add_property ("length", buf);
748         snprintf (buf, sizeof(buf), "%" PRIu32, (uint32_t) _anchor_point);
749         node->add_property ("anchor-point", buf);
750         snprintf (buf, sizeof(buf), "%" PRId64, _position.val());
751         node->add_property ("position", buf);
752
753         child = node->add_child ("FadeIn");
754
755         for (AutomationList::iterator ii = _fade_in.begin(); ii != _fade_in.end(); ++ii) {
756                 XMLNode* pnode;
757
758                 pnode = new XMLNode ("point");
759
760                 snprintf (buf, sizeof (buf), "%" PRId64, (framepos_t) floor ((*ii)->when));
761                 pnode->add_property ("x", buf);
762                 snprintf (buf, sizeof (buf), "%.12g", (*ii)->value);
763                 pnode->add_property ("y", buf);
764                 child->add_child_nocopy (*pnode);
765         }
766
767         child = node->add_child ("FadeOut");
768
769         for (AutomationList::iterator ii = _fade_out.begin(); ii != _fade_out.end(); ++ii) {
770                 XMLNode* pnode;
771
772                 pnode = new XMLNode ("point");
773
774                 snprintf (buf, sizeof (buf), "%" PRId64, (framepos_t) floor ((*ii)->when));
775                 pnode->add_property ("x", buf);
776                 snprintf (buf, sizeof (buf), "%.12g", (*ii)->value);
777                 pnode->add_property ("y", buf);
778                 child->add_child_nocopy (*pnode);
779         }
780
781         return *node;
782 }
783
784 int
785 Crossfade::set_state (const XMLNode& node, int /*version*/)
786 {
787         XMLNodeConstIterator i;
788         XMLNodeList children;
789         XMLNode* fi;
790         XMLNode* fo;
791         const XMLProperty* prop;
792         LocaleGuard lg (X_("POSIX"));
793         PropertyChange what_changed;
794         framepos_t val;
795
796         set_id (node);
797
798         if ((prop = node.property ("position")) != 0) {
799                 sscanf (prop->value().c_str(), "%" PRId64, &val);
800                 if (val != _position) {
801                         _position = val;
802                         what_changed.add (Properties::position);
803                 }
804         } else {
805                 warning << _("old-style crossfade information - no position information") << endmsg;
806                 _position = _in->first_frame();
807         }
808
809         if ((prop = node.property ("active")) != 0) {
810                 bool x = string_is_affirmative (prop->value());
811                 if (x != _active) {
812                         _active = x;
813                         what_changed.add (Properties::active);
814                 }
815         } else {
816                 _active = true;
817         }
818
819         if ((prop = node.property ("follow-overlap")) != 0) {
820                 _follow_overlap = string_is_affirmative (prop->value());
821         } else {
822                 _follow_overlap = false;
823         }
824
825         if ((prop = node.property ("fixed")) != 0) {
826                 _fixed = string_is_affirmative (prop->value());
827         } else {
828                 _fixed = false;
829         }
830
831         if ((prop = node.property ("anchor-point")) != 0) {
832                 _anchor_point = AnchorPoint (atoi ((prop->value().c_str())));
833         } else {
834                 _anchor_point = StartOfIn;
835         }
836
837         if ((prop = node.property ("length")) != 0) {
838
839                 sscanf (prop->value().c_str(), "%" PRId64, &val);
840                 if (val != _length) {
841                         _length = val;
842                         what_changed.add (Properties::length);
843                 }
844
845         } else {
846
847                 /* XXX this branch is legacy code from before
848                    the point where we stored xfade lengths.
849                 */
850
851                 if ((_length = overlap_length()) == 0) {
852                         throw failed_constructor();
853                 }
854         }
855
856         if ((fi = find_named_node (node, "FadeIn")) == 0) {
857                 return -1;
858         }
859
860         if ((fo = find_named_node (node, "FadeOut")) == 0) {
861                 return -1;
862         }
863
864         /* fade in */
865
866         _fade_in.freeze ();
867         _fade_in.clear ();
868
869         children = fi->children();
870
871         for (i = children.begin(); i != children.end(); ++i) {
872                 if ((*i)->name() == "point") {
873                         framepos_t x;
874                         float y;
875
876                         prop = (*i)->property ("x");
877                         sscanf (prop->value().c_str(), "%" PRId64, &x);
878
879                         prop = (*i)->property ("y");
880                         sscanf (prop->value().c_str(), "%f", &y);
881
882                         _fade_in.add (x, y);
883                 }
884         }
885
886         if (_fade_in.size() < 2) {
887                 /* fade state somehow saved with no points */
888                 return -1;
889         }
890
891         _fade_in.front()->value = 0.0;
892         _fade_in.back()->value = 1.0;
893
894         _fade_in.thaw ();
895
896         /* fade out */
897
898         _fade_out.freeze ();
899         _fade_out.clear ();
900
901         children = fo->children();
902
903         for (i = children.begin(); i != children.end(); ++i) {
904                 if ((*i)->name() == "point") {
905                         framepos_t x;
906                         float y;
907                         XMLProperty* prop;
908
909                         prop = (*i)->property ("x");
910                         sscanf (prop->value().c_str(), "%" PRId64, &x);
911
912                         prop = (*i)->property ("y");
913                         sscanf (prop->value().c_str(), "%f", &y);
914
915                         _fade_out.add (x, y);
916                 }
917         }
918
919         if (_fade_out.size() < 2) {
920                 /* fade state somehow saved with no points */
921                 return -1;
922         }
923
924         _fade_out.front()->value = 1.0;
925         _fade_out.back()->value = 0.0;
926
927         _fade_out.thaw ();
928
929         PropertyChanged (what_changed); /* EMIT SIGNAL */
930         FadesChanged (); /* EMIT SIGNAL */
931
932         return 0;
933 }
934
935 bool
936 Crossfade::can_follow_overlap () const
937 {
938         return !_fixed;
939 }
940
941 void
942 Crossfade::set_follow_overlap (bool yn)
943 {
944         if (yn == _follow_overlap || _fixed) {
945                 return;
946         }
947
948         _follow_overlap = yn;
949
950         if (!yn) {
951                 set_xfade_length (_short_xfade_length);
952         } else {
953                 set_xfade_length (_out->first_frame() + _out->length() - _in->first_frame());
954         }
955
956         PropertyChanged (PropertyChange (Properties::follow_overlap));
957 }
958
959 framecnt_t
960 Crossfade::set_xfade_length (framecnt_t len)
961 {
962         framecnt_t limit = 0;
963
964         switch (_anchor_point) {
965         case StartOfIn:
966                 limit = _in->length();
967                 break;
968
969         case EndOfIn:
970                 limit = _in->length();
971                 break;
972
973         case EndOfOut:
974                 limit = _out->length();
975                 break;
976
977         }
978
979         len = min (limit, len);
980
981         double factor = len / (double) _length;
982
983         _in_update = true;
984         _fade_out.x_scale (factor);
985         _fade_in.x_scale (factor);
986         _in_update = false;
987
988         _length = len;
989
990         PropertyChanged (PropertyChange (Properties::length));
991
992         return len;
993 }
994
995 framecnt_t
996 Crossfade::overlap_length () const
997 {
998         if (_fixed) {
999                 return _length;
1000         }
1001         return _out->first_frame() + _out->length() - _in->first_frame();
1002 }
1003
1004 void
1005 Crossfade::set_short_xfade_length (framecnt_t n)
1006 {
1007         _short_xfade_length = n;
1008 }