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