Apply MIDI looping patch from torbenh, with minor changes.
[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
753         //configure_io( ChanCount( DataType::AUDIO, nout ), ChanCount( DataType::AUDIO, nin ) )
754         
755         if (nouts < 2 || (nouts == outputs.size() && npans == _streampanners.size())) {
756                 return;
757         } 
758
759         n = _streampanners.size();
760         clear_panners ();
761
762         if (n != npans) {
763                 changed = true;
764         }
765
766         n = outputs.size();
767         outputs.clear ();
768
769         if (n != nouts) {
770                 changed = true;
771         }
772
773         switch (nouts) {
774         case 0:
775                 break;
776
777         case 1:
778                 fatal << _("programming error:")
779                       << X_("Panner::reset() called with a single output")
780                       << endmsg;
781                 /*NOTREACHED*/
782                 break;
783
784         case 2:
785                 /* line */
786                 outputs.push_back (Output (0, 0));
787                 outputs.push_back (Output (1.0, 0));
788
789                 for (n = 0; n < npans; ++n) {
790                         _streampanners.push_back (new EqualPowerStereoPanner (*this, Evoral::Parameter(PanAutomation, 0, n)));
791                 }
792                 break;
793
794         case 3: // triangle
795                 outputs.push_back (Output  (0.5, 0));
796                 outputs.push_back (Output  (0, 1.0));
797                 outputs.push_back (Output  (1.0, 1.0));
798
799                 for (n = 0; n < npans; ++n) {
800                         _streampanners.push_back (new Multi2dPanner (*this, Evoral::Parameter(PanAutomation, 0, n)));
801                 }
802
803                 break; 
804
805         case 4: // square
806                 outputs.push_back (Output  (0, 0));
807                 outputs.push_back (Output  (1.0, 0));
808                 outputs.push_back (Output  (1.0, 1.0));
809                 outputs.push_back (Output  (0, 1.0));
810
811                 for (n = 0; n < npans; ++n) {
812                         _streampanners.push_back (new Multi2dPanner (*this, Evoral::Parameter(PanAutomation, 0, n)));
813                 }
814
815                 break;  
816
817         case 5: //square+offcenter center
818                 outputs.push_back (Output  (0, 0));
819                 outputs.push_back (Output  (1.0, 0));
820                 outputs.push_back (Output  (1.0, 1.0));
821                 outputs.push_back (Output  (0, 1.0));
822                 outputs.push_back (Output  (0.5, 0.75));
823
824                 for (n = 0; n < npans; ++n) {
825                         _streampanners.push_back (new Multi2dPanner (*this, Evoral::Parameter(PanAutomation, 0, n)));
826                 }
827
828                 break;
829
830         default:
831                 /* XXX horrible placement. FIXME */
832                 for (n = 0; n < nouts; ++n) {
833                         outputs.push_back (Output (0.1 * n, 0.1 * n));
834                 }
835
836                 for (n = 0; n < npans; ++n) {
837                         _streampanners.push_back (new Multi2dPanner (*this, Evoral::Parameter(PanAutomation, 0, n)));
838                 }
839
840                 break;
841         }
842
843         for (std::vector<StreamPanner*>::iterator x = _streampanners.begin(); x != _streampanners.end(); ++x) {
844                 (*x)->update ();
845         }
846
847         /* force hard left/right panning in a common case: 2in/2out 
848         */
849         
850         if (npans == 2 && outputs.size() == 2) {
851
852                 /* Do this only if we changed configuration, or our configuration
853                    appears to be the default set up (center).
854                 */
855
856                 float left;
857                 float right;
858
859                 _streampanners.front()->get_position (left);
860                 _streampanners.back()->get_position (right);
861
862                 if (changed || ((left == 0.5) && (right == 0.5))) {
863                 
864                         _streampanners.front()->set_position (0.0);
865                         _streampanners.front()->pan_control()->list()->reset_default (0.0);
866                         
867                         _streampanners.back()->set_position (1.0);
868                         _streampanners.back()->pan_control()->list()->reset_default (1.0);
869                         
870                         changed = true;
871                 }
872         }
873
874         if (changed) {
875                 Changed (); /* EMIT SIGNAL */
876         }
877
878         return;
879 }
880
881 void
882 Panner::remove (uint32_t which)
883 {
884         vector<StreamPanner*>::iterator i;
885         for (i = _streampanners.begin(); i != _streampanners.end() && which; ++i, --which);
886
887         if (i != _streampanners.end()) {
888                 delete *i;
889                 _streampanners.erase (i);
890         }
891 }
892
893 void
894 Panner::clear_panners ()
895 {
896         for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
897                 delete *i;
898         }
899
900         _streampanners.clear ();
901 }
902
903 void
904 Panner::set_automation_style (AutoStyle style)
905 {
906         for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
907                 ((AutomationList*)(*i)->pan_control()->list().get())->set_automation_style (style);
908         }
909         _session.set_dirty ();
910 }       
911
912 void
913 Panner::set_automation_state (AutoState state)
914 {
915         for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
916                 ((AutomationList*)(*i)->pan_control()->list().get())->set_automation_state (state);
917         }
918         _session.set_dirty ();
919 }       
920
921 AutoState
922 Panner::automation_state () const
923 {
924         if (!empty()) {
925                 return ((AutomationList*)_streampanners.front()->pan_control()->list().get())->automation_state ();
926         } else {
927                 return Off;
928         }
929 }
930
931 AutoStyle
932 Panner::automation_style () const
933 {
934         if (!empty()) {
935                 return ((AutomationList*)_streampanners.front()->pan_control()->list().get())->automation_style ();
936         } else {
937                 return Absolute;
938         }
939 }
940
941
942 struct PanPlugins {
943     string name;
944     uint32_t nouts;
945     StreamPanner* (*factory)(Panner&, Evoral::Parameter);
946 };
947
948 PanPlugins pan_plugins[] = {
949         { EqualPowerStereoPanner::name, 2, EqualPowerStereoPanner::factory },
950         { Multi2dPanner::name, 3, Multi2dPanner::factory },
951         { string (""), 0, 0 }
952 };
953
954 XMLNode&
955 Panner::get_state (void)
956 {
957         return state (true);
958 }
959
960 XMLNode&
961 Panner::state (bool full)
962 {
963         XMLNode& node = Processor::state(full);
964
965         node.add_property ("type", "panner");
966
967         char buf[32];
968
969         node.add_property (X_("linked"), (_linked ? "yes" : "no"));
970         node.add_property (X_("link_direction"), enum_2_string (_link_direction));
971         node.add_property (X_("bypassed"), (bypassed() ? "yes" : "no"));
972
973         for (vector<Panner::Output>::iterator o = outputs.begin(); o != outputs.end(); ++o) {
974                 XMLNode* onode = new XMLNode (X_("Output"));
975                 snprintf (buf, sizeof (buf), "%.12g", (*o).x);
976                 onode->add_property (X_("x"), buf);
977                 snprintf (buf, sizeof (buf), "%.12g", (*o).y);
978                 onode->add_property (X_("y"), buf);
979                 node.add_child_nocopy (*onode);
980         }
981
982         for (vector<StreamPanner*>::const_iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
983                 node.add_child_nocopy ((*i)->state (full));
984         }
985
986
987         return node;
988 }
989
990 int
991 Panner::set_state (const XMLNode& node)
992 {
993         XMLNodeList nlist;
994         XMLNodeConstIterator niter;
995         const XMLProperty *prop;
996         uint32_t i;
997         uint32_t num_panners = 0;
998         StreamPanner* sp;
999         LocaleGuard lg (X_("POSIX"));
1000
1001         clear_panners ();
1002
1003         Processor::set_state(node);
1004
1005         ChanCount ins = ChanCount::ZERO;
1006         ChanCount outs = ChanCount::ZERO;
1007
1008         // XXX: this might not be necessary anymore
1009         outputs.clear ();
1010
1011         if ((prop = node.property (X_("linked"))) != 0) {
1012                 set_linked (prop->value() == "yes");
1013         }
1014
1015
1016         if ((prop = node.property (X_("bypassed"))) != 0) {
1017                 set_bypassed (prop->value() == "yes");
1018         }
1019     
1020         if ((prop = node.property (X_("link_direction"))) != 0) {
1021                 LinkDirection ld; /* here to provide type information */
1022                 set_link_direction (LinkDirection (string_2_enum (prop->value(), ld)));
1023         }
1024
1025         nlist = node.children();
1026
1027         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1028                 if ((*niter)->name() == X_("Output")) {
1029                         
1030                         float x, y;
1031                         
1032                         prop = (*niter)->property (X_("x"));
1033                         sscanf (prop->value().c_str(), "%g", &x);
1034                         
1035                         prop = (*niter)->property (X_("y"));
1036                         sscanf (prop->value().c_str(), "%g", &y);
1037                         
1038                         outputs.push_back (Output (x, y));
1039                 }
1040         }
1041
1042         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1043
1044                 if ((*niter)->name() == X_("StreamPanner")) {
1045                 
1046                         if ((prop = (*niter)->property (X_("type")))) {
1047                                 
1048                                 for (i = 0; pan_plugins[i].factory; ++i) {
1049                                         if (prop->value() == pan_plugins[i].name) {
1050                                                 
1051                                                 
1052                                                 /* note that we assume that all the stream panners
1053                                                    are of the same type. pretty good
1054                                                    assumption, but its still an assumption.
1055                                                 */
1056                                                 
1057                                                 sp = pan_plugins[i].factory (*this, Evoral::Parameter(PanAutomation, 0, num_panners));
1058                                                 num_panners++;
1059                                                 
1060                                                 if (sp->set_state (**niter) == 0) {
1061                                                         _streampanners.push_back (sp);
1062                                                 }
1063                                                 
1064                                                 break;
1065                                         }
1066                                 }
1067                                 
1068                                 
1069                                 if (!pan_plugins[i].factory) {
1070                                         error << string_compose (_("Unknown panner plugin \"%1\" found in pan state - ignored"),
1071                                                           prop->value())
1072                                               << endmsg;
1073                                 }
1074
1075                         } else {
1076                                 error << _("panner plugin node has no type information!")
1077                                       << endmsg;
1078                                 return -1;
1079                         }
1080
1081                 }       
1082         }
1083
1084         reset(num_panners, outputs.size());
1085         /* don't try to do old-school automation loading if it wasn't marked as existing */
1086
1087         if ((prop = node.property (X_("automation")))) {
1088
1089                 /* automation path is relative */
1090                 
1091                 automation_path = Glib::build_filename(_session.automation_dir(), prop->value ());
1092         } 
1093
1094         return 0;
1095 }
1096
1097 bool
1098 Panner::touching () const
1099 {
1100         for (vector<StreamPanner*>::const_iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1101                 if (((AutomationList*)(*i)->pan_control()->list().get())->touching ()) {
1102                         return true;
1103                 }
1104         }
1105
1106         return false;
1107 }
1108
1109 void
1110 Panner::set_position (float xpos, StreamPanner& orig)
1111 {
1112         float xnow;
1113         float xdelta ;
1114         float xnew;
1115
1116         orig.get_position (xnow);
1117         xdelta = xpos - xnow;
1118         
1119         if (_link_direction == SameDirection) {
1120
1121                 for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1122                         if (*i == &orig) {
1123                                 (*i)->set_position (xpos, true);
1124                         } else {
1125                                 (*i)->get_position (xnow);
1126                                 xnew = min (1.0f, xnow + xdelta);
1127                                 xnew = max (0.0f, xnew);
1128                                 (*i)->set_position (xnew, true);
1129                         }
1130                 }
1131
1132         } else {
1133
1134                 for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1135                         if (*i == &orig) {
1136                                 (*i)->set_position (xpos, true);
1137                         } else {
1138                                 (*i)->get_position (xnow);
1139                                 xnew = min (1.0f, xnow - xdelta);
1140                                 xnew = max (0.0f, xnew);
1141                                 (*i)->set_position (xnew, true);
1142                         }
1143                 }
1144         }
1145 }
1146
1147 void
1148 Panner::set_position (float xpos, float ypos, StreamPanner& orig)
1149 {
1150         float xnow, ynow;
1151         float xdelta, ydelta;
1152         float xnew, ynew;
1153
1154         orig.get_position (xnow, ynow);
1155         xdelta = xpos - xnow;
1156         ydelta = ypos - ynow;
1157         
1158         if (_link_direction == SameDirection) {
1159
1160                 for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1161                         if (*i == &orig) {
1162                                 (*i)->set_position (xpos, ypos, true);
1163                         } else {
1164                                 (*i)->get_position (xnow, ynow);
1165
1166                                 xnew = min (1.0f, xnow + xdelta);
1167                                 xnew = max (0.0f, xnew);
1168
1169                                 ynew = min (1.0f, ynow + ydelta);
1170                                 ynew = max (0.0f, ynew);
1171
1172                                 (*i)->set_position (xnew, ynew, true);
1173                         }
1174                 }
1175
1176         } else {
1177
1178                 for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1179                         if (*i == &orig) {
1180                                 (*i)->set_position (xpos, ypos, true);
1181                         } else {
1182                                 (*i)->get_position (xnow, ynow);
1183                                 
1184                                 xnew = min (1.0f, xnow - xdelta);
1185                                 xnew = max (0.0f, xnew);
1186
1187                                 ynew = min (1.0f, ynow - ydelta);
1188                                 ynew = max (0.0f, ynew);
1189
1190                                 (*i)->set_position (xnew, ynew, true);
1191                         }
1192                 }
1193         }
1194 }
1195
1196 void
1197 Panner::set_position (float xpos, float ypos, float zpos, StreamPanner& orig)
1198 {
1199         float xnow, ynow, znow;
1200         float xdelta, ydelta, zdelta;
1201         float xnew, ynew, znew;
1202
1203         orig.get_position (xnow, ynow, znow);
1204         xdelta = xpos - xnow;
1205         ydelta = ypos - ynow;
1206         zdelta = zpos - znow;
1207
1208         if (_link_direction == SameDirection) {
1209
1210                 for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1211                         if (*i == &orig) {
1212                                 (*i)->set_position (xpos, ypos, zpos, true);
1213                         } else {
1214                                 (*i)->get_position (xnow, ynow, znow);
1215                                 
1216                                 xnew = min (1.0f, xnow + xdelta);
1217                                 xnew = max (0.0f, xnew);
1218
1219                                 ynew = min (1.0f, ynow + ydelta);
1220                                 ynew = max (0.0f, ynew);
1221
1222                                 znew = min (1.0f, znow + zdelta);
1223                                 znew = max (0.0f, znew);
1224
1225                                 (*i)->set_position (xnew, ynew, znew, true);
1226                         }
1227                 }
1228
1229         } else {
1230
1231                 for (vector<StreamPanner*>::iterator i = _streampanners.begin(); i != _streampanners.end(); ++i) {
1232                         if (*i == &orig) {
1233                                 (*i)->set_position (xpos, ypos, true);
1234                         } else {
1235                                 (*i)->get_position (xnow, ynow, znow);
1236
1237                                 xnew = min (1.0f, xnow - xdelta);
1238                                 xnew = max (0.0f, xnew);
1239
1240                                 ynew = min (1.0f, ynow - ydelta);
1241                                 ynew = max (0.0f, ynew);
1242
1243                                 znew = min (1.0f, znow + zdelta);
1244                                 znew = max (0.0f, znew);
1245
1246                                 (*i)->set_position (xnew, ynew, znew, true);
1247                         }
1248                 }
1249         }
1250 }
1251
1252 void
1253 Panner::distribute_no_automation (BufferSet& inbufs, BufferSet& outbufs, nframes_t nframes, nframes_t offset, gain_t gain_coeff)
1254 {
1255         if (outbufs.count().n_audio() == 0) {
1256                 // Don't want to lose audio...
1257                 assert(inbufs.count().n_audio() == 0);
1258                 return;
1259         }
1260
1261         // We shouldn't be called in the first place...
1262         assert(!bypassed());
1263         assert(!empty());
1264
1265         
1266         if (outbufs.count().n_audio() == 1) {
1267
1268                 AudioBuffer& dst = outbufs.get_audio(0);
1269
1270                 if (gain_coeff == 0.0f) {
1271
1272                         /* only one output, and gain was zero, so make it silent */
1273
1274                         dst.silence(offset);
1275                         
1276                 } else if (gain_coeff == 1.0f){
1277
1278                         /* mix all buffers into the output */
1279
1280                         // copy the first
1281                         dst.read_from(inbufs.get_audio(0), nframes, offset);
1282                         
1283                         // accumulate starting with the second
1284             if (inbufs.count().n_audio() > 0) {
1285                 BufferSet::audio_iterator i = inbufs.audio_begin();
1286                 for (++i; i != inbufs.audio_end(); ++i) {
1287                     dst.accumulate_from(*i, nframes, offset);
1288                 }
1289             }
1290
1291                 } else {
1292
1293                         /* mix all buffers into the output, scaling them all by the gain */
1294
1295                         // copy the first
1296                         dst.read_from(inbufs.get_audio(0), nframes, offset);
1297                         
1298                         // accumulate (with gain) starting with the second
1299             if (inbufs.count().n_audio() > 0) {
1300                         BufferSet::audio_iterator i = inbufs.audio_begin();
1301                             for (++i; i != inbufs.audio_end(); ++i) {
1302                                 dst.accumulate_with_gain_from(*i, nframes, offset, gain_coeff);
1303                         }
1304             }
1305
1306                 }
1307
1308                 return;
1309         }
1310         
1311         /* the terrible silence ... */
1312         for (BufferSet::audio_iterator i = outbufs.audio_begin(); i != outbufs.audio_end(); ++i) {
1313                 i->silence(nframes, offset);
1314         }
1315
1316         BufferSet::audio_iterator i = inbufs.audio_begin();
1317
1318         for (vector<StreamPanner*>::iterator pan = _streampanners.begin(); pan != _streampanners.end() && i != inbufs.audio_end(); ++pan, ++i) {
1319                 (*pan)->distribute (*i, outbufs, gain_coeff, nframes);
1320         }
1321 }
1322
1323 void
1324 Panner::run_out_of_place (BufferSet& inbufs, BufferSet& outbufs, nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset)
1325 {       
1326         if (outbufs.count().n_audio() == 0) {
1327                 // Failing to deliver audio we were asked to deliver is a bug
1328                 assert(inbufs.count().n_audio() == 0);
1329                 return;
1330         }
1331
1332         // We shouldn't be called in the first place...
1333         assert(!bypassed());
1334         assert(!empty());
1335
1336         // If we shouldn't play automation defer to distribute_no_automation
1337         if ( !( automation_state() & Play ||
1338                          ((automation_state() & Touch) && !touching()) ) ) {
1339
1340                 // Speed quietning
1341                 gain_t gain_coeff = 1.0;
1342                 if (fabsf(_session.transport_speed()) > 1.5f) {
1343                         gain_coeff = speed_quietning;
1344                 }
1345
1346                 distribute_no_automation(inbufs, outbufs, nframes, offset, gain_coeff);
1347                 return;
1348         }
1349
1350         // Otherwise.. let the automation flow, baby
1351         
1352         if (outbufs.count().n_audio() == 1) {
1353
1354                 AudioBuffer& dst = outbufs.get_audio(0);
1355
1356                 // FIXME: apply gain automation?
1357
1358                 // copy the first
1359                 dst.read_from(inbufs.get_audio(0), nframes, offset);
1360
1361                 // accumulate starting with the second
1362                 BufferSet::audio_iterator i = inbufs.audio_begin();
1363                 for (++i; i != inbufs.audio_end(); ++i) {
1364                         dst.accumulate_from(*i, nframes, offset);
1365                 }
1366
1367                 return;
1368         }
1369
1370         // More than 1 output, we should have 1 panner for each input
1371         //assert(_streampanners.size() == inbufs.count().n_audio());
1372         
1373         /* the terrible silence ... */
1374         for (BufferSet::audio_iterator i = outbufs.audio_begin(); i != outbufs.audio_end(); ++i) {
1375                 i->silence(nframes, offset);
1376         }
1377
1378         BufferSet::audio_iterator i = inbufs.audio_begin();
1379         for (vector<StreamPanner*>::iterator pan = _streampanners.begin(); pan != _streampanners.end(); ++pan, ++i) {
1380                 (*pan)->distribute_automated (*i, outbufs, start_frame, end_frame, nframes, _session.pan_automation_buffer());
1381         }
1382 }
1383
1384 /* old school automation handling */
1385
1386 /*
1387 void
1388 Panner::set_name (string str)
1389 {
1390         automation_path = Glib::build_filename(_session.automation_dir(), 
1391                 _session.snap_name() + "-pan-" + legalize_for_path (str) + ".automation");
1392 }
1393 */
1394
1395 int
1396 Panner::load ()
1397 {
1398         char line[128];
1399         uint32_t linecnt = 0;
1400         float version;
1401         vector<StreamPanner*>::iterator sp;
1402         LocaleGuard lg (X_("POSIX"));
1403
1404         if (automation_path.length() == 0) {
1405                 return 0;
1406         }
1407         
1408         if (access (automation_path.c_str(), F_OK)) {
1409                 return 0;
1410         }
1411
1412         ifstream in (automation_path.c_str());
1413
1414         if (!in) {
1415                 error << string_compose (_("cannot open pan automation file %1 (%2)"),
1416                                   automation_path, strerror (errno))
1417                       << endmsg;
1418                 return -1;
1419         }
1420
1421         sp = _streampanners.begin();
1422
1423         while (in.getline (line, sizeof(line), '\n')) {
1424
1425                 if (++linecnt == 1) {
1426                         if (memcmp (line, X_("version"), 7) == 0) {
1427                                 if (sscanf (line, "version %f", &version) != 1) {
1428                                         error << string_compose(_("badly formed version number in pan automation event file \"%1\""), automation_path) << endmsg;
1429                                         return -1;
1430                                 }
1431                         } else {
1432                                 error << string_compose(_("no version information in pan automation event file \"%1\" (first line = %2)"), 
1433                                                  automation_path, line) << endmsg;
1434                                 return -1;
1435                         }
1436
1437                         continue;
1438                 }
1439
1440                 if (strlen (line) == 0 || line[0] == '#') {
1441                         continue;
1442                 }
1443
1444                 if (strcmp (line, "begin") == 0) {
1445                         
1446                         if (sp == _streampanners.end()) {
1447                                 error << string_compose (_("too many panner states found in pan automation file %1"),
1448                                                   automation_path)
1449                                       << endmsg;
1450                                 return -1;
1451                         }
1452
1453                         if ((*sp)->load (in, automation_path, linecnt)) {
1454                                 return -1;
1455                         }
1456                         
1457                         ++sp;
1458                 }
1459         }
1460
1461         return 0;
1462 }