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