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