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