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