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