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