1 /*
2  * Copyright (C) 2009-2012 Carl Hetherington <carl@carlh.net>
3  * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
4  * Copyright (C) 2009-2017 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2013-2017 Robin Gareus <robin@gareus.org>
6  * Copyright (C) 2018 Len Ovens <len@ovenwerks.net>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22 
23 #include <cmath>
24 #include <algorithm>
25 
26 #include "pbd/enumwriter.h"
27 #include "pbd/enum_convert.h"
28 
29 #include "ardour/amp.h"
30 #include "ardour/audioengine.h"
31 #include "ardour/buffer_set.h"
32 #include "ardour/debug.h"
33 #include "ardour/delivery.h"
34 #include "ardour/io.h"
35 #include "ardour/mute_master.h"
36 #include "ardour/pannable.h"
37 #include "ardour/panner_shell.h"
38 #include "ardour/port.h"
39 #include "ardour/session.h"
40 
41 #include "pbd/i18n.h"
42 
43 namespace PBD {
44 	DEFINE_ENUM_CONVERT(ARDOUR::Delivery::Role);
45 }
46 
47 namespace ARDOUR { class Panner; }
48 
49 using namespace std;
50 using namespace PBD;
51 using namespace ARDOUR;
52 
53 PBD::Signal0<void>            Delivery::PannersLegal;
54 bool                          Delivery::panners_legal = false;
55 
56 /* deliver to an existing IO object */
57 
Delivery(Session & s,boost::shared_ptr<IO> io,boost::shared_ptr<Pannable> pannable,boost::shared_ptr<MuteMaster> mm,const string & name,Role r)58 Delivery::Delivery (Session& s, boost::shared_ptr<IO> io, boost::shared_ptr<Pannable> pannable,
59                     boost::shared_ptr<MuteMaster> mm, const string& name, Role r)
60 	: IOProcessor(s, boost::shared_ptr<IO>(), (role_requires_output_ports (r) ? io : boost::shared_ptr<IO>()), name, (r == Send || r == Aux || r == Foldback))
61 	, _role (r)
62 	, _output_buffers (new BufferSet())
63 	, _current_gain (GAIN_COEFF_ZERO)
64 	, _no_outs_cuz_we_no_monitor (false)
65 	, _mute_master (mm)
66 	, _no_panner_reset (false)
67 {
68 	if (pannable) {
69 		bool is_send = false;
70 		if (r & (Delivery::Send|Delivery::Aux|Delivery::Foldback)) is_send = true;
71 		_panshell = boost::shared_ptr<PannerShell>(new PannerShell (_name, _session, pannable, is_send));
72 	}
73 
74 	_display_to_user = false;
75 
76 	if (_output) {
77 		_output->changed.connect_same_thread (*this, boost::bind (&Delivery::output_changed, this, _1, _2));
78 	}
79 }
80 
81 /* deliver to a new IO object */
82 
Delivery(Session & s,boost::shared_ptr<Pannable> pannable,boost::shared_ptr<MuteMaster> mm,const string & name,Role r)83 Delivery::Delivery (Session& s, boost::shared_ptr<Pannable> pannable, boost::shared_ptr<MuteMaster> mm, const string& name, Role r)
84 	: IOProcessor(s, false, (role_requires_output_ports (r) ? true : false), name, "", DataType::AUDIO, (r == Send || r == Aux || r == Foldback))
85 	, _role (r)
86 	, _output_buffers (new BufferSet())
87 	, _current_gain (GAIN_COEFF_ZERO)
88 	, _no_outs_cuz_we_no_monitor (false)
89 	, _mute_master (mm)
90 	, _no_panner_reset (false)
91 {
92 	if (pannable) {
93 		bool is_send = false;
94 		if (r & (Delivery::Send|Delivery::Aux|Delivery::Foldback)) is_send = true;
95 		_panshell = boost::shared_ptr<PannerShell>(new PannerShell (_name, _session, pannable, is_send));
96 	}
97 
98 	_display_to_user = false;
99 
100 	if (_output) {
101 		_output->changed.connect_same_thread (*this, boost::bind (&Delivery::output_changed, this, _1, _2));
102 	}
103 }
104 
105 
~Delivery()106 Delivery::~Delivery()
107 {
108 	DEBUG_TRACE (DEBUG::Destruction, string_compose ("delivery %1 destructor\n", _name));
109 
110 	/* this object should vanish from any signal callback lists
111 	   that it is on before we get any further. The full qualification
112 	   of the method name is not necessary, but is here to make it
113 	   clear that this call is about signals, not data flow connections.
114 	*/
115 
116 	ScopedConnectionList::drop_connections ();
117 
118 	delete _output_buffers;
119 }
120 
121 std::string
display_name() const122 Delivery::display_name () const
123 {
124 	switch (_role) {
125 	case Main:
126 		return _("main outs");
127 		break;
128 	case Listen:
129 		return _("listen");
130 		break;
131 	case Send:
132 	case Insert:
133 	default:
134 		return name();
135 	}
136 }
137 
138 bool
can_support_io_configuration(const ChanCount & in,ChanCount & out)139 Delivery::can_support_io_configuration (const ChanCount& in, ChanCount& out)
140 {
141 	if (_role == Main) {
142 
143 		/* the out buffers will be set to point to the port output buffers
144 		   of our output object.
145 		*/
146 
147 		if (_output) {
148 			if (_output->n_ports() != ChanCount::ZERO) {
149 				/* increase number of output ports if the processor chain requires it */
150 				out = ChanCount::max (_output->n_ports(), in);
151 				return true;
152 			} else {
153 				/* not configured yet - we will passthru */
154 				out = in;
155 				return true;
156 			}
157 		} else {
158 			fatal << "programming error: this should never be reached" << endmsg;
159 			abort(); /*NOTREACHED*/
160 		}
161 
162 
163 	} else if (_role == Insert) {
164 
165 		/* the output buffers will be filled with data from the *input* ports
166 		   of this Insert.
167 		*/
168 
169 		if (_input) {
170 			if (_input->n_ports() != ChanCount::ZERO) {
171 				out = _input->n_ports();
172 				return true;
173 			} else {
174 				/* not configured yet - we will passthru */
175 				out = in;
176 				return true;
177 			}
178 		} else {
179 			fatal << "programming error: this should never be reached" << endmsg;
180 			abort(); /*NOTREACHED*/
181 		}
182 
183 	} else {
184 		fatal << "programming error: this should never be reached" << endmsg;
185 	}
186 
187 	return false;
188 }
189 
190 /** Caller must hold process lock */
191 bool
configure_io(ChanCount in,ChanCount out)192 Delivery::configure_io (ChanCount in, ChanCount out)
193 {
194 #ifndef NDEBUG
195 	bool r = AudioEngine::instance()->process_lock().trylock();
196 	assert (!r && "trylock inside Delivery::configure_io");
197 #endif
198 
199 	/* check configuration by comparison with our I/O port configuration, if appropriate.
200 	   see ::can_support_io_configuration() for comments
201 	*/
202 
203 	if (_role == Main) {
204 
205 		if (_output) {
206 			if (_output->n_ports() != out) {
207 				if (_output->n_ports() != ChanCount::ZERO) {
208 					_output->ensure_io (out, false, this);
209 				} else {
210 					/* I/O not yet configured */
211 				}
212 			}
213 		}
214 
215 	} else if (_role == Insert) {
216 
217 		if (_input) {
218 			if (_input->n_ports() != in) {
219 				if (_input->n_ports() != ChanCount::ZERO) {
220 					fatal << _name << " programming error: configure_io called with " << in << " and " << out << " with " << _input->n_ports() << " input ports" << endmsg;
221 					abort(); /*NOTREACHED*/
222 				} else {
223 					/* I/O not yet configured */
224 				}
225 			}
226 		}
227 
228 	}
229 
230 	if (!Processor::configure_io (in, out)) {
231 		return false;
232 	}
233 
234 	reset_panner ();
235 
236 	return true;
237 }
238 
239 void
run(BufferSet & bufs,samplepos_t start_sample,samplepos_t end_sample,double,pframes_t nframes,bool result_required)240 Delivery::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double /*speed*/, pframes_t nframes, bool result_required)
241 {
242 	assert (_output);
243 
244 	PortSet& ports (_output->ports());
245 	gain_t tgain;
246 
247 	if (ports.num_ports () == 0) {
248 		goto out;
249 	}
250 
251 	if (!_active && !_pending_active) {
252 		_output->silence (nframes);
253 		goto out;
254 	}
255 
256 	/* this setup is not just for our purposes, but for anything that comes after us in the
257 	 * processing pathway that wants to use this->output_buffers() for some reason.
258 	 */
259 
260 	// TODO delayline -- latency-compensation
261 	output_buffers().get_backend_port_addresses (ports, nframes);
262 
263 	// this Delivery processor is not a derived type, and thus we assume
264 	// we really can modify the buffers passed in (it is almost certainly
265 	// the main output stage of a Route). Contrast with Send::run()
266 	// which cannot do this.
267 
268 	tgain = target_gain ();
269 
270 	if (tgain != _current_gain) {
271 		/* target gain has changed */
272 
273 		_current_gain = Amp::apply_gain (bufs, _session.nominal_sample_rate(), nframes, _current_gain, tgain);
274 
275 	} else if (tgain < GAIN_COEFF_SMALL) {
276 
277 		/* we were quiet last time, and we're still supposed to be quiet.
278 			 Silence the outputs, and make sure the buffers are quiet too,
279 			 */
280 
281 		_output->silence (nframes);
282 		if (result_required) {
283 			bufs.set_count (output_buffers().count ());
284 			Amp::apply_simple_gain (bufs, nframes, GAIN_COEFF_ZERO);
285 		}
286 		goto out;
287 
288 	} else if (tgain != GAIN_COEFF_UNITY) {
289 
290 		/* target gain has not changed, but is not unity */
291 		Amp::apply_simple_gain (bufs, nframes, tgain);
292 	}
293 
294 	// Speed quietning
295 
296 	if (fabs (_session.transport_speed()) > 1.5 && Config->get_quieten_at_speed ()) {
297 		Amp::apply_simple_gain (bufs, nframes, speed_quietning, false);
298 	}
299 
300 	// Panning
301 
302 	if (_panshell && !_panshell->bypassed() && _panshell->panner()) {
303 
304 		// Use the panner to distribute audio to output port buffers
305 
306 		_panshell->run (bufs, output_buffers(), start_sample, end_sample, nframes);
307 
308 		// non-audio data will not have been delivered by the panner
309 
310 		for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
311 			if (*t != DataType::AUDIO && bufs.count().get(*t) > 0) {
312 				_output->copy_to_outputs (bufs, *t, nframes, 0);
313 			}
314 		}
315 
316 	} else {
317 
318 		/* Do a 1:1 copy of data to output ports
319 
320 		   Audio is handled separately because we use 0 for the offset,
321 		   since the port offset is only used for timestamped events
322 		   (i.e. MIDI).
323 		*/
324 
325 		if (bufs.count().n_audio() > 0) {
326 			_output->copy_to_outputs (bufs, DataType::AUDIO, nframes, 0);
327 		}
328 
329 		for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
330 			if (*t != DataType::AUDIO && bufs.count().get(*t) > 0) {
331 				_output->copy_to_outputs (bufs, *t, nframes, 0);
332 			}
333 		}
334 	}
335 
336 	if (result_required) {
337 		/* "bufs" are internal, meaning they should never reflect
338 		   split-cycle offsets. So shift events back in time from where
339 		   they were for the external buffers associated with Ports.
340 		*/
341 
342 		const BufferSet& outs (output_buffers());
343 		bufs.set_count (output_buffers().count ());
344 
345 		for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
346 
347 			uint32_t n = 0;
348 			for (BufferSet::iterator b = bufs.begin (*t); b != bufs.end (*t); ++b) {
349 				if (outs.count ().get (*t) <= n) {
350 					continue;
351 				}
352 				b->read_from (outs.get_available (*t, n++), nframes, 0);
353 			}
354 		}
355 	}
356 
357 out:
358 	_active = _pending_active;
359 }
360 
361 XMLNode&
state()362 Delivery::state ()
363 {
364 	XMLNode& node (IOProcessor::state ());
365 
366 	if (_role & Main) {
367 		node.set_property("type", "main-outs");
368 	} else if (_role & Listen) {
369 		node.set_property("type", "listen");
370 	} else {
371 		node.set_property("type", "delivery");
372 	}
373 
374 	node.set_property("role", _role);
375 
376 	if (_panshell) {
377 		node.add_child_nocopy (_panshell->get_state ());
378 		if (_panshell->unlinked_pannable () && _role != Listen) {
379 			node.add_child_nocopy (_panshell->unlinked_pannable()->get_state ());
380 		}
381 	}
382 
383 	return node;
384 }
385 
386 int
set_state(const XMLNode & node,int version)387 Delivery::set_state (const XMLNode& node, int version)
388 {
389 	if (IOProcessor::set_state (node, version)) {
390 		return -1;
391 	}
392 
393 	if (node.get_property ("role", _role)) {
394 		// std::cerr << this << ' ' << _name << " set role to " << enum_2_string (_role) << std::endl;
395 	} else {
396 		// std::cerr << this << ' ' << _name << " NO ROLE INFO\n";
397 	}
398 
399 	XMLNode* pan_node = node.child (X_("PannerShell"));
400 
401 	if (pan_node && _panshell) {
402 		_panshell->set_state (*pan_node, version);
403 	}
404 
405 	reset_panner ();
406 
407 	XMLNode* pannnode = node.child (X_("Pannable"));
408 
409 	if (_panshell && _panshell->unlinked_pannable() && pannnode) {
410 		_panshell->unlinked_pannable()->set_state (*pannnode, version);
411 	}
412 
413 	return 0;
414 }
415 
416 void
unpan()417 Delivery::unpan ()
418 {
419 	/* caller must hold process lock */
420 
421 	_panshell.reset ();
422 }
423 
424 uint32_t
pan_outs() const425 Delivery::pan_outs () const
426 {
427 	if (_output) {
428 		return _output->n_ports().n_audio();
429 	}
430 
431 	return _configured_output.n_audio();
432 }
433 
434 void
reset_panner()435 Delivery::reset_panner ()
436 {
437 	if (panners_legal) {
438 		if (!_no_panner_reset) {
439 
440 			if (_panshell && _role != Insert && _role != Listen) {
441 				_panshell->configure_io (ChanCount (DataType::AUDIO, pans_required()), ChanCount (DataType::AUDIO, pan_outs()));
442 			}
443 		}
444 
445 	} else {
446 		panner_legal_c.disconnect ();
447 		PannersLegal.connect_same_thread (panner_legal_c, boost::bind (&Delivery::panners_became_legal, this));
448 	}
449 }
450 
451 void
panners_became_legal()452 Delivery::panners_became_legal ()
453 {
454 	if (_panshell && _role != Insert) {
455 		_panshell->configure_io (ChanCount (DataType::AUDIO, pans_required()), ChanCount (DataType::AUDIO, pan_outs()));
456 	}
457 
458 	panner_legal_c.disconnect ();
459 }
460 
461 void
defer_pan_reset()462 Delivery::defer_pan_reset ()
463 {
464 	_no_panner_reset = true;
465 }
466 
467 void
allow_pan_reset()468 Delivery::allow_pan_reset ()
469 {
470 	_no_panner_reset = false;
471 	reset_panner ();
472 }
473 
474 
475 int
disable_panners()476 Delivery::disable_panners ()
477 {
478 	panners_legal = false;
479 	return 0;
480 }
481 
482 void
reset_panners()483 Delivery::reset_panners ()
484 {
485 	panners_legal = true;
486 	PannersLegal ();
487 }
488 
489 void
flush_buffers(samplecnt_t nframes)490 Delivery::flush_buffers (samplecnt_t nframes)
491 {
492 	/* io_lock, not taken: function must be called from Session::process() calltree */
493 
494 	if (!_output) {
495 		return;
496 	}
497 
498 	PortSet& ports (_output->ports());
499 
500 	for (PortSet::iterator i = ports.begin(); i != ports.end(); ++i) {
501 		i->flush_buffers (nframes);
502 	}
503 }
504 
505 void
non_realtime_transport_stop(samplepos_t now,bool flush)506 Delivery::non_realtime_transport_stop (samplepos_t now, bool flush)
507 {
508 	Processor::non_realtime_transport_stop (now, flush);
509 
510 	if (_panshell) {
511 		_panshell->pannable()->non_realtime_transport_stop (now, flush);
512 	}
513 
514 	if (_output) {
515 		PortSet& ports (_output->ports());
516 
517 		for (PortSet::iterator i = ports.begin(); i != ports.end(); ++i) {
518 			i->transport_stopped ();
519 		}
520 	}
521 }
522 
523 void
realtime_locate(bool for_loop_end)524 Delivery::realtime_locate (bool for_loop_end)
525 {
526 	if (_output) {
527 		PortSet& ports (_output->ports());
528 
529 		for (PortSet::iterator i = ports.begin(); i != ports.end(); ++i) {
530 			i->realtime_locate (for_loop_end);
531 		}
532 	}
533 }
534 
535 gain_t
target_gain()536 Delivery::target_gain ()
537 {
538 	/* if we've been requested to deactivate, our target gain is zero */
539 
540 	if (!_pending_active) {
541 		return GAIN_COEFF_ZERO;
542 	}
543 
544 	/* if we've been told not to output because its a monitoring situation and
545 	   we're not monitoring, then be quiet.
546 	*/
547 
548 	if (_no_outs_cuz_we_no_monitor) {
549 		return GAIN_COEFF_ZERO;
550 	}
551 
552 	MuteMaster::MutePoint mp = MuteMaster::Main; // stupid gcc uninit warning
553 
554 	switch (_role) {
555 		case Main:
556 			mp = MuteMaster::Main;
557 			break;
558 		case Listen:
559 			mp = MuteMaster::Listen;
560 			break;
561 		case Send:
562 		case Insert:
563 		case Aux:
564 		case Foldback:
565 			if (_pre_fader) {
566 				mp = MuteMaster::PreFader;
567 			} else {
568 				mp = MuteMaster::PostFader;
569 			}
570 			break;
571 	}
572 
573 	gain_t desired_gain = _mute_master->mute_gain_at (mp);
574 
575 	if (_gain_control) {
576 		desired_gain *= _gain_control->get_value();
577 	}
578 
579 	if (_role == Listen && _session.monitor_out() && !_session.listening()) {
580 
581 		/* nobody is soloed, and this delivery is a listen-send to the
582 		 * control/monitor/listen bus, we should be silent since
583 		 * it gets its signal from the master out.
584 		 */
585 
586 		desired_gain = GAIN_COEFF_ZERO;
587 	}
588 
589 	return desired_gain;
590 }
591 
592 void
no_outs_cuz_we_no_monitor(bool yn)593 Delivery::no_outs_cuz_we_no_monitor (bool yn)
594 {
595 	_no_outs_cuz_we_no_monitor = yn;
596 }
597 
598 bool
set_name(const std::string & name)599 Delivery::set_name (const std::string& name)
600 {
601 	bool ret = IOProcessor::set_name (name);
602 
603 	if (ret && _panshell) {
604 		ret = _panshell->set_name (name);
605 	}
606 
607 	return ret;
608 }
609 
610 bool ignore_output_change = false;
611 
612 void
output_changed(IOChange change,void *)613 Delivery::output_changed (IOChange change, void* /*src*/)
614 {
615 	if (change.type & IOChange::ConfigurationChanged) {
616 		reset_panner ();
617 		_output_buffers->attach_buffers (_output->ports ());
618 	}
619 }
620 
621 boost::shared_ptr<Panner>
panner() const622 Delivery::panner () const
623 {
624 	if (_panshell) {
625 		return _panshell->panner();
626 	} else {
627 		return boost::shared_ptr<Panner>();
628 	}
629 }
630 
631