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