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