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