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