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