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