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