merge from trunk
[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 (*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 (jack_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 (jack_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' << (jack_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                 jack_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, jack_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                 jack_nframes_t limit = min ((jack_nframes_t)64, nframes);
314                 jack_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                 jack_nframes_t limit = min ((jack_nframes_t)64, nframes);
364                 jack_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                                               jack_nframes_t start, jack_nframes_t end, jack_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 (jack_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 (jack_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 (jack_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
547         return *root;
548 }
549
550 int
551 EqualPowerStereoPanner::set_state (const XMLNode& node)
552 {
553         const XMLProperty* prop;
554         int x;
555         float pos;
556         LocaleGuard lg (X_("POSIX"));
557
558         if ((prop = node.property (X_("x")))) {
559                 pos = atof (prop->value().c_str());
560                 set_position (pos, true);
561         } 
562
563         if ((prop = node.property (X_("automation-state")))) {
564                 sscanf (prop->value().c_str(), "0x%x", &x);
565                 _automation.set_automation_state ((AutoState) x);
566
567                 if (x != Off) {
568                         set_position (_automation.eval (parent.session().transport_frame()));
569                 }
570         }
571
572         if ((prop = node.property (X_("automation-style")))) {
573                 sscanf (prop->value().c_str(), "0x%x", &x);
574                 _automation.set_automation_style ((AutoStyle) x);
575         }
576
577         StreamPanner::set_state (node);
578         
579         return 0;
580 }
581
582 /*----------------------------------------------------------------------*/
583
584 Multi2dPanner::Multi2dPanner (Panner& p)
585         : StreamPanner (p), _automation (0.0, 1.0, 0.5) // XXX useless
586 {
587         update ();
588 }
589
590 Multi2dPanner::~Multi2dPanner ()
591 {
592 }
593
594 void
595 Multi2dPanner::snapshot (jack_nframes_t now)
596 {
597         // how?
598 }
599
600 void
601 Multi2dPanner::transport_stopped (jack_nframes_t frame)
602 {
603         //what?
604 }
605
606 void
607 Multi2dPanner::set_automation_style (AutoStyle style)
608 {
609         //what?
610 }
611
612 void
613 Multi2dPanner::set_automation_state (AutoState state)
614 {
615         // what?
616 }
617
618 void
619 Multi2dPanner::update ()
620 {
621         static const float BIAS = FLT_MIN;
622         uint32_t i;
623         uint32_t nouts = parent.outputs.size();
624         float dsq[nouts];
625         float f, fr;
626         vector<pan_t> pans;
627
628         f = 0.0f;
629
630         for (i = 0; i < nouts; i++) {
631                 dsq[i] = ((x - parent.outputs[i].x) * (x - parent.outputs[i].x) + (y - parent.outputs[i].y) * (y - parent.outputs[i].y) + BIAS);
632                 if (dsq[i] < 0.0) {
633                         dsq[i] = 0.0;
634                 }
635                 f += dsq[i] * dsq[i];
636         }
637 #ifdef __APPLE__
638         // terrible hack to support OSX < 10.3.9 builds
639         fr = (float) (1.0 / sqrt((double)f));
640 #else
641         fr = 1.0 / sqrtf(f);
642 #endif  
643         for (i = 0; i < nouts; ++i) {
644                 parent.outputs[i].desired_pan = 1.0f - (dsq[i] * fr);
645         }
646
647         effective_x = x;
648 }
649
650 void
651 Multi2dPanner::distribute (Sample* src, Sample** obufs, gain_t gain_coeff, jack_nframes_t nframes)
652 {
653         Sample* dst;
654         pan_t pan;
655         vector<Panner::Output>::iterator o;
656         uint32_t n;
657
658         if (_muted) {
659                 return;
660         }
661
662
663         for (n = 0, o = parent.outputs.begin(); o != parent.outputs.end(); ++o, ++n) {
664
665                 dst = obufs[n];
666         
667 #ifdef CAN_INTERP
668                 if (fabsf ((delta = (left_interp - desired_left))) > 0.002) { // about 1 degree of arc 
669                         
670                         /* interpolate over 64 frames or nframes, whichever is smaller */
671                         
672                         jack_nframes_t limit = min ((jack_nframes_t)64, nframes);
673                         jack_nframes_t n;
674                         
675                         delta = -(delta / (float) (limit));
676                 
677                         for (n = 0; n < limit; n++) {
678                                 left_interp = left_interp + delta;
679                                 left = left_interp + 0.9 * (left - left_interp);
680                                 dst[n] += src[n] * left * gain_coeff;
681                         }
682                         
683                         pan = left * gain_coeff;
684                         
685                         for (; n < nframes; ++n) {
686                                 dst[n] += src[n] * pan;
687                         }
688                         
689                 } else {
690
691 #else                   
692                         pan = (*o).desired_pan;
693                         
694                         if ((pan *= gain_coeff) != 1.0f) {
695                                 
696                                 if (pan != 0.0f) {
697                                         
698                                         for (jack_nframes_t n = 0; n < nframes; ++n) {
699                                                 dst[n] += src[n] * pan;
700                                         }      
701                                         
702                                 } 
703
704                                 
705                         } else {
706                                 
707                                 for (jack_nframes_t n = 0; n < nframes; ++n) {
708                                         dst[n] += src[n];
709                                 }      
710
711                         }
712 #endif
713 #ifdef CAN_INTERP
714                 }
715 #endif
716         }
717         
718         return;
719 }
720
721 void
722 Multi2dPanner::distribute_automated (Sample* src, Sample** obufs, 
723                                      jack_nframes_t start, jack_nframes_t end, jack_nframes_t nframes,
724                                      pan_t** buffers)
725 {
726         if (_muted) {
727                 return;
728         }
729
730         /* what ? */
731
732         return;
733 }
734
735 StreamPanner*
736 Multi2dPanner::factory (Panner& p)
737 {
738         return new Multi2dPanner (p);
739 }
740
741 int
742 Multi2dPanner::load (istream& in, string path, uint32_t& linecnt)
743 {
744         return 0;
745 }
746
747 int
748 Multi2dPanner::save (ostream& out) const
749 {
750         return 0;
751 }
752
753 XMLNode&
754 Multi2dPanner::get_state (void)
755 {
756         return state (true);
757 }
758
759 XMLNode&
760 Multi2dPanner::state (bool full_state)
761 {
762         XMLNode* root = new XMLNode ("StreamPanner");
763         char buf[64];
764         LocaleGuard lg (X_("POSIX"));
765
766         snprintf (buf, sizeof (buf), "%.12g", x); 
767         root->add_property (X_("x"), buf);
768         snprintf (buf, sizeof (buf), "%.12g", y); 
769         root->add_property (X_("y"), buf);
770         root->add_property (X_("type"), Multi2dPanner::name);
771
772         return *root;
773 }
774
775 int
776 Multi2dPanner::set_state (const XMLNode& node)
777 {
778         const XMLProperty* prop;
779         float newx,newy;
780         LocaleGuard lg (X_("POSIX"));
781
782         newx = -1;
783         newy = -1;
784
785         if ((prop = node.property (X_("x")))) {
786                 newx = atof (prop->value().c_str());
787         }
788        
789         if ((prop = node.property (X_("y")))) {
790                 newy = atof (prop->value().c_str());
791         }
792         
793         if (x < 0 || y < 0) {
794                 error << _("badly-formed positional data for Multi2dPanner - ignored")
795                       << endmsg;
796                 return -1;
797         } 
798         
799         set_position (newx, newy);
800         return 0;
801 }
802
803 /*---------------------------------------------------------------------- */
804
805 Panner::Panner (string name, Session& s)
806         : _session (s)
807 {
808         set_name (name);
809         _linked = false;
810         _link_direction = SameDirection;
811         _bypassed = false;
812 }
813
814 Panner::~Panner ()
815 {
816 }
817
818 void
819 Panner::set_linked (bool yn)
820 {
821         if (yn != _linked) {
822                 _linked = yn;
823                 _session.set_dirty ();
824                 LinkStateChanged (); /* EMIT SIGNAL */
825         }
826 }
827
828 void
829 Panner::set_link_direction (LinkDirection ld)
830 {
831         if (ld != _link_direction) {
832                 _link_direction = ld;
833                 _session.set_dirty ();
834                 LinkStateChanged (); /* EMIT SIGNAL */
835         }
836 }
837
838 void
839 Panner::set_name (string str)
840 {
841         automation_path = _session.automation_dir();
842         automation_path += _session.snap_name();
843         automation_path += "-pan-";
844         automation_path += legalize_for_path (str);
845         automation_path += ".automation";
846 }
847
848
849 void
850 Panner::set_bypassed (bool yn)
851 {
852         if (yn != _bypassed) {
853                 _bypassed = yn;
854                 StateChanged ();
855         }
856 }
857
858
859 void
860 Panner::reset (uint32_t nouts, uint32_t npans)
861 {
862         uint32_t n;
863         bool changed = false;
864
865
866         if (nouts < 2 || (nouts == outputs.size() && npans == size())) {
867                 return;
868         } 
869
870         n = size();
871         clear ();
872
873         if (n != npans) {
874                 changed = true;
875         }
876
877         n = outputs.size();
878         outputs.clear ();
879
880         if (n != nouts) {
881                 changed = true;
882         }
883
884         switch (nouts) {
885         case 0:
886                 break;
887
888         case 1:
889                 fatal << _("programming error:")
890                       << X_("Panner::reset() called with a single output")
891                       << endmsg;
892                 /*NOTREACHED*/
893                 break;
894
895         case 2:
896                 /* line */
897                 outputs.push_back (Output (0, 0));
898                 outputs.push_back (Output (1.0, 0));
899
900                 for (n = 0; n < npans; ++n) {
901                         push_back (new EqualPowerStereoPanner (*this));
902                 }
903                 break;
904
905         case 3: // triangle
906                 outputs.push_back (Output  (0.5, 0));
907                 outputs.push_back (Output  (0, 1.0));
908                 outputs.push_back (Output  (1.0, 1.0));
909
910                 for (n = 0; n < npans; ++n) {
911                         push_back (new Multi2dPanner (*this));
912                 }
913
914                 break; 
915
916         case 4: // square
917                 outputs.push_back (Output  (0, 0));
918                 outputs.push_back (Output  (1.0, 0));
919                 outputs.push_back (Output  (1.0, 1.0));
920                 outputs.push_back (Output  (0, 1.0));
921
922                 for (n = 0; n < npans; ++n) {
923                         push_back (new Multi2dPanner (*this));
924                 }
925
926                 break;  
927
928         case 5: //square+offcenter center
929                 outputs.push_back (Output  (0, 0));
930                 outputs.push_back (Output  (1.0, 0));
931                 outputs.push_back (Output  (1.0, 1.0));
932                 outputs.push_back (Output  (0, 1.0));
933                 outputs.push_back (Output  (0.5, 0.75));
934
935                 for (n = 0; n < npans; ++n) {
936                         push_back (new Multi2dPanner (*this));
937                 }
938
939                 break;
940
941         default:
942                 /* XXX horrible placement. FIXME */
943                 for (n = 0; n < nouts; ++n) {
944                         outputs.push_back (Output (0.1 * n, 0.1 * n));
945                 }
946
947                 for (n = 0; n < npans; ++n) {
948                         push_back (new Multi2dPanner (*this));
949                 }
950
951                 break;
952         }
953
954         for (iterator x = begin(); x != end(); ++x) {
955                 (*x)->update ();
956         }
957
958         /* force hard left/right panning in a common case: 2in/2out 
959         */
960         
961         if (npans == 2 && outputs.size() == 2) {
962
963                 /* Do this only if we changed configuration, or our configuration
964                    appears to be the default set up (center).
965                 */
966
967                 float left;
968                 float right;
969
970                 front()->get_position (left);
971                 back()->get_position (right);
972
973                 if (changed || ((left == 0.5) && (right == 0.5))) {
974                 
975                         front()->set_position (0.0);
976                         front()->automation().reset_default (0.0);
977                         
978                         back()->set_position (1.0);
979                         back()->automation().reset_default (1.0);
980                         
981                         changed = true;
982                 }
983         }
984
985         if (changed) {
986                 Changed (); /* EMIT SIGNAL */
987         }
988
989         return;
990 }
991
992 void
993 Panner::remove (uint32_t which)
994 {
995         vector<StreamPanner*>::iterator i;
996         for (i = begin(); i != end() && which; ++i, --which);
997
998         if (i != end()) {
999                 delete *i;
1000                 erase (i);
1001         }
1002 }
1003
1004 void
1005 Panner::clear ()
1006 {
1007         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1008                 delete *i;
1009         }
1010
1011         vector<StreamPanner*>::clear ();
1012 }
1013
1014 void
1015 Panner::set_automation_style (AutoStyle style)
1016 {
1017         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1018                 (*i)->set_automation_style (style);
1019         }
1020         _session.set_dirty ();
1021 }       
1022
1023 void
1024 Panner::set_automation_state (AutoState state)
1025 {
1026         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1027                 (*i)->set_automation_state (state);
1028         }
1029         _session.set_dirty ();
1030 }       
1031
1032 AutoState
1033 Panner::automation_state () const
1034 {
1035         if (!empty()) {
1036                 return front()->automation().automation_state ();
1037         } else {
1038                 return Off;
1039         }
1040 }
1041
1042 AutoStyle
1043 Panner::automation_style () const
1044 {
1045         if (!empty()) {
1046                 return front()->automation().automation_style ();
1047         } else {
1048                 return Absolute;
1049         }
1050 }
1051
1052 void
1053 Panner::transport_stopped (jack_nframes_t frame)
1054 {
1055         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1056                 (*i)->transport_stopped (frame);
1057         }
1058 }       
1059
1060 void
1061 Panner::snapshot (jack_nframes_t now)
1062 {
1063         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1064                 (*i)->snapshot (now);
1065         }
1066 }       
1067
1068 void
1069 Panner::clear_automation ()
1070 {
1071         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1072                 (*i)->automation().clear ();
1073         }
1074         _session.set_dirty ();
1075 }       
1076
1077 int
1078 Panner::save () const
1079 {
1080         ofstream out (automation_path.c_str());
1081         
1082         if (!out) {
1083                 error << string_compose (_("cannot open pan automation file \"%1\" for saving (%s)"), automation_path, strerror (errno))
1084                       << endmsg;
1085                 return -1;
1086         }
1087
1088         out << X_("version ") << current_automation_version_number << endl;
1089
1090         for (vector<StreamPanner*>::const_iterator i = begin(); i != end(); ++i) {
1091                 if ((*i)->save (out)) {
1092                         return -1;
1093                 }
1094         }
1095
1096         return 0;
1097 }
1098
1099 int
1100 Panner::load ()
1101 {
1102         char line[128];
1103         uint32_t linecnt = 0;
1104         float version;
1105         iterator sp;
1106         LocaleGuard lg (X_("POSIX"));
1107
1108         if (automation_path.length() == 0) {
1109                 return 0;
1110         }
1111         
1112         if (access (automation_path.c_str(), F_OK)) {
1113                 return 0;
1114         }
1115
1116         ifstream in (automation_path.c_str());
1117
1118         if (!in) {
1119                 error << string_compose (_("cannot open pan automation file %1 (%2)"),
1120                                   automation_path, strerror (errno))
1121                       << endmsg;
1122                 return -1;
1123         }
1124
1125         sp = begin();
1126
1127         while (in.getline (line, sizeof(line), '\n')) {
1128
1129                 if (++linecnt == 1) {
1130                         if (memcmp (line, X_("version"), 7) == 0) {
1131                                 if (sscanf (line, "version %f", &version) != 1) {
1132                                         error << string_compose(_("badly formed version number in pan automation event file \"%1\""), automation_path) << endmsg;
1133                                         return -1;
1134                                 }
1135                         } else {
1136                                 error << string_compose(_("no version information in pan automation event file \"%1\" (first line = %2)"), 
1137                                                  automation_path, line) << endmsg;
1138                                 return -1;
1139                         }
1140
1141                         if (version != current_automation_version_number) {
1142                                 error << string_compose(_("mismatched pan automation event file version (%1)"), version) << endmsg;
1143                                 return -1;
1144                         }
1145
1146                         continue;
1147                 }
1148
1149                 if (strlen (line) == 0 || line[0] == '#') {
1150                         continue;
1151                 }
1152
1153                 if (strcmp (line, "begin") == 0) {
1154                         
1155                         if (sp == end()) {
1156                                 error << string_compose (_("too many panner states found in pan automation file %1"),
1157                                                   automation_path)
1158                                       << endmsg;
1159                                 return -1;
1160                         }
1161
1162                         if ((*sp)->load (in, automation_path, linecnt)) {
1163                                 return -1;
1164                         }
1165                         
1166                         ++sp;
1167                 }
1168         }
1169
1170         return 0;
1171 }
1172
1173 struct PanPlugins {
1174     string name;
1175     uint32_t nouts;
1176     StreamPanner* (*factory)(Panner&);
1177 };
1178
1179 PanPlugins pan_plugins[] = {
1180         { EqualPowerStereoPanner::name, 2, EqualPowerStereoPanner::factory },
1181         { Multi2dPanner::name, 3, Multi2dPanner::factory },
1182         { string (""), 0, 0 }
1183 };
1184
1185 XMLNode&
1186 Panner::get_state (void)
1187 {
1188         return state (true);
1189 }
1190
1191 XMLNode&
1192 Panner::state (bool full)
1193 {
1194         XMLNode* root = new XMLNode (X_("Panner"));
1195         char buf[32];
1196
1197         for (iterator p = begin(); p != end(); ++p) {
1198                 root->add_child_nocopy ((*p)->state (full));
1199         }
1200
1201         root->add_property (X_("linked"), (_linked ? "yes" : "no"));
1202         snprintf (buf, sizeof (buf), "%d", _link_direction);
1203         root->add_property (X_("link_direction"), buf);
1204         root->add_property (X_("bypassed"), (bypassed() ? "yes" : "no"));
1205
1206         /* add each output */
1207
1208         for (vector<Panner::Output>::iterator o = outputs.begin(); o != outputs.end(); ++o) {
1209                 XMLNode* onode = new XMLNode (X_("Output"));
1210                 snprintf (buf, sizeof (buf), "%.12g", (*o).x);
1211                 onode->add_property (X_("x"), buf);
1212                 snprintf (buf, sizeof (buf), "%.12g", (*o).y);
1213                 onode->add_property (X_("y"), buf);
1214                 root->add_child_nocopy (*onode);
1215         }
1216
1217         if (full) {
1218                 if (save () == 0) {
1219                         root->add_property (X_("automation"), Glib::path_get_basename (automation_path));
1220                 }
1221         }
1222
1223         return *root;
1224 }
1225
1226 int
1227 Panner::set_state (const XMLNode& node)
1228 {
1229         XMLNodeList nlist;
1230         XMLNodeConstIterator niter;
1231         const XMLProperty *prop;
1232         uint32_t i;
1233         StreamPanner* sp;
1234         LocaleGuard lg (X_("POSIX"));
1235
1236         clear ();
1237         outputs.clear ();
1238
1239         if ((prop = node.property (X_("linked"))) != 0) {
1240                 set_linked (prop->value() == "yes");
1241         }
1242
1243
1244         if ((prop = node.property (X_("bypassed"))) != 0) {
1245                 set_bypassed (prop->value() == "yes");
1246         }
1247
1248         if ((prop = node.property (X_("link_direction"))) != 0) {
1249                 sscanf (prop->value().c_str(), "%d", &i);
1250                 set_link_direction ((LinkDirection) (i));
1251         }
1252
1253         nlist = node.children();
1254
1255         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1256                 if ((*niter)->name() == X_("Output")) {
1257                         
1258                         float x, y;
1259                         
1260                         prop = (*niter)->property (X_("x"));
1261                         sscanf (prop->value().c_str(), "%g", &x);
1262                         
1263                         prop = (*niter)->property (X_("y"));
1264                         sscanf (prop->value().c_str(), "%g", &y);
1265                         
1266                         outputs.push_back (Output (x, y));
1267                 }
1268         }
1269
1270         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1271
1272                 if ((*niter)->name() == X_("StreamPanner")) {
1273                 
1274                         if ((prop = (*niter)->property (X_("type")))) {
1275                                 
1276                                 for (i = 0; pan_plugins[i].factory; ++i) {
1277                                         if (prop->value() == pan_plugins[i].name) {
1278                                                 
1279                                                 
1280                                                 /* note that we assume that all the stream panners
1281                                                    are of the same type. pretty good
1282                                                    assumption, but its still an assumption.
1283                                                 */
1284                                                 
1285                                                 sp = pan_plugins[i].factory (*this);
1286                                                 
1287                                                 if (sp->set_state (**niter) == 0) {
1288                                                         push_back (sp);
1289                                                 }
1290                                                 
1291                                                 break;
1292                                         }
1293                                 }
1294                                 
1295                                 
1296                                 if (!pan_plugins[i].factory) {
1297                                         error << string_compose (_("Unknown panner plugin \"%1\" found in pan state - ignored"),
1298                                                           prop->value())
1299                                               << endmsg;
1300                                 }
1301
1302                         } else {
1303                                 error << _("panner plugin node has no type information!")
1304                                       << endmsg;
1305                                 return -1;
1306                         }
1307
1308                 }       
1309         }
1310
1311         /* don't try to load automation if it wasn't marked as existing */
1312
1313         if ((prop = node.property (X_("automation")))) {
1314
1315                 /* automation path is relative */
1316                 
1317                 automation_path = _session.automation_dir();
1318                 automation_path += prop->value ();
1319         } 
1320
1321         return 0;
1322 }
1323
1324
1325
1326 bool
1327 Panner::touching () const
1328 {
1329         for (vector<StreamPanner*>::const_iterator i = begin(); i != end(); ++i) {
1330                 if ((*i)->automation().touching ()) {
1331                         return true;
1332                 }
1333         }
1334
1335         return false;
1336 }
1337
1338 void
1339 Panner::set_position (float xpos, StreamPanner& orig)
1340 {
1341         float xnow;
1342         float xdelta ;
1343         float xnew;
1344
1345         orig.get_position (xnow);
1346         xdelta = xpos - xnow;
1347         
1348         if (_link_direction == SameDirection) {
1349
1350                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1351                         if (*i == &orig) {
1352                                 (*i)->set_position (xpos, true);
1353                         } else {
1354                                 (*i)->get_position (xnow);
1355                                 xnew = min (1.0f, xnow + xdelta);
1356                                 xnew = max (0.0f, xnew);
1357                                 (*i)->set_position (xnew, true);
1358                         }
1359                 }
1360
1361         } else {
1362
1363                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1364                         if (*i == &orig) {
1365                                 (*i)->set_position (xpos, true);
1366                         } else {
1367                                 (*i)->get_position (xnow);
1368                                 xnew = min (1.0f, xnow - xdelta);
1369                                 xnew = max (0.0f, xnew);
1370                                 (*i)->set_position (xnew, true);
1371                         }
1372                 }
1373         }
1374 }
1375
1376 void
1377 Panner::set_position (float xpos, float ypos, StreamPanner& orig)
1378 {
1379         float xnow, ynow;
1380         float xdelta, ydelta;
1381         float xnew, ynew;
1382
1383         orig.get_position (xnow, ynow);
1384         xdelta = xpos - xnow;
1385         ydelta = ypos - ynow;
1386         
1387         if (_link_direction == SameDirection) {
1388
1389                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1390                         if (*i == &orig) {
1391                                 (*i)->set_position (xpos, ypos, true);
1392                         } else {
1393                                 (*i)->get_position (xnow, ynow);
1394
1395                                 xnew = min (1.0f, xnow + xdelta);
1396                                 xnew = max (0.0f, xnew);
1397
1398                                 ynew = min (1.0f, ynow + ydelta);
1399                                 ynew = max (0.0f, ynew);
1400
1401                                 (*i)->set_position (xnew, ynew, true);
1402                         }
1403                 }
1404
1405         } else {
1406
1407                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1408                         if (*i == &orig) {
1409                                 (*i)->set_position (xpos, ypos, true);
1410                         } else {
1411                                 (*i)->get_position (xnow, ynow);
1412                                 
1413                                 xnew = min (1.0f, xnow - xdelta);
1414                                 xnew = max (0.0f, xnew);
1415
1416                                 ynew = min (1.0f, ynow - ydelta);
1417                                 ynew = max (0.0f, ynew);
1418
1419                                 (*i)->set_position (xnew, ynew, true);
1420                         }
1421                 }
1422         }
1423 }
1424
1425 void
1426 Panner::set_position (float xpos, float ypos, float zpos, StreamPanner& orig)
1427 {
1428         float xnow, ynow, znow;
1429         float xdelta, ydelta, zdelta;
1430         float xnew, ynew, znew;
1431
1432         orig.get_position (xnow, ynow, znow);
1433         xdelta = xpos - xnow;
1434         ydelta = ypos - ynow;
1435         zdelta = zpos - znow;
1436
1437         if (_link_direction == SameDirection) {
1438
1439                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1440                         if (*i == &orig) {
1441                                 (*i)->set_position (xpos, ypos, zpos, true);
1442                         } else {
1443                                 (*i)->get_position (xnow, ynow, znow);
1444                                 
1445                                 xnew = min (1.0f, xnow + xdelta);
1446                                 xnew = max (0.0f, xnew);
1447
1448                                 ynew = min (1.0f, ynow + ydelta);
1449                                 ynew = max (0.0f, ynew);
1450
1451                                 znew = min (1.0f, znow + zdelta);
1452                                 znew = max (0.0f, znew);
1453
1454                                 (*i)->set_position (xnew, ynew, znew, true);
1455                         }
1456                 }
1457
1458         } else {
1459
1460                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1461                         if (*i == &orig) {
1462                                 (*i)->set_position (xpos, ypos, true);
1463                         } else {
1464                                 (*i)->get_position (xnow, ynow, znow);
1465
1466                                 xnew = min (1.0f, xnow - xdelta);
1467                                 xnew = max (0.0f, xnew);
1468
1469                                 ynew = min (1.0f, ynow - ydelta);
1470                                 ynew = max (0.0f, ynew);
1471
1472                                 znew = min (1.0f, znow + zdelta);
1473                                 znew = max (0.0f, znew);
1474
1475                                 (*i)->set_position (xnew, ynew, znew, true);
1476                         }
1477                 }
1478         }
1479 }