patch from hsyl20 for punch in wierdness (mantis #1937). Thanks!
[ardour.git] / libs / ardour / panner.cc
1 /*
2     Copyright (C) 2004 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 <cmath>
21 #include <cerrno>
22 #include <fstream>
23 #include <cstdlib>
24 #include <string>
25 #include <cstdio>
26 #include <locale.h>
27 #include <unistd.h>
28 #include <float.h>
29
30 #include <glibmm.h>
31
32 #include <pbd/error.h>
33 #include <pbd/failed_constructor.h>
34 #include <pbd/xml++.h>
35 #include <pbd/enumwriter.h>
36
37 #include <ardour/session.h>
38 #include <ardour/panner.h>
39 #include <ardour/utils.h>
40
41 #include <ardour/mix.h>
42
43 #include "i18n.h"
44
45 #include <pbd/mathfix.h>
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace PBD;
50
51 float Panner::current_automation_version_number = 1.0;
52
53 string EqualPowerStereoPanner::name = "Equal Power Stereo";
54 string Multi2dPanner::name = "Multiple (2D)";
55
56 /* this is a default mapper of  control values to a pan position
57    others can be imagined. 
58 */
59
60 static pan_t direct_control_to_pan (double fract) { 
61         return fract;
62 }
63
64 static double direct_pan_to_control (pan_t val) { 
65         return val;
66 }
67
68 StreamPanner::StreamPanner (Panner& p)
69         : parent (p),
70           _control (X_("panner"), *this)
71 {
72         _muted = false;
73
74         parent.session().add_controllable (&_control);
75
76         x = 0.5;
77         y = 0.5;
78         z = 0.5;
79 }
80
81 StreamPanner::~StreamPanner ()
82 {
83 }
84
85 void
86 StreamPanner::PanControllable::set_value (float val)
87 {
88         panner.set_position (direct_control_to_pan (val));
89 }
90
91 float
92 StreamPanner::PanControllable::get_value (void) const
93 {
94         float xpos;
95         panner.get_effective_position (xpos);
96         return direct_pan_to_control (xpos);
97 }
98
99 bool
100 StreamPanner::PanControllable::can_send_feedback () const
101 {
102         AutoState astate = panner.get_parent().automation_state ();
103
104         if ((astate == Play) || (astate == Touch && !panner.get_parent().touching())) {
105                 return true;
106         }
107
108         return false;
109 }
110
111 void
112 StreamPanner::set_muted (bool yn)
113 {
114         if (yn != _muted) {
115                 _muted = yn;
116                 StateChanged ();
117         }
118 }
119
120 void
121 StreamPanner::set_position (float xpos, bool link_call)
122 {
123         if (!link_call && parent.linked()) {
124                 parent.set_position (xpos, *this);
125         }
126
127         if (x != xpos) {
128                 x = xpos;
129                 update ();
130                 Changed ();
131                 _control.Changed ();
132         }
133 }
134
135 void
136 StreamPanner::set_position (float xpos, float ypos, bool link_call)
137 {
138         if (!link_call && parent.linked()) {
139                 parent.set_position (xpos, ypos, *this);
140         }
141
142         if (x != xpos || y != ypos) {
143                 
144                 x = xpos;
145                 y = ypos;
146                 update ();
147                 Changed ();
148         }
149 }
150
151 void
152 StreamPanner::set_position (float xpos, float ypos, float zpos, bool link_call)
153 {
154         if (!link_call && parent.linked()) {
155                 parent.set_position (xpos, ypos, zpos, *this);
156         }
157
158         if (x != xpos || y != ypos || z != zpos) {
159                 x = xpos;
160                 y = ypos;
161                 z = zpos;
162                 update ();
163                 Changed ();
164         }
165 }
166
167 int
168 StreamPanner::set_state (const XMLNode& node)
169 {
170         const XMLProperty* prop;
171         XMLNodeConstIterator iter;
172
173         if ((prop = node.property (X_("muted")))) {
174                 set_muted (string_is_affirmative (prop->value()));
175         }
176
177         return 0;
178 }
179
180 void
181 StreamPanner::add_state (XMLNode& node)
182 {
183         node.add_property (X_("muted"), (muted() ? "yes" : "no"));
184 }
185
186 /*---------------------------------------------------------------------- */
187
188 BaseStereoPanner::BaseStereoPanner (Panner& p)
189         : StreamPanner (p), _automation (0.0, 1.0, 0.5)
190 {
191 }
192
193 BaseStereoPanner::~BaseStereoPanner ()
194 {
195 }
196
197 void
198 BaseStereoPanner::snapshot (nframes_t now)
199 {
200         if (_automation.automation_state() == Write || _automation.automation_state() == Touch) {
201                 _automation.rt_add (now, x);
202         }
203 }
204
205 void
206 BaseStereoPanner::transport_stopped (nframes_t frame)
207 {
208         if (_automation.automation_state() != Off) {
209                 set_position (_automation.eval (frame));
210         }
211
212         _automation.reposition_for_rt_add (frame);
213 }
214
215 void
216 BaseStereoPanner::set_automation_style (AutoStyle style)
217 {
218         _automation.set_automation_style (style);
219 }
220
221 void
222 BaseStereoPanner::set_automation_state (AutoState state)
223 {
224         if (state != _automation.automation_state()) {
225
226                 _automation.set_automation_state (state);
227                 
228                 if (state != Off) {
229                         set_position (_automation.eval (parent.session().transport_frame()));
230                 }
231         }
232 }
233
234 int
235 BaseStereoPanner::load (istream& in, string path, uint32_t& linecnt)
236 {
237         char line[128];
238         LocaleGuard lg (X_("POSIX"));
239         
240         _automation.clear ();
241
242         while (in.getline (line, sizeof (line), '\n')) {
243                 jack_nframes_t when;
244                 double value;
245
246                 ++linecnt;
247
248                 if (strcmp (line, "end") == 0) {
249                         break;
250                 }
251
252                 if (sscanf (line, "%" PRIu32 " %lf", &when, &value) != 2) {
253                         warning << string_compose(_("badly formatted pan automation event record at line %1 of %2 (ignored) [%3]"), linecnt, path, line) << endmsg;
254                         continue;
255                 }
256
257                 _automation.fast_simple_add (when, value);
258         }
259
260         /* now that we are done loading */
261
262         _automation.StateChanged ();
263
264         return 0;
265 }
266
267 void
268 BaseStereoPanner::distribute (Sample* src, Sample** obufs, gain_t gain_coeff, nframes_t nframes)
269 {
270         pan_t delta;
271         Sample* dst;
272         pan_t pan;
273
274         if (_muted) {
275                 return;
276         }
277
278         /* LEFT */
279
280         dst = obufs[0];
281
282         if (fabsf ((delta = (left - desired_left))) > 0.002) { // about 1 degree of arc 
283                 
284                 /* interpolate over 64 frames or nframes, whichever is smaller */
285                 
286                 nframes_t limit = min ((nframes_t)64, nframes);
287                 nframes_t n;
288
289                 delta = -(delta / (float) (limit));
290                 
291                 for (n = 0; n < limit; n++) {
292                         left_interp = left_interp + delta;
293                         left = left_interp + 0.9 * (left - left_interp);
294                         dst[n] += src[n] * left * gain_coeff;
295                 }
296                 
297                 pan = left * gain_coeff;
298
299                 Session::mix_buffers_with_gain(dst+n,src+n,nframes-n,pan);
300                 
301         } else {
302                 
303                 left = desired_left;
304                 left_interp = left;
305
306                 if ((pan = (left * gain_coeff)) != 1.0f) {
307                         
308                         if (pan != 0.0f) {
309                                 
310                                 Session::mix_buffers_with_gain(dst,src,nframes,pan);
311
312                                 /* mark that we wrote into the buffer */
313
314                                 // obufs[0] = 0;
315
316                         } 
317                         
318                 } else {
319                         
320                         Session::mix_buffers_no_gain(dst,src,nframes);
321                         
322                         /* mark that we wrote into the buffer */
323                         
324                         // obufs[0] = 0;
325                 }
326         }
327
328         /* RIGHT */
329
330         dst = obufs[1];
331         
332         if (fabsf ((delta = (right - desired_right))) > 0.002) { // about 1 degree of arc 
333                 
334                 /* interpolate over 64 frames or nframes, whichever is smaller */
335                 
336                 nframes_t limit = min ((nframes_t)64, nframes);
337                 nframes_t n;
338
339                 delta = -(delta / (float) (limit));
340
341                 for (n = 0; n < limit; n++) {
342                         right_interp = right_interp + delta;
343                         right = right_interp + 0.9 * (right - right_interp);
344                         dst[n] += src[n] * right * gain_coeff;
345                 }
346                 
347                 pan = right * gain_coeff;
348                 
349                 Session::mix_buffers_with_gain(dst+n,src+n,nframes-n,pan);
350                 
351                 /* XXX it would be nice to mark the buffer as written to */
352
353         } else {
354
355                 right = desired_right;
356                 right_interp = right;
357                 
358                 if ((pan = (right * gain_coeff)) != 1.0f) {
359                         
360                         if (pan != 0.0f) {
361                                 
362                                 Session::mix_buffers_with_gain(dst,src,nframes,pan);
363                                 
364                                 /* XXX it would be nice to mark the buffer as written to */
365                         }
366                         
367                 } else {
368                         
369                         Session::mix_buffers_no_gain(dst,src,nframes);
370                         
371                         /* XXX it would be nice to mark the buffer as written to */
372                 }
373         }
374 }
375
376 /*---------------------------------------------------------------------- */
377
378 EqualPowerStereoPanner::EqualPowerStereoPanner (Panner& p)
379         : BaseStereoPanner (p)
380 {
381         update ();
382
383         left = desired_left;
384         right = desired_right;
385         left_interp = left;
386         right_interp = right;
387 }
388
389 EqualPowerStereoPanner::~EqualPowerStereoPanner ()
390 {
391 }
392
393 void
394 EqualPowerStereoPanner::update ()
395 {
396         /* it would be very nice to split this out into a virtual function
397            that can be accessed from BaseStereoPanner and used in distribute_automated().
398            
399            but the place where its used in distribute_automated() is a tight inner loop,
400            and making "nframes" virtual function calls to compute values is an absurd
401            overhead.
402         */
403
404         /* x == 0 => hard left
405            x == 1 => hard right
406         */
407
408         float panR = x;
409         float panL = 1 - panR;
410
411         const float pan_law_attenuation = -3.0f;
412         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
413         
414         desired_left = panL * (scale * panL + 1.0f - scale);
415         desired_right = panR * (scale * panR + 1.0f - scale);
416
417         effective_x = x;
418 }
419
420 void
421 EqualPowerStereoPanner::distribute_automated (Sample* src, Sample** obufs, 
422                                               nframes_t start, nframes_t end, nframes_t nframes,
423                                               pan_t** buffers)
424 {
425         Sample* dst;
426         pan_t* pbuf;
427
428         /* fetch positional data */
429
430         if (!_automation.rt_safe_get_vector (start, end, buffers[0], nframes)) {
431                 /* fallback */
432                 if (!_muted) {
433                         distribute (src, obufs, 1.0, nframes);
434                 }
435                 return;
436         }
437
438         /* store effective pan position. do this even if we are muted */
439
440         if (nframes > 0) 
441                 effective_x = buffers[0][nframes-1];
442
443         if (_muted) {
444                 return;
445         }
446
447         /* apply pan law to convert positional data into pan coefficients for
448            each buffer (output)
449         */
450
451         const float pan_law_attenuation = -3.0f;
452         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
453
454         for (nframes_t n = 0; n < nframes; ++n) {
455
456                 float panR = buffers[0][n];
457                 float panL = 1 - panR;
458                 
459                 buffers[0][n] = panL * (scale * panL + 1.0f - scale);
460                 buffers[1][n] = panR * (scale * panR + 1.0f - scale);
461         }
462
463         /* LEFT */
464
465         dst = obufs[0];
466         pbuf = buffers[0];
467         
468         for (nframes_t n = 0; n < nframes; ++n) {
469                 dst[n] += src[n] * pbuf[n];
470         }       
471
472         /* XXX it would be nice to mark the buffer as written to */
473
474         /* RIGHT */
475
476         dst = obufs[1];
477         pbuf = buffers[1];
478
479         for (nframes_t n = 0; n < nframes; ++n) {
480                 dst[n] += src[n] * pbuf[n];
481         }       
482         
483         /* XXX it would be nice to mark the buffer as written to */
484 }
485
486 StreamPanner*
487 EqualPowerStereoPanner::factory (Panner& parent)
488 {
489         return new EqualPowerStereoPanner (parent);
490 }
491
492 XMLNode&
493 EqualPowerStereoPanner::get_state (void)
494 {
495         return state (true);
496 }
497
498 XMLNode&
499 EqualPowerStereoPanner::state (bool full_state)
500 {
501         XMLNode* root = new XMLNode ("StreamPanner");
502         char buf[64];
503         LocaleGuard lg (X_("POSIX"));
504
505         snprintf (buf, sizeof (buf), "%.12g", x); 
506         root->add_property (X_("x"), buf);
507         root->add_property (X_("type"), EqualPowerStereoPanner::name);
508
509         XMLNode* autonode = new XMLNode (X_("Automation"));
510         autonode->add_child_nocopy (_automation.state (full_state));
511         root->add_child_nocopy (*autonode);
512
513         StreamPanner::add_state (*root);
514
515         root->add_child_nocopy (_control.get_state ());
516
517         return *root;
518 }
519
520 int
521 EqualPowerStereoPanner::set_state (const XMLNode& node)
522 {
523         const XMLProperty* prop;
524         float pos;
525         LocaleGuard lg (X_("POSIX"));
526
527         if ((prop = node.property (X_("x")))) {
528                 pos = atof (prop->value().c_str());
529                 set_position (pos, true);
530         } 
531
532         StreamPanner::set_state (node);
533
534         for (XMLNodeConstIterator iter = node.children().begin(); iter != node.children().end(); ++iter) {
535
536                 if ((*iter)->name() == X_("controllable")) {
537                         if ((prop = (*iter)->property("name")) != 0 && prop->value() == "panner") {
538                                 _control.set_state (**iter);
539                         }
540
541                 } else if ((*iter)->name() == X_("Automation")) {
542
543                         _automation.set_state (*((*iter)->children().front()));
544
545                         if (_automation.automation_state() != Off) {
546                                 set_position (_automation.eval (parent.session().transport_frame()));
547                         }
548                 }
549         }
550
551         return 0;
552 }
553
554 /*----------------------------------------------------------------------*/
555
556 Multi2dPanner::Multi2dPanner (Panner& p)
557         : StreamPanner (p), _automation (0.0, 1.0, 0.5) // XXX useless
558 {
559         update ();
560 }
561
562 Multi2dPanner::~Multi2dPanner ()
563 {
564 }
565
566 void
567 Multi2dPanner::snapshot (nframes_t now)
568 {
569         // how?
570 }
571
572 void
573 Multi2dPanner::transport_stopped (nframes_t frame)
574 {
575         //what?
576 }
577
578 void
579 Multi2dPanner::set_automation_style (AutoStyle style)
580 {
581         //what?
582 }
583
584 void
585 Multi2dPanner::set_automation_state (AutoState state)
586 {
587         // what?
588 }
589
590 void
591 Multi2dPanner::update ()
592 {
593         static const float BIAS = FLT_MIN;
594         uint32_t i;
595         uint32_t nouts = parent.outputs.size();
596         float dsq[nouts];
597         float f, fr;
598         vector<pan_t> pans;
599
600         f = 0.0f;
601
602         for (i = 0; i < nouts; i++) {
603                 dsq[i] = ((x - parent.outputs[i].x) * (x - parent.outputs[i].x) + (y - parent.outputs[i].y) * (y - parent.outputs[i].y) + BIAS);
604                 if (dsq[i] < 0.0) {
605                         dsq[i] = 0.0;
606                 }
607                 f += dsq[i] * dsq[i];
608         }
609 #ifdef __APPLE__
610         // terrible hack to support OSX < 10.3.9 builds
611         fr = (float) (1.0 / sqrt((double)f));
612 #else
613         fr = 1.0 / sqrtf(f);
614 #endif  
615         for (i = 0; i < nouts; ++i) {
616                 parent.outputs[i].desired_pan = 1.0f - (dsq[i] * fr);
617         }
618
619         effective_x = x;
620 }
621
622 void
623 Multi2dPanner::distribute (Sample* src, Sample** obufs, gain_t gain_coeff, nframes_t nframes)
624 {
625         Sample* dst;
626         pan_t pan;
627         vector<Panner::Output>::iterator o;
628         uint32_t n;
629
630         if (_muted) {
631                 return;
632         }
633
634
635         for (n = 0, o = parent.outputs.begin(); o != parent.outputs.end(); ++o, ++n) {
636
637                 dst = obufs[n];
638         
639 #ifdef CAN_INTERP
640                 if (fabsf ((delta = (left_interp - desired_left))) > 0.002) { // about 1 degree of arc 
641                         
642                         /* interpolate over 64 frames or nframes, whichever is smaller */
643                         
644                         nframes_t limit = min ((nframes_t)64, nframes);
645                         nframes_t n;
646                         
647                         delta = -(delta / (float) (limit));
648                 
649                         for (n = 0; n < limit; n++) {
650                                 left_interp = left_interp + delta;
651                                 left = left_interp + 0.9 * (left - left_interp);
652                                 dst[n] += src[n] * left * gain_coeff;
653                         }
654                         
655                         pan = left * gain_coeff;
656                         Session::mix_buffers_with_gain(dst+n,src+n,nframes-n,pan);
657                         
658                 } else {
659
660 #else                   
661                         pan = (*o).desired_pan;
662                         
663                         if ((pan *= gain_coeff) != 1.0f) {
664                                 
665                                 if (pan != 0.0f) {
666                                         Session::mix_buffers_with_gain(dst,src,nframes,pan);
667                                 } 
668                         } else {
669                                         Session::mix_buffers_no_gain(dst,src,nframes);
670                         }
671 #endif
672 #ifdef CAN_INTERP
673                 }
674 #endif
675         }
676         
677         return;
678 }
679
680 void
681 Multi2dPanner::distribute_automated (Sample* src, Sample** obufs, 
682                                      nframes_t start, nframes_t end, nframes_t nframes,
683                                      pan_t** buffers)
684 {
685         if (_muted) {
686                 return;
687         }
688
689         /* what ? */
690
691         return;
692 }
693
694 StreamPanner*
695 Multi2dPanner::factory (Panner& p)
696 {
697         return new Multi2dPanner (p);
698 }
699
700 int
701 Multi2dPanner::load (istream& in, string path, uint32_t& linecnt)
702 {
703         return 0;
704 }
705
706 XMLNode&
707 Multi2dPanner::get_state (void)
708 {
709         return state (true);
710 }
711
712 XMLNode&
713 Multi2dPanner::state (bool full_state)
714 {
715         XMLNode* root = new XMLNode ("StreamPanner");
716         char buf[64];
717         LocaleGuard lg (X_("POSIX"));
718
719         snprintf (buf, sizeof (buf), "%.12g", x); 
720         root->add_property (X_("x"), buf);
721         snprintf (buf, sizeof (buf), "%.12g", y); 
722         root->add_property (X_("y"), buf);
723         root->add_property (X_("type"), Multi2dPanner::name);
724
725         /* XXX no meaningful automation yet */
726
727         return *root;
728 }
729
730 int
731 Multi2dPanner::set_state (const XMLNode& node)
732 {
733         const XMLProperty* prop;
734         float newx,newy;
735         LocaleGuard lg (X_("POSIX"));
736
737         newx = -1;
738         newy = -1;
739
740         if ((prop = node.property (X_("x")))) {
741                 newx = atof (prop->value().c_str());
742         }
743        
744         if ((prop = node.property (X_("y")))) {
745                 newy = atof (prop->value().c_str());
746         }
747         
748         if (x < 0 || y < 0) {
749                 error << _("badly-formed positional data for Multi2dPanner - ignored")
750                       << endmsg;
751                 return -1;
752         } 
753         
754         set_position (newx, newy);
755         return 0;
756 }
757
758 /*---------------------------------------------------------------------- */
759
760 Panner::Panner (string name, Session& s)
761         : _session (s)
762 {
763         set_name (name);
764
765         _linked = false;
766         _link_direction = SameDirection;
767         _bypassed = false;
768 }
769
770 Panner::~Panner ()
771 {
772 }
773
774 void
775 Panner::set_linked (bool yn)
776 {
777         if (yn != _linked) {
778                 _linked = yn;
779                 _session.set_dirty ();
780                 LinkStateChanged (); /* EMIT SIGNAL */
781         }
782 }
783
784 void
785 Panner::set_link_direction (LinkDirection ld)
786 {
787         if (ld != _link_direction) {
788                 _link_direction = ld;
789                 _session.set_dirty ();
790                 LinkStateChanged (); /* EMIT SIGNAL */
791         }
792 }
793
794 void
795 Panner::set_bypassed (bool yn)
796 {
797         if (yn != _bypassed) {
798                 _bypassed = yn;
799                 StateChanged ();
800         }
801 }
802
803 void
804 Panner::reset_to_default ()
805 {
806         vector<float> positions;
807
808         switch (outputs.size()) {
809         case 0:
810         case 1:
811                 return;
812         }
813
814         if (outputs.size() == 2) {
815                 switch (size()) {
816                 case 1:
817                         front()->set_position (0.5);
818                         front()->automation().reset_default (0.5);
819                         return;
820                         break;
821                 case 2:
822                         front()->set_position (0.0);
823                         front()->automation().reset_default (0.0);
824                         back()->set_position (1.0);
825                         back()->automation().reset_default (1.0);
826                         return;
827                 default:
828                         break;
829                 }
830         }
831         
832         vector<Output>::iterator o;
833         iterator p;
834
835         for (o = outputs.begin(), p = begin(); o != outputs.end() && p != end(); ++o, ++p) {
836                 (*p)->set_position ((*o).x, (*o).y);
837         }
838 }
839
840 void
841 Panner::reset_streampanner (uint32_t which)
842 {
843         if (which >= size() || which >= outputs.size()) {
844                 return;
845         }
846         
847         switch (outputs.size()) {
848         case 0:
849         case 1:
850                 return;
851
852         case 2:
853                 switch (size()) {
854                 case 1:
855                         /* stereo out, 1 stream, default = middle */
856                         front()->set_position (0.5);
857                         front()->automation().reset_default (0.5);
858                         break;
859                 case 2:
860                         /* stereo out, 2 streams, default = hard left/right */
861                         if (which == 0) {
862                                 front()->set_position (0.0);
863                                 front()->automation().reset_default (0.0);
864                         } else {
865                                 back()->set_position (1.0);
866                                 back()->automation().reset_default (1.0);
867                         }
868                         break;
869                 }
870                 return;
871
872         default:
873                 (*this)[which]->set_position (outputs[which].x, outputs[which].y);
874         }
875 }
876
877 void
878 Panner::reset (uint32_t nouts, uint32_t npans)
879 {
880         uint32_t n;
881         bool changed = false;
882         bool do_not_and_did_not_need_panning = ((nouts < 2) && (outputs.size() < 2));
883
884         /* if new and old config don't need panning, or if 
885            the config hasn't changed, we're done.
886         */
887
888         if (do_not_and_did_not_need_panning || 
889             ((nouts == outputs.size()) && (npans == size()))) {
890                 return;
891         } 
892
893         n = size();
894         clear ();
895
896         if (n != npans) {
897                 changed = true;
898         }
899
900         n = outputs.size();
901         outputs.clear ();
902
903         if (n != nouts) {
904                 changed = true;
905         }
906
907         if (nouts < 2) {
908                 goto send_changed;
909         }
910
911         switch (nouts) {
912         case 0:
913                 break;
914
915         case 1:
916                 fatal << _("programming error:")
917                       << X_("Panner::reset() called with a single output")
918                       << endmsg;
919                 /*NOTREACHED*/
920                 break;
921
922         case 2:
923                 /* line */
924                 outputs.push_back (Output (0, 0));
925                 outputs.push_back (Output (1.0, 0));
926
927                 for (n = 0; n < npans; ++n) {
928                         push_back (new EqualPowerStereoPanner (*this));
929                 }
930                 break;
931
932         case 3: // triangle
933                 outputs.push_back (Output  (0.5, 0));
934                 outputs.push_back (Output  (0, 1.0));
935                 outputs.push_back (Output  (1.0, 1.0));
936
937                 for (n = 0; n < npans; ++n) {
938                         push_back (new Multi2dPanner (*this));
939                 }
940
941                 break; 
942
943         case 4: // square
944                 outputs.push_back (Output  (0, 0));
945                 outputs.push_back (Output  (1.0, 0));
946                 outputs.push_back (Output  (1.0, 1.0));
947                 outputs.push_back (Output  (0, 1.0));
948
949                 for (n = 0; n < npans; ++n) {
950                         push_back (new Multi2dPanner (*this));
951                 }
952
953                 break;  
954
955         case 5: //square+offcenter center
956                 outputs.push_back (Output  (0, 0));
957                 outputs.push_back (Output  (1.0, 0));
958                 outputs.push_back (Output  (1.0, 1.0));
959                 outputs.push_back (Output  (0, 1.0));
960                 outputs.push_back (Output  (0.5, 0.75));
961
962                 for (n = 0; n < npans; ++n) {
963                         push_back (new Multi2dPanner (*this));
964                 }
965
966                 break;
967
968         default:
969                 /* XXX horrible placement. FIXME */
970                 for (n = 0; n < nouts; ++n) {
971                         outputs.push_back (Output (0.1 * n, 0.1 * n));
972                 }
973
974                 for (n = 0; n < npans; ++n) {
975                         push_back (new Multi2dPanner (*this));
976                 }
977
978                 break;
979         }
980
981         for (iterator x = begin(); x != end(); ++x) {
982                 (*x)->update ();
983         }
984
985         /* force hard left/right panning in a common case: 2in/2out 
986         */
987         
988         if (npans == 2 && outputs.size() == 2) {
989
990                 /* Do this only if we changed configuration, or our configuration
991                    appears to be the default set up (center).
992                 */
993
994                 float left;
995                 float right;
996
997                 front()->get_position (left);
998                 back()->get_position (right);
999
1000                 if (changed || ((left == 0.5) && (right == 0.5))) {
1001                 
1002                         front()->set_position (0.0);
1003                         front()->automation().reset_default (0.0);
1004                         
1005                         back()->set_position (1.0);
1006                         back()->automation().reset_default (1.0);
1007                         
1008                         changed = true;
1009                 }
1010         }
1011
1012   send_changed:
1013         if (changed) {
1014                 Changed (); /* EMIT SIGNAL */
1015         }
1016
1017         return;
1018 }
1019
1020 void
1021 Panner::remove (uint32_t which)
1022 {
1023         vector<StreamPanner*>::iterator i;
1024         for (i = begin(); i != end() && which; ++i, --which);
1025
1026         if (i != end()) {
1027                 delete *i;
1028                 erase (i);
1029         }
1030 }
1031
1032 void
1033 Panner::clear ()
1034 {
1035         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1036                 delete *i;
1037         }
1038
1039         vector<StreamPanner*>::clear ();
1040 }
1041
1042 void
1043 Panner::set_automation_style (AutoStyle style)
1044 {
1045         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1046                 (*i)->set_automation_style (style);
1047         }
1048         _session.set_dirty ();
1049 }       
1050
1051 void
1052 Panner::set_automation_state (AutoState state)
1053 {
1054         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1055                 (*i)->set_automation_state (state);
1056         }
1057         _session.set_dirty ();
1058 }       
1059
1060 AutoState
1061 Panner::automation_state () const
1062 {
1063         if (!empty()) {
1064                 return front()->automation().automation_state ();
1065         } else {
1066                 return Off;
1067         }
1068 }
1069
1070 AutoStyle
1071 Panner::automation_style () const
1072 {
1073         if (!empty()) {
1074                 return front()->automation().automation_style ();
1075         } else {
1076                 return Absolute;
1077         }
1078 }
1079
1080 void
1081 Panner::transport_stopped (nframes_t frame)
1082 {
1083         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1084                 (*i)->transport_stopped (frame);
1085         }
1086 }       
1087
1088 void
1089 Panner::snapshot (nframes_t now)
1090 {
1091         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1092                 (*i)->snapshot (now);
1093         }
1094 }       
1095
1096 void
1097 Panner::clear_automation ()
1098 {
1099         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1100                 (*i)->automation().clear ();
1101         }
1102         _session.set_dirty ();
1103 }       
1104
1105 struct PanPlugins {
1106     string name;
1107     uint32_t nouts;
1108     StreamPanner* (*factory)(Panner&);
1109 };
1110
1111 PanPlugins pan_plugins[] = {
1112         { EqualPowerStereoPanner::name, 2, EqualPowerStereoPanner::factory },
1113         { Multi2dPanner::name, 3, Multi2dPanner::factory },
1114         { string (""), 0, 0 }
1115 };
1116
1117 XMLNode&
1118 Panner::get_state (void)
1119 {
1120         return state (true);
1121 }
1122
1123 XMLNode&
1124 Panner::state (bool full)
1125 {
1126         XMLNode* root = new XMLNode (X_("Panner"));
1127         char buf[32];
1128
1129         root->add_property (X_("linked"), (_linked ? "yes" : "no"));
1130         root->add_property (X_("link_direction"), enum_2_string (_link_direction));
1131         root->add_property (X_("bypassed"), (bypassed() ? "yes" : "no"));
1132
1133         /* add each output */
1134
1135         for (vector<Panner::Output>::iterator o = outputs.begin(); o != outputs.end(); ++o) {
1136                 XMLNode* onode = new XMLNode (X_("Output"));
1137                 snprintf (buf, sizeof (buf), "%.12g", (*o).x);
1138                 onode->add_property (X_("x"), buf);
1139                 snprintf (buf, sizeof (buf), "%.12g", (*o).y);
1140                 onode->add_property (X_("y"), buf);
1141                 root->add_child_nocopy (*onode);
1142         }
1143
1144         for (vector<StreamPanner*>::const_iterator i = begin(); i != end(); ++i) {
1145                 root->add_child_nocopy ((*i)->state (full));
1146         }
1147
1148         return *root;
1149 }
1150
1151 int
1152 Panner::set_state (const XMLNode& node)
1153 {
1154         XMLNodeList nlist;
1155         XMLNodeConstIterator niter;
1156         const XMLProperty *prop;
1157         uint32_t i;
1158         StreamPanner* sp;
1159         LocaleGuard lg (X_("POSIX"));
1160
1161         clear ();
1162         outputs.clear ();
1163
1164         if ((prop = node.property (X_("linked"))) != 0) {
1165                 set_linked (string_is_affirmative (prop->value()));
1166         }
1167
1168
1169         if ((prop = node.property (X_("bypassed"))) != 0) {
1170                 set_bypassed (string_is_affirmative (prop->value()));
1171         }
1172
1173         if ((prop = node.property (X_("link_direction"))) != 0) {
1174                 LinkDirection ld; /* here to provide type information */
1175                 set_link_direction (LinkDirection (string_2_enum (prop->value(), ld)));
1176         }
1177
1178         nlist = node.children();
1179
1180         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1181                 if ((*niter)->name() == X_("Output")) {
1182                         
1183                         float x, y;
1184                         
1185                         prop = (*niter)->property (X_("x"));
1186                         sscanf (prop->value().c_str(), "%g", &x);
1187                         
1188                         prop = (*niter)->property (X_("y"));
1189                         sscanf (prop->value().c_str(), "%g", &y);
1190                         
1191                         outputs.push_back (Output (x, y));
1192                 }
1193         }
1194
1195         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1196
1197                 if ((*niter)->name() == X_("StreamPanner")) {
1198                 
1199                         if ((prop = (*niter)->property (X_("type")))) {
1200                                 
1201                                 for (i = 0; pan_plugins[i].factory; ++i) {
1202                                         if (prop->value() == pan_plugins[i].name) {
1203                                                 
1204                                                 
1205                                                 /* note that we assume that all the stream panners
1206                                                    are of the same type. pretty good
1207                                                    assumption, but its still an assumption.
1208                                                 */
1209                                                 
1210                                                 sp = pan_plugins[i].factory (*this);
1211                                                 
1212                                                 if (sp->set_state (**niter) == 0) {
1213                                                         push_back (sp);
1214                                                 }
1215                                                 
1216                                                 break;
1217                                         }
1218                                 }
1219                                 
1220                                 
1221                                 if (!pan_plugins[i].factory) {
1222                                         error << string_compose (_("Unknown panner plugin \"%1\" found in pan state - ignored"),
1223                                                           prop->value())
1224                                               << endmsg;
1225                                 }
1226
1227                         } else {
1228                                 error << _("panner plugin node has no type information!")
1229                                       << endmsg;
1230                                 return -1;
1231                         }
1232
1233                 }       
1234         }
1235
1236         /* don't try to do old-school automation loading if it wasn't marked as existing */
1237
1238         if ((prop = node.property (X_("automation")))) {
1239
1240                 /* automation path is relative */
1241                 
1242                 automation_path = Glib::build_filename(_session.automation_dir(), prop->value ());
1243         } 
1244
1245         return 0;
1246 }
1247
1248
1249
1250 bool
1251 Panner::touching () const
1252 {
1253         for (vector<StreamPanner*>::const_iterator i = begin(); i != end(); ++i) {
1254                 if ((*i)->automation().touching ()) {
1255                         return true;
1256                 }
1257         }
1258
1259         return false;
1260 }
1261
1262 void
1263 Panner::set_position (float xpos, StreamPanner& orig)
1264 {
1265         float xnow;
1266         float xdelta ;
1267         float xnew;
1268
1269         orig.get_position (xnow);
1270         xdelta = xpos - xnow;
1271         
1272         if (_link_direction == SameDirection) {
1273
1274                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1275                         if (*i == &orig) {
1276                                 (*i)->set_position (xpos, true);
1277                         } else {
1278                                 (*i)->get_position (xnow);
1279                                 xnew = min (1.0f, xnow + xdelta);
1280                                 xnew = max (0.0f, xnew);
1281                                 (*i)->set_position (xnew, true);
1282                         }
1283                 }
1284
1285         } else {
1286
1287                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1288                         if (*i == &orig) {
1289                                 (*i)->set_position (xpos, true);
1290                         } else {
1291                                 (*i)->get_position (xnow);
1292                                 xnew = min (1.0f, xnow - xdelta);
1293                                 xnew = max (0.0f, xnew);
1294                                 (*i)->set_position (xnew, true);
1295                         }
1296                 }
1297         }
1298 }
1299
1300 void
1301 Panner::set_position (float xpos, float ypos, StreamPanner& orig)
1302 {
1303         float xnow, ynow;
1304         float xdelta, ydelta;
1305         float xnew, ynew;
1306
1307         orig.get_position (xnow, ynow);
1308         xdelta = xpos - xnow;
1309         ydelta = ypos - ynow;
1310         
1311         if (_link_direction == SameDirection) {
1312
1313                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1314                         if (*i == &orig) {
1315                                 (*i)->set_position (xpos, ypos, true);
1316                         } else {
1317                                 (*i)->get_position (xnow, ynow);
1318
1319                                 xnew = min (1.0f, xnow + xdelta);
1320                                 xnew = max (0.0f, xnew);
1321
1322                                 ynew = min (1.0f, ynow + ydelta);
1323                                 ynew = max (0.0f, ynew);
1324
1325                                 (*i)->set_position (xnew, ynew, true);
1326                         }
1327                 }
1328
1329         } else {
1330
1331                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1332                         if (*i == &orig) {
1333                                 (*i)->set_position (xpos, ypos, true);
1334                         } else {
1335                                 (*i)->get_position (xnow, ynow);
1336                                 
1337                                 xnew = min (1.0f, xnow - xdelta);
1338                                 xnew = max (0.0f, xnew);
1339
1340                                 ynew = min (1.0f, ynow - ydelta);
1341                                 ynew = max (0.0f, ynew);
1342
1343                                 (*i)->set_position (xnew, ynew, true);
1344                         }
1345                 }
1346         }
1347 }
1348
1349 void
1350 Panner::set_position (float xpos, float ypos, float zpos, StreamPanner& orig)
1351 {
1352         float xnow, ynow, znow;
1353         float xdelta, ydelta, zdelta;
1354         float xnew, ynew, znew;
1355
1356         orig.get_position (xnow, ynow, znow);
1357         xdelta = xpos - xnow;
1358         ydelta = ypos - ynow;
1359         zdelta = zpos - znow;
1360
1361         if (_link_direction == SameDirection) {
1362
1363                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1364                         if (*i == &orig) {
1365                                 (*i)->set_position (xpos, ypos, zpos, true);
1366                         } else {
1367                                 (*i)->get_position (xnow, ynow, znow);
1368                                 
1369                                 xnew = min (1.0f, xnow + xdelta);
1370                                 xnew = max (0.0f, xnew);
1371
1372                                 ynew = min (1.0f, ynow + ydelta);
1373                                 ynew = max (0.0f, ynew);
1374
1375                                 znew = min (1.0f, znow + zdelta);
1376                                 znew = max (0.0f, znew);
1377
1378                                 (*i)->set_position (xnew, ynew, znew, true);
1379                         }
1380                 }
1381
1382         } else {
1383
1384                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1385                         if (*i == &orig) {
1386                                 (*i)->set_position (xpos, ypos, true);
1387                         } else {
1388                                 (*i)->get_position (xnow, ynow, znow);
1389
1390                                 xnew = min (1.0f, xnow - xdelta);
1391                                 xnew = max (0.0f, xnew);
1392
1393                                 ynew = min (1.0f, ynow - ydelta);
1394                                 ynew = max (0.0f, ynew);
1395
1396                                 znew = min (1.0f, znow + zdelta);
1397                                 znew = max (0.0f, znew);
1398
1399                                 (*i)->set_position (xnew, ynew, znew, true);
1400                         }
1401                 }
1402         }
1403 }
1404
1405 /* old school automation handling */
1406
1407 void
1408 Panner::set_name (string str)
1409 {
1410         automation_path = Glib::build_filename(_session.automation_dir(), 
1411                 _session.snap_name() + "-pan-" + legalize_for_path (str) + ".automation");
1412 }
1413
1414 int
1415 Panner::load ()
1416 {
1417         char line[128];
1418         uint32_t linecnt = 0;
1419         float version;
1420         iterator sp;
1421         LocaleGuard lg (X_("POSIX"));
1422
1423         if (automation_path.length() == 0) {
1424                 return 0;
1425         }
1426         
1427         if (access (automation_path.c_str(), F_OK)) {
1428                 return 0;
1429         }
1430
1431         ifstream in (automation_path.c_str());
1432
1433         if (!in) {
1434                 error << string_compose (_("cannot open pan automation file %1 (%2)"),
1435                                   automation_path, strerror (errno))
1436                       << endmsg;
1437                 return -1;
1438         }
1439
1440         sp = begin();
1441
1442         while (in.getline (line, sizeof(line), '\n')) {
1443
1444                 if (++linecnt == 1) {
1445                         if (memcmp (line, X_("version"), 7) == 0) {
1446                                 if (sscanf (line, "version %f", &version) != 1) {
1447                                         error << string_compose(_("badly formed version number in pan automation event file \"%1\""), automation_path) << endmsg;
1448                                         return -1;
1449                                 }
1450                         } else {
1451                                 error << string_compose(_("no version information in pan automation event file \"%1\" (first line = %2)"), 
1452                                                  automation_path, line) << endmsg;
1453                                 return -1;
1454                         }
1455
1456                         continue;
1457                 }
1458
1459                 if (strlen (line) == 0 || line[0] == '#') {
1460                         continue;
1461                 }
1462
1463                 if (strcmp (line, "begin") == 0) {
1464                         
1465                         if (sp == end()) {
1466                                 error << string_compose (_("too many panner states found in pan automation file %1"),
1467                                                   automation_path)
1468                                       << endmsg;
1469                                 return -1;
1470                         }
1471
1472                         if ((*sp)->load (in, automation_path, linecnt)) {
1473                                 return -1;
1474                         }
1475                         
1476                         ++sp;
1477                 }
1478         }
1479
1480         return 0;
1481 }