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