Merged with trunk R1283.
[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_("panner")) {
549
550                         _control.set_state (**iter);
551
552                 } else if ((*iter)->name() == X_("Automation")) {
553
554                         _automation.set_state (*((*iter)->children().front()));
555
556                         if (_automation.automation_state() != Off) {
557                                 set_position (_automation.eval (parent.session().transport_frame()));
558                         }
559                 }
560         }
561
562         return 0;
563 }
564
565 /*----------------------------------------------------------------------*/
566
567 Multi2dPanner::Multi2dPanner (Panner& p)
568         : StreamPanner (p), _automation (0.0, 1.0, 0.5) // XXX useless
569 {
570         update ();
571 }
572
573 Multi2dPanner::~Multi2dPanner ()
574 {
575 }
576
577 void
578 Multi2dPanner::snapshot (nframes_t now)
579 {
580         // how?
581 }
582
583 void
584 Multi2dPanner::transport_stopped (nframes_t frame)
585 {
586         //what?
587 }
588
589 void
590 Multi2dPanner::set_automation_style (AutoStyle style)
591 {
592         //what?
593 }
594
595 void
596 Multi2dPanner::set_automation_state (AutoState state)
597 {
598         // what?
599 }
600
601 void
602 Multi2dPanner::update ()
603 {
604         static const float BIAS = FLT_MIN;
605         uint32_t i;
606         uint32_t nouts = parent.outputs.size();
607         float dsq[nouts];
608         float f, fr;
609         vector<pan_t> pans;
610
611         f = 0.0f;
612
613         for (i = 0; i < nouts; i++) {
614                 dsq[i] = ((x - parent.outputs[i].x) * (x - parent.outputs[i].x) + (y - parent.outputs[i].y) * (y - parent.outputs[i].y) + BIAS);
615                 if (dsq[i] < 0.0) {
616                         dsq[i] = 0.0;
617                 }
618                 f += dsq[i] * dsq[i];
619         }
620 #ifdef __APPLE__
621         // terrible hack to support OSX < 10.3.9 builds
622         fr = (float) (1.0 / sqrt((double)f));
623 #else
624         fr = 1.0 / sqrtf(f);
625 #endif  
626         for (i = 0; i < nouts; ++i) {
627                 parent.outputs[i].desired_pan = 1.0f - (dsq[i] * fr);
628         }
629
630         effective_x = x;
631 }
632
633 void
634 Multi2dPanner::distribute (AudioBuffer& srcbuf, BufferSet& obufs, gain_t gain_coeff, nframes_t nframes)
635 {
636         Sample* dst;
637         pan_t pan;
638         vector<Panner::Output>::iterator o;
639         uint32_t n;
640
641         if (_muted) {
642                 return;
643         }
644         
645         Sample* const src = srcbuf.data(nframes);
646
647
648         for (n = 0, o = parent.outputs.begin(); o != parent.outputs.end(); ++o, ++n) {
649
650                 dst = obufs.get_audio(n).data(nframes);
651         
652 #ifdef CAN_INTERP
653                 if (fabsf ((delta = (left_interp - desired_left))) > 0.002) { // about 1 degree of arc 
654                         
655                         /* interpolate over 64 frames or nframes, whichever is smaller */
656                         
657                         nframes_t limit = min ((nframes_t)64, nframes);
658                         nframes_t n;
659                         
660                         delta = -(delta / (float) (limit));
661                 
662                         for (n = 0; n < limit; n++) {
663                                 left_interp = left_interp + delta;
664                                 left = left_interp + 0.9 * (left - left_interp);
665                                 dst[n] += src[n] * left * gain_coeff;
666                         }
667                         
668                         pan = left * gain_coeff;
669                         
670                         for (; n < nframes; ++n) {
671                                 dst[n] += src[n] * pan;
672                         }
673                         
674                 } else {
675
676 #else                   
677                         pan = (*o).desired_pan;
678                         
679                         if ((pan *= gain_coeff) != 1.0f) {
680                                 
681                                 if (pan != 0.0f) {
682                                         
683                                         for (nframes_t n = 0; n < nframes; ++n) {
684                                                 dst[n] += src[n] * pan;
685                                         }      
686                                         
687                                 } 
688
689                                 
690                         } else {
691                                 
692                                 for (nframes_t n = 0; n < nframes; ++n) {
693                                         dst[n] += src[n];
694                                 }      
695
696                         }
697 #endif
698 #ifdef CAN_INTERP
699                 }
700 #endif
701         }
702         
703         return;
704 }
705
706 void
707 Multi2dPanner::distribute_automated (AudioBuffer& src, BufferSet& obufs, 
708                                      nframes_t start, nframes_t end, nframes_t nframes,
709                                      pan_t** buffers)
710 {
711         if (_muted) {
712                 return;
713         }
714
715         /* what ? */
716
717         return;
718 }
719
720 StreamPanner*
721 Multi2dPanner::factory (Panner& p)
722 {
723         return new Multi2dPanner (p);
724 }
725
726 int
727 Multi2dPanner::load (istream& in, string path, uint32_t& linecnt)
728 {
729         return 0;
730 }
731
732 XMLNode&
733 Multi2dPanner::get_state (void)
734 {
735         return state (true);
736 }
737
738 XMLNode&
739 Multi2dPanner::state (bool full_state)
740 {
741         XMLNode* root = new XMLNode ("StreamPanner");
742         char buf[64];
743         LocaleGuard lg (X_("POSIX"));
744
745         snprintf (buf, sizeof (buf), "%.12g", x); 
746         root->add_property (X_("x"), buf);
747         snprintf (buf, sizeof (buf), "%.12g", y); 
748         root->add_property (X_("y"), buf);
749         root->add_property (X_("type"), Multi2dPanner::name);
750
751         /* XXX no meaningful automation yet */
752
753         return *root;
754 }
755
756 int
757 Multi2dPanner::set_state (const XMLNode& node)
758 {
759         const XMLProperty* prop;
760         float newx,newy;
761         LocaleGuard lg (X_("POSIX"));
762
763         newx = -1;
764         newy = -1;
765
766         if ((prop = node.property (X_("x")))) {
767                 newx = atof (prop->value().c_str());
768         }
769        
770         if ((prop = node.property (X_("y")))) {
771                 newy = atof (prop->value().c_str());
772         }
773         
774         if (x < 0 || y < 0) {
775                 error << _("badly-formed positional data for Multi2dPanner - ignored")
776                       << endmsg;
777                 return -1;
778         } 
779         
780         set_position (newx, newy);
781         return 0;
782 }
783
784 /*---------------------------------------------------------------------- */
785
786 Panner::Panner (string name, Session& s)
787         : _session (s)
788 {
789         set_name (name);
790
791         _linked = false;
792         _link_direction = SameDirection;
793         _bypassed = false;
794 }
795
796 Panner::~Panner ()
797 {
798 }
799
800 void
801 Panner::set_linked (bool yn)
802 {
803         if (yn != _linked) {
804                 _linked = yn;
805                 _session.set_dirty ();
806                 LinkStateChanged (); /* EMIT SIGNAL */
807         }
808 }
809
810 void
811 Panner::set_link_direction (LinkDirection ld)
812 {
813         if (ld != _link_direction) {
814                 _link_direction = ld;
815                 _session.set_dirty ();
816                 LinkStateChanged (); /* EMIT SIGNAL */
817         }
818 }
819
820 void
821 Panner::set_bypassed (bool yn)
822 {
823         if (yn != _bypassed) {
824                 _bypassed = yn;
825                 StateChanged ();
826         }
827 }
828
829
830 void
831 Panner::reset (uint32_t nouts, uint32_t npans)
832 {
833         uint32_t n;
834         bool changed = false;
835
836         if (nouts < 2 || (nouts == outputs.size() && npans == size())) {
837                 return;
838         } 
839
840         n = size();
841         clear ();
842
843         if (n != npans) {
844                 changed = true;
845         }
846
847         n = outputs.size();
848         outputs.clear ();
849
850         if (n != nouts) {
851                 changed = true;
852         }
853
854         switch (nouts) {
855         case 0:
856                 break;
857
858         case 1:
859                 fatal << _("programming error:")
860                       << X_("Panner::reset() called with a single output")
861                       << endmsg;
862                 /*NOTREACHED*/
863                 break;
864
865         case 2:
866                 /* line */
867                 outputs.push_back (Output (0, 0));
868                 outputs.push_back (Output (1.0, 0));
869
870                 for (n = 0; n < npans; ++n) {
871                         push_back (new EqualPowerStereoPanner (*this));
872                 }
873                 break;
874
875         case 3: // triangle
876                 outputs.push_back (Output  (0.5, 0));
877                 outputs.push_back (Output  (0, 1.0));
878                 outputs.push_back (Output  (1.0, 1.0));
879
880                 for (n = 0; n < npans; ++n) {
881                         push_back (new Multi2dPanner (*this));
882                 }
883
884                 break; 
885
886         case 4: // square
887                 outputs.push_back (Output  (0, 0));
888                 outputs.push_back (Output  (1.0, 0));
889                 outputs.push_back (Output  (1.0, 1.0));
890                 outputs.push_back (Output  (0, 1.0));
891
892                 for (n = 0; n < npans; ++n) {
893                         push_back (new Multi2dPanner (*this));
894                 }
895
896                 break;  
897
898         case 5: //square+offcenter center
899                 outputs.push_back (Output  (0, 0));
900                 outputs.push_back (Output  (1.0, 0));
901                 outputs.push_back (Output  (1.0, 1.0));
902                 outputs.push_back (Output  (0, 1.0));
903                 outputs.push_back (Output  (0.5, 0.75));
904
905                 for (n = 0; n < npans; ++n) {
906                         push_back (new Multi2dPanner (*this));
907                 }
908
909                 break;
910
911         default:
912                 /* XXX horrible placement. FIXME */
913                 for (n = 0; n < nouts; ++n) {
914                         outputs.push_back (Output (0.1 * n, 0.1 * n));
915                 }
916
917                 for (n = 0; n < npans; ++n) {
918                         push_back (new Multi2dPanner (*this));
919                 }
920
921                 break;
922         }
923
924         for (iterator x = begin(); x != end(); ++x) {
925                 (*x)->update ();
926         }
927
928         /* force hard left/right panning in a common case: 2in/2out 
929         */
930         
931         if (npans == 2 && outputs.size() == 2) {
932
933                 /* Do this only if we changed configuration, or our configuration
934                    appears to be the default set up (center).
935                 */
936
937                 float left;
938                 float right;
939
940                 front()->get_position (left);
941                 back()->get_position (right);
942
943                 if (changed || ((left == 0.5) && (right == 0.5))) {
944                 
945                         front()->set_position (0.0);
946                         front()->automation().reset_default (0.0);
947                         
948                         back()->set_position (1.0);
949                         back()->automation().reset_default (1.0);
950                         
951                         changed = true;
952                 }
953         }
954
955         if (changed) {
956                 Changed (); /* EMIT SIGNAL */
957         }
958
959         return;
960 }
961
962 void
963 Panner::remove (uint32_t which)
964 {
965         vector<StreamPanner*>::iterator i;
966         for (i = begin(); i != end() && which; ++i, --which);
967
968         if (i != end()) {
969                 delete *i;
970                 erase (i);
971         }
972 }
973
974 void
975 Panner::clear ()
976 {
977         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
978                 delete *i;
979         }
980
981         vector<StreamPanner*>::clear ();
982 }
983
984 void
985 Panner::set_automation_style (AutoStyle style)
986 {
987         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
988                 (*i)->set_automation_style (style);
989         }
990         _session.set_dirty ();
991 }       
992
993 void
994 Panner::set_automation_state (AutoState state)
995 {
996         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
997                 (*i)->set_automation_state (state);
998         }
999         _session.set_dirty ();
1000 }       
1001
1002 AutoState
1003 Panner::automation_state () const
1004 {
1005         if (!empty()) {
1006                 return front()->automation().automation_state ();
1007         } else {
1008                 return Off;
1009         }
1010 }
1011
1012 AutoStyle
1013 Panner::automation_style () const
1014 {
1015         if (!empty()) {
1016                 return front()->automation().automation_style ();
1017         } else {
1018                 return Absolute;
1019         }
1020 }
1021
1022 void
1023 Panner::transport_stopped (nframes_t frame)
1024 {
1025         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1026                 (*i)->transport_stopped (frame);
1027         }
1028 }       
1029
1030 void
1031 Panner::snapshot (nframes_t now)
1032 {
1033         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1034                 (*i)->snapshot (now);
1035         }
1036 }       
1037
1038 void
1039 Panner::clear_automation ()
1040 {
1041         for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1042                 (*i)->automation().clear ();
1043         }
1044         _session.set_dirty ();
1045 }       
1046
1047 struct PanPlugins {
1048     string name;
1049     uint32_t nouts;
1050     StreamPanner* (*factory)(Panner&);
1051 };
1052
1053 PanPlugins pan_plugins[] = {
1054         { EqualPowerStereoPanner::name, 2, EqualPowerStereoPanner::factory },
1055         { Multi2dPanner::name, 3, Multi2dPanner::factory },
1056         { string (""), 0, 0 }
1057 };
1058
1059 XMLNode&
1060 Panner::get_state (void)
1061 {
1062         return state (true);
1063 }
1064
1065 XMLNode&
1066 Panner::state (bool full)
1067 {
1068         XMLNode* root = new XMLNode (X_("Panner"));
1069         char buf[32];
1070
1071         root->add_property (X_("linked"), (_linked ? "yes" : "no"));
1072         root->add_property (X_("link_direction"), enum_2_string (_link_direction));
1073         root->add_property (X_("bypassed"), (bypassed() ? "yes" : "no"));
1074
1075         /* add each output */
1076
1077         for (vector<Panner::Output>::iterator o = outputs.begin(); o != outputs.end(); ++o) {
1078                 XMLNode* onode = new XMLNode (X_("Output"));
1079                 snprintf (buf, sizeof (buf), "%.12g", (*o).x);
1080                 onode->add_property (X_("x"), buf);
1081                 snprintf (buf, sizeof (buf), "%.12g", (*o).y);
1082                 onode->add_property (X_("y"), buf);
1083                 root->add_child_nocopy (*onode);
1084         }
1085
1086         for (vector<StreamPanner*>::const_iterator i = begin(); i != end(); ++i) {
1087                 root->add_child_nocopy ((*i)->state (full));
1088         }
1089
1090         return *root;
1091 }
1092
1093 int
1094 Panner::set_state (const XMLNode& node)
1095 {
1096         XMLNodeList nlist;
1097         XMLNodeConstIterator niter;
1098         const XMLProperty *prop;
1099         uint32_t i;
1100         StreamPanner* sp;
1101         LocaleGuard lg (X_("POSIX"));
1102
1103         clear ();
1104         outputs.clear ();
1105
1106         if ((prop = node.property (X_("linked"))) != 0) {
1107                 set_linked (prop->value() == "yes");
1108         }
1109
1110
1111         if ((prop = node.property (X_("bypassed"))) != 0) {
1112                 set_bypassed (prop->value() == "yes");
1113         }
1114
1115         if ((prop = node.property (X_("link_direction"))) != 0) {
1116                 LinkDirection ld; /* here to provide type information */
1117                 set_link_direction (LinkDirection (string_2_enum (prop->value(), ld)));
1118         }
1119
1120         nlist = node.children();
1121
1122         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1123                 if ((*niter)->name() == X_("Output")) {
1124                         
1125                         float x, y;
1126                         
1127                         prop = (*niter)->property (X_("x"));
1128                         sscanf (prop->value().c_str(), "%g", &x);
1129                         
1130                         prop = (*niter)->property (X_("y"));
1131                         sscanf (prop->value().c_str(), "%g", &y);
1132                         
1133                         outputs.push_back (Output (x, y));
1134                 }
1135         }
1136
1137         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1138
1139                 if ((*niter)->name() == X_("StreamPanner")) {
1140                 
1141                         if ((prop = (*niter)->property (X_("type")))) {
1142                                 
1143                                 for (i = 0; pan_plugins[i].factory; ++i) {
1144                                         if (prop->value() == pan_plugins[i].name) {
1145                                                 
1146                                                 
1147                                                 /* note that we assume that all the stream panners
1148                                                    are of the same type. pretty good
1149                                                    assumption, but its still an assumption.
1150                                                 */
1151                                                 
1152                                                 sp = pan_plugins[i].factory (*this);
1153                                                 
1154                                                 if (sp->set_state (**niter) == 0) {
1155                                                         push_back (sp);
1156                                                 }
1157                                                 
1158                                                 break;
1159                                         }
1160                                 }
1161                                 
1162                                 
1163                                 if (!pan_plugins[i].factory) {
1164                                         error << string_compose (_("Unknown panner plugin \"%1\" found in pan state - ignored"),
1165                                                           prop->value())
1166                                               << endmsg;
1167                                 }
1168
1169                         } else {
1170                                 error << _("panner plugin node has no type information!")
1171                                       << endmsg;
1172                                 return -1;
1173                         }
1174
1175                 }       
1176         }
1177
1178         /* don't try to do old-school automation loading if it wasn't marked as existing */
1179
1180         if ((prop = node.property (X_("automation")))) {
1181
1182                 /* automation path is relative */
1183                 
1184                 automation_path = _session.automation_dir();
1185                 automation_path += prop->value ();
1186         } 
1187
1188         return 0;
1189 }
1190
1191
1192
1193 bool
1194 Panner::touching () const
1195 {
1196         for (vector<StreamPanner*>::const_iterator i = begin(); i != end(); ++i) {
1197                 if ((*i)->automation().touching ()) {
1198                         return true;
1199                 }
1200         }
1201
1202         return false;
1203 }
1204
1205 void
1206 Panner::set_position (float xpos, StreamPanner& orig)
1207 {
1208         float xnow;
1209         float xdelta ;
1210         float xnew;
1211
1212         orig.get_position (xnow);
1213         xdelta = xpos - xnow;
1214         
1215         if (_link_direction == SameDirection) {
1216
1217                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1218                         if (*i == &orig) {
1219                                 (*i)->set_position (xpos, true);
1220                         } else {
1221                                 (*i)->get_position (xnow);
1222                                 xnew = min (1.0f, xnow + xdelta);
1223                                 xnew = max (0.0f, xnew);
1224                                 (*i)->set_position (xnew, true);
1225                         }
1226                 }
1227
1228         } else {
1229
1230                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1231                         if (*i == &orig) {
1232                                 (*i)->set_position (xpos, true);
1233                         } else {
1234                                 (*i)->get_position (xnow);
1235                                 xnew = min (1.0f, xnow - xdelta);
1236                                 xnew = max (0.0f, xnew);
1237                                 (*i)->set_position (xnew, true);
1238                         }
1239                 }
1240         }
1241 }
1242
1243 void
1244 Panner::set_position (float xpos, float ypos, StreamPanner& orig)
1245 {
1246         float xnow, ynow;
1247         float xdelta, ydelta;
1248         float xnew, ynew;
1249
1250         orig.get_position (xnow, ynow);
1251         xdelta = xpos - xnow;
1252         ydelta = ypos - ynow;
1253         
1254         if (_link_direction == SameDirection) {
1255
1256                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1257                         if (*i == &orig) {
1258                                 (*i)->set_position (xpos, ypos, true);
1259                         } else {
1260                                 (*i)->get_position (xnow, ynow);
1261
1262                                 xnew = min (1.0f, xnow + xdelta);
1263                                 xnew = max (0.0f, xnew);
1264
1265                                 ynew = min (1.0f, ynow + ydelta);
1266                                 ynew = max (0.0f, ynew);
1267
1268                                 (*i)->set_position (xnew, ynew, true);
1269                         }
1270                 }
1271
1272         } else {
1273
1274                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1275                         if (*i == &orig) {
1276                                 (*i)->set_position (xpos, ypos, true);
1277                         } else {
1278                                 (*i)->get_position (xnow, ynow);
1279                                 
1280                                 xnew = min (1.0f, xnow - xdelta);
1281                                 xnew = max (0.0f, xnew);
1282
1283                                 ynew = min (1.0f, ynow - ydelta);
1284                                 ynew = max (0.0f, ynew);
1285
1286                                 (*i)->set_position (xnew, ynew, true);
1287                         }
1288                 }
1289         }
1290 }
1291
1292 void
1293 Panner::set_position (float xpos, float ypos, float zpos, StreamPanner& orig)
1294 {
1295         float xnow, ynow, znow;
1296         float xdelta, ydelta, zdelta;
1297         float xnew, ynew, znew;
1298
1299         orig.get_position (xnow, ynow, znow);
1300         xdelta = xpos - xnow;
1301         ydelta = ypos - ynow;
1302         zdelta = zpos - znow;
1303
1304         if (_link_direction == SameDirection) {
1305
1306                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1307                         if (*i == &orig) {
1308                                 (*i)->set_position (xpos, ypos, zpos, true);
1309                         } else {
1310                                 (*i)->get_position (xnow, ynow, znow);
1311                                 
1312                                 xnew = min (1.0f, xnow + xdelta);
1313                                 xnew = max (0.0f, xnew);
1314
1315                                 ynew = min (1.0f, ynow + ydelta);
1316                                 ynew = max (0.0f, ynew);
1317
1318                                 znew = min (1.0f, znow + zdelta);
1319                                 znew = max (0.0f, znew);
1320
1321                                 (*i)->set_position (xnew, ynew, znew, true);
1322                         }
1323                 }
1324
1325         } else {
1326
1327                 for (vector<StreamPanner*>::iterator i = begin(); i != end(); ++i) {
1328                         if (*i == &orig) {
1329                                 (*i)->set_position (xpos, ypos, true);
1330                         } else {
1331                                 (*i)->get_position (xnow, ynow, znow);
1332
1333                                 xnew = min (1.0f, xnow - xdelta);
1334                                 xnew = max (0.0f, xnew);
1335
1336                                 ynew = min (1.0f, ynow - ydelta);
1337                                 ynew = max (0.0f, ynew);
1338
1339                                 znew = min (1.0f, znow + zdelta);
1340                                 znew = max (0.0f, znew);
1341
1342                                 (*i)->set_position (xnew, ynew, znew, true);
1343                         }
1344                 }
1345         }
1346 }
1347
1348 void
1349 Panner::distribute_no_automation (BufferSet& inbufs, BufferSet& outbufs, nframes_t nframes, nframes_t offset, gain_t gain_coeff)
1350 {
1351         if (outbufs.count().get(DataType::AUDIO) == 0) {
1352                 // Don't want to lose audio...
1353                 assert(inbufs.count().get(DataType::AUDIO) == 0);
1354                 return;
1355         }
1356
1357         // We shouldn't be called in the first place...
1358         assert(!bypassed());
1359         assert(!empty());
1360
1361         
1362         if (outbufs.count().get(DataType::AUDIO) == 1) {
1363
1364                 AudioBuffer& dst = outbufs.get_audio(0);
1365
1366                 if (gain_coeff == 0.0f) {
1367
1368                         /* only one output, and gain was zero, so make it silent */
1369
1370                         dst.silence(offset);
1371                         
1372                 } else if (gain_coeff == 1.0f){
1373
1374                         /* mix all buffers into the output */
1375
1376                         // copy the first
1377                         dst.read_from(inbufs.get_audio(0), nframes, offset);
1378                         
1379                         // accumulate starting with the second
1380                         BufferSet::audio_iterator i = inbufs.audio_begin();
1381                         for (++i; i != inbufs.audio_end(); ++i) {
1382                                 dst.accumulate_from(*i, nframes, offset);
1383                         }
1384
1385                 } else {
1386
1387                         /* mix all buffers into the output, scaling them all by the gain */
1388
1389                         // copy the first
1390                         dst.read_from(inbufs.get_audio(0), nframes, offset);
1391                         
1392                         // accumulate (with gain) starting with the second
1393                         BufferSet::audio_iterator i = inbufs.audio_begin();
1394                         for (++i; i != inbufs.audio_end(); ++i) {
1395                                 dst.accumulate_with_gain_from(*i, nframes, offset, gain_coeff);
1396                         }
1397
1398                 }
1399
1400                 return;
1401         }
1402
1403         // More than 1 output, we should have 1 panner for each input
1404         assert(size() == inbufs.count().get(DataType::AUDIO));
1405         
1406         /* the terrible silence ... */
1407         for (BufferSet::audio_iterator i = outbufs.audio_begin(); i != outbufs.audio_end(); ++i) {
1408                 i->silence(nframes, offset);
1409         }
1410
1411         BufferSet::audio_iterator i = inbufs.audio_begin();
1412         for (iterator pan = begin(); pan != end(); ++pan, ++i) {
1413                 (*pan)->distribute (*i, outbufs, gain_coeff, nframes);
1414         }
1415 }
1416
1417 void
1418 Panner::distribute (BufferSet& inbufs, BufferSet& outbufs, nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset)
1419 {       
1420         if (outbufs.count().get(DataType::AUDIO) == 0) {
1421                 // Failing to deliver audio we were asked to deliver is a bug
1422                 assert(inbufs.count().get(DataType::AUDIO) == 0);
1423                 return;
1424         }
1425
1426         // We shouldn't be called in the first place...
1427         assert(!bypassed());
1428         assert(!empty());
1429
1430         // If we shouldn't play automation defer to distribute_no_automation
1431         if ( !( automation_state() & Play ||
1432                          ((automation_state() & Touch) && !touching()) ) ) {
1433
1434                 // Speed quietning
1435                 gain_t gain_coeff = 1.0;
1436                 if (fabsf(_session.transport_speed()) > 1.5f) {
1437                         gain_coeff = speed_quietning;
1438                 }
1439
1440                 distribute_no_automation(inbufs, outbufs, nframes, offset, gain_coeff);
1441                 return;
1442         }
1443
1444         // Otherwise.. let the automation flow, baby
1445         
1446         if (outbufs.count().get(DataType::AUDIO) == 1) {
1447
1448                 AudioBuffer& dst = outbufs.get_audio(0);
1449
1450                 // FIXME: apply gain automation?
1451
1452                 // copy the first
1453                 dst.read_from(inbufs.get_audio(0), nframes, offset);
1454
1455                 // accumulate starting with the second
1456                 BufferSet::audio_iterator i = inbufs.audio_begin();
1457                 for (++i; i != inbufs.audio_end(); ++i) {
1458                         dst.accumulate_from(*i, nframes, offset);
1459                 }
1460
1461                 return;
1462         }
1463
1464         // More than 1 output, we should have 1 panner for each input
1465         assert(size() == inbufs.count().get(DataType::AUDIO));
1466         
1467         /* the terrible silence ... */
1468         for (BufferSet::audio_iterator i = outbufs.audio_begin(); i != outbufs.audio_end(); ++i) {
1469                 i->silence(nframes, offset);
1470         }
1471
1472         BufferSet::audio_iterator i = inbufs.audio_begin();
1473         for (iterator pan = begin(); pan != end(); ++pan, ++i) {
1474                 (*pan)->distribute_automated (*i, outbufs, start_frame, end_frame, nframes, _session.pan_automation_buffer());
1475         }
1476 }
1477
1478 /* old school automation handling */
1479
1480 void
1481 Panner::set_name (string str)
1482 {
1483         automation_path = _session.automation_dir();
1484         automation_path += _session.snap_name();
1485         automation_path += "-pan-";
1486         automation_path += legalize_for_path (str);
1487         automation_path += ".automation";
1488 }
1489
1490 int
1491 Panner::load ()
1492 {
1493         char line[128];
1494         uint32_t linecnt = 0;
1495         float version;
1496         iterator sp;
1497         LocaleGuard lg (X_("POSIX"));
1498
1499         if (automation_path.length() == 0) {
1500                 return 0;
1501         }
1502         
1503         if (access (automation_path.c_str(), F_OK)) {
1504                 return 0;
1505         }
1506
1507         ifstream in (automation_path.c_str());
1508
1509         if (!in) {
1510                 error << string_compose (_("cannot open pan automation file %1 (%2)"),
1511                                   automation_path, strerror (errno))
1512                       << endmsg;
1513                 return -1;
1514         }
1515
1516         sp = begin();
1517
1518         while (in.getline (line, sizeof(line), '\n')) {
1519
1520                 if (++linecnt == 1) {
1521                         if (memcmp (line, X_("version"), 7) == 0) {
1522                                 if (sscanf (line, "version %f", &version) != 1) {
1523                                         error << string_compose(_("badly formed version number in pan automation event file \"%1\""), automation_path) << endmsg;
1524                                         return -1;
1525                                 }
1526                         } else {
1527                                 error << string_compose(_("no version information in pan automation event file \"%1\" (first line = %2)"), 
1528                                                  automation_path, line) << endmsg;
1529                                 return -1;
1530                         }
1531
1532                         continue;
1533                 }
1534
1535                 if (strlen (line) == 0 || line[0] == '#') {
1536                         continue;
1537                 }
1538
1539                 if (strcmp (line, "begin") == 0) {
1540                         
1541                         if (sp == end()) {
1542                                 error << string_compose (_("too many panner states found in pan automation file %1"),
1543                                                   automation_path)
1544                                       << endmsg;
1545                                 return -1;
1546                         }
1547
1548                         if ((*sp)->load (in, automation_path, linecnt)) {
1549                                 return -1;
1550                         }
1551                         
1552                         ++sp;
1553                 }
1554         }
1555
1556         return 0;
1557 }