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