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