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