1 /*
2  * Copyright (C) 2013-2016 Tim Mayberry <mojofunk@gmail.com>
3  * Copyright (C) 2013-2017 Paul Davis <paul@linuxaudiosystems.com>
4  * Copyright (C) 2014-2016 Robin Gareus <robin@gareus.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 
21 #ifndef __libardour_audiobackend_h__
22 #define __libardour_audiobackend_h__
23 
24 #include <string>
25 #include <vector>
26 
27 #include <stdint.h>
28 #include <stdlib.h>
29 
30 #include <boost/function.hpp>
31 
32 #include "ardour/audioengine.h"
33 #include "ardour/libardour_visibility.h"
34 #include "ardour/port_engine.h"
35 #include "ardour/types.h"
36 
37 #ifdef ARDOURBACKEND_DLL_EXPORTS // defined if we are building the ARDOUR Panners DLLs (instead of using them)
38 # define ARDOURBACKEND_API LIBARDOUR_DLL_EXPORT
39 #else
40 # define ARDOURBACKEND_API LIBARDOUR_DLL_IMPORT
41 #endif
42 #define ARDOURBACKEND_LOCAL LIBARDOUR_DLL_LOCAL
43 
44 namespace ARDOUR
45 {
46 struct LIBARDOUR_API AudioBackendInfo {
47 	const char* name;
48 
49 	/** Using arg1 and arg2, initialize this audiobackend.
50 	 *
51 	 * Returns zero on success, non-zero otherwise.
52 	 */
53 	int (*instantiate) (const std::string& arg1, const std::string& arg2);
54 
55 	/** Release all resources associated with this audiobackend */
56 	int (*deinstantiate) (void);
57 
58 	/** Factory method to create an AudioBackend-derived class.
59 	 *
60 	 * Returns a valid shared_ptr to the object if successfull,
61 	 * or a "null" shared_ptr otherwise.
62 	 */
63 	boost::shared_ptr<AudioBackend> (*factory) (AudioEngine&);
64 
65 	/** Return true if the underlying mechanism/API has been
66 	 * configured and does not need (re)configuration in order
67 	 * to be usable. Return false otherwise.
68 	 *
69 	 * Note that this may return true if (re)configuration, even though
70 	 * not currently required, is still possible.
71 	 */
72 	bool (*already_configured) ();
73 
74 	/** Return true if the underlying mechanism/API can be
75 	 * used on the given system.
76 	 *
77 	 * If this function returns false, the backend is not
78 	 * listed in the engine dialog.
79 	 */
80 	bool (*available) ();
81 };
82 
83 /** AudioBackend is an high-level abstraction for interacting with the operating system's
84  * audio and midi I/O.
85  */
86 class LIBARDOUR_API AudioBackend : public PortEngine
87 {
88 public:
AudioBackend(AudioEngine & e,AudioBackendInfo & i)89 	AudioBackend (AudioEngine& e, AudioBackendInfo& i)
90 	        : PortEngine (e)
91 	        , _info (i)
92 	        , engine (e)
93 	{}
94 
~AudioBackend()95 	virtual ~AudioBackend () {}
96 
97 	enum ErrorCode {
98 		NoError                    = 0,
99 		BackendInitializationError = -64,
100 		BackendDeinitializationError,
101 		BackendReinitializationError,
102 		AudioDeviceOpenError,
103 		AudioDeviceCloseError,
104 		AudioDeviceInvalidError,
105 		AudioDeviceNotAvailableError,
106 		AudioDeviceNotConnectedError,
107 		AudioDeviceReservationError,
108 		AudioDeviceIOError,
109 		MidiDeviceOpenError,
110 		MidiDeviceCloseError,
111 		MidiDeviceNotAvailableError,
112 		MidiDeviceNotConnectedError,
113 		MidiDeviceIOError,
114 		SampleFormatNotSupportedError,
115 		SampleRateNotSupportedError,
116 		RequestedInputLatencyNotSupportedError,
117 		RequestedOutputLatencyNotSupportedError,
118 		PeriodSizeNotSupportedError,
119 		PeriodCountNotSupportedError,
120 		DeviceConfigurationNotSupportedError,
121 		ChannelCountNotSupportedError,
122 		InputChannelCountNotSupportedError,
123 		OutputChannelCountNotSupportedError,
124 		AquireRealtimePermissionError,
125 		SettingAudioThreadPriorityError,
126 		SettingMIDIThreadPriorityError,
127 		ProcessThreadStartError,
128 		FreewheelThreadStartError,
129 		PortRegistrationError,
130 		PortReconnectError,
131 		OutOfMemoryError,
132 	};
133 
134 	static std::string get_error_string (ErrorCode);
135 
136 	enum StandardDeviceName {
137 		DeviceNone,
138 		DeviceDefault
139 	};
140 
141 	static std::string get_standard_device_name (StandardDeviceName);
142 
143 	/** Return the AudioBackendInfo object from which this backend
144 	 * was constructed.
145 	 */
info()146 	AudioBackendInfo& info () const
147 	{
148 		return _info;
149 	}
150 
151 	/** Return the name of this backend.
152 	 *
153 	 * Should use a well-known, unique term. Expected examples
154 	 * might include "JACK", "CoreAudio", "ASIO" etc.
155 	 */
156 	virtual std::string name () const = 0;
157 
158 	/** Return true if the callback from the underlying mechanism/API
159 	 * (CoreAudio, JACK, ASIO etc.) occurs in a thread subject to realtime
160 	 * constraints. Return false otherwise.
161 	 */
162 	virtual bool is_realtime () const = 0;
163 
client_real_time_priority()164 	virtual int client_real_time_priority () { return PBD_RT_PRI_PROC; }
165 
166 	/* Discovering devices and parameters */
167 
168 	/** Return true if this backend requires the selection of a "driver"
169 	 * before any device can be selected. Return false otherwise.
170 	 *
171 	 * Intended mainly to differentiate between meta-APIs like JACK
172 	 * which can still expose different backends (such as ALSA or CoreAudio
173 	 * or FFADO or netjack) and those like ASIO or CoreAudio which
174 	 * do not.
175 	 */
requires_driver_selection()176 	virtual bool requires_driver_selection () const
177 	{
178 		return false;
179 	}
180 
181 	/** If the return value of requires_driver_selection() is true,
182 	 * then this function can return the list of known driver names.
183 	 *
184 	 * If the return value of requires_driver_selection() is false,
185 	 * then this function should not be called. If it is called
186 	 * its return value is an empty vector of strings.
187 	 */
enumerate_drivers()188 	virtual std::vector<std::string> enumerate_drivers () const
189 	{
190 		return std::vector<std::string> ();
191 	}
192 
193 	/** Returns zero if the backend can successfully use \p drivername
194 	 * as the driver, non-zero otherwise.
195 	 *
196 	 * Should not be used unless the backend returns true from
197 	 * requires_driver_selection()
198 	 */
set_driver(const std::string & drivername)199 	virtual int set_driver (const std::string& drivername)
200 	{
201 		return 0;
202 	}
203 
204 	/** used to list device names along with whether or not they are currently
205 	 *  available.
206 	 */
207 	struct DeviceStatus {
208 		std::string name;
209 		bool        available;
210 
DeviceStatusDeviceStatus211 		DeviceStatus (const std::string& s, bool avail)
212 		        : name (s)
213 		        , available (avail)
214 		{}
215 	};
216 
217 	/** An optional alternate interface for backends to provide a facility to
218 	 * select separate input and output devices.
219 	 *
220 	 * If a backend returns true then enumerate_input_devices() and
221 	 * enumerate_output_devices() will be used instead of enumerate_devices()
222 	 * to enumerate devices. Similarly set_input/output_device_name() should
223 	 * be used to set devices instead of set_device_name().
224 	 */
use_separate_input_and_output_devices()225 	virtual bool use_separate_input_and_output_devices () const
226 	{
227 		return false;
228 	}
229 
230 	/* Return true if the backend uses separate I/O devices only for the case
231 	 * of allowing one to be "None".
232 	 *
233 	 * ie. Input Device must match Output Device, except if either of them
234 	 * is get_standard_device_name (DeviceNone).
235 	 */
match_input_output_devices_or_none()236 	virtual bool match_input_output_devices_or_none () const
237 	{
238 		return false;
239 	}
240 
241 	/** Returns a collection of DeviceStatuses identifying devices discovered
242 	 * by this backend since the start of the process.
243 	 *
244 	 * Any of the names in each DeviceStatus may be used to identify a
245 	 * device in other calls to the backend, though any of them may become
246 	 * invalid at any time.
247 	 */
248 	virtual std::vector<DeviceStatus> enumerate_devices () const = 0;
249 
250 	/** Returns a collection of DeviceStatuses identifying input devices
251 	 * discovered by this backend since the start of the process.
252 	 *
253 	 * Any of the names in each DeviceStatus may be used to identify a
254 	 * device in other calls to the backend, though any of them may become
255 	 * invalid at any time.
256 	 */
enumerate_input_devices()257 	virtual std::vector<DeviceStatus> enumerate_input_devices () const
258 	{
259 		return std::vector<DeviceStatus> ();
260 	}
261 
262 	/** Returns a collection of DeviceStatuses identifying output devices
263 	 * discovered by this backend since the start of the process.
264 	 *
265 	 * Any of the names in each DeviceStatus may be used to identify a
266 	 * device in other calls to the backend, though any of them may become
267 	 * invalid at any time.
268 	 */
enumerate_output_devices()269 	virtual std::vector<DeviceStatus> enumerate_output_devices () const
270 	{
271 		return std::vector<DeviceStatus> ();
272 	}
273 
274 	/** An interface to set buffers/period for playback latency.
275 	 * useful for ALSA or JACK/ALSA on Linux.
276 	 *
277 	 * @return true if the backend supports period-size configuration
278 	 */
can_set_period_size()279 	virtual bool can_set_period_size () const
280 	{
281 		return false;
282 	}
283 
284 	/** Returns a vector of supported period-sizes for the given driver */
available_period_sizes(const std::string & driver,const std::string & device)285 	virtual std::vector<uint32_t> available_period_sizes (const std::string& driver, const std::string& device) const
286 	{
287 		return std::vector<uint32_t> ();
288 	}
289 
290 	/** Set the period size to be used.
291 	 * must be called before starting the backend.
292 	 */
set_peridod_size(uint32_t)293 	virtual int set_peridod_size (uint32_t)
294 	{
295 		return -1;
296 	}
297 
298 	/**
299 	 * @return true if backend supports requesting an update to the device list
300 	 * and any cached properties associated with the devices.
301 	 */
can_request_update_devices()302 	virtual bool can_request_update_devices ()
303 	{
304 		return false;
305 	}
306 
307 	/**
308 	 * Request an update to the list of devices returned in the enumerations.
309 	 * The Backend must return true from can_request_update_devices to support
310 	 * this interface.
311 	 * @return true if the devices were updated
312 	 */
update_devices()313 	virtual bool update_devices ()
314 	{
315 		return false;
316 	}
317 
318 	/**
319 	 * @return true if backend supports a blocking or buffered mode, false by
320 	 * default unless implemented by a derived class.
321 	 */
can_use_buffered_io()322 	virtual bool can_use_buffered_io ()
323 	{
324 		return false;
325 	}
326 
327 	/**
328 	 * Set the backend to use a blocking or buffered I/O mode
329 	 */
set_use_buffered_io(bool)330 	virtual void set_use_buffered_io (bool) {}
331 
332 	/**
333 	 * @return Set the backend to use a blocking or buffered I/O mode, false by
334 	 * default unless implemented by a derived class.
335 	 */
get_use_buffered_io()336 	virtual bool get_use_buffered_io ()
337 	{
338 		return false;
339 	}
340 
341 	/** Returns a collection of float identifying sample rates that are
342 	 * potentially usable with the hardware identified by \p device .
343 	 * Any of these values may be supplied in other calls to this backend
344 	 * as the desired sample rate to use with the name device, but the
345 	 * requested sample rate may turn out to be unavailable, or become invalid
346 	 * at any time.
347 	 */
348 	virtual std::vector<float> available_sample_rates (const std::string& device) const = 0;
349 
350 	/* backends that suppor586t separate input and output devices should
351 	 * implement this function and return an intersection (not union) of available
352 	 * sample rates valid for the given input + output device combination.
353 	 */
available_sample_rates2(const std::string & input_device,const std::string & output_device)354 	virtual std::vector<float> available_sample_rates2 (const std::string& input_device, const std::string& output_device) const
355 	{
356 		std::vector<float> input_sizes  = available_sample_rates (input_device);
357 		std::vector<float> output_sizes = available_sample_rates (output_device);
358 		std::vector<float> rv;
359 		std::set_union (input_sizes.begin (), input_sizes.end (),
360 		                output_sizes.begin (), output_sizes.end (),
361 		                std::back_inserter (rv));
362 		return rv;
363 	}
364 
365 	/* Returns the default sample rate that will be shown to the user when
366 	 * configuration options are first presented. If the derived class
367 	 * needs or wants to override this, it can. It also MUST override this
368 	 * if there is any chance that an SR of 44.1kHz is not in the list
369 	 * returned by available_sample_rates()
370 	 */
default_sample_rate()371 	virtual float default_sample_rate () const
372 	{
373 		return 44100.0;
374 	}
375 
376 	/** Returns a collection of uint32 identifying buffer sizes that are
377 	 * potentially usable with the hardware identified by \p device .
378 	 * Any of these values may be supplied in other calls to this backend
379 	 * as the desired buffer size to use with the name device, but the
380 	 * requested buffer size may turn out to be unavailable, or become invalid
381 	 * at any time.
382 	 */
383 	virtual std::vector<uint32_t> available_buffer_sizes (const std::string& device) const = 0;
384 
385 	/* backends that support separate input and output devices should
386 	 * implement this function and return an intersection (not union) of available
387 	 * buffer sizes valid for the given input + output device combination.
388 	 */
available_buffer_sizes2(const std::string & input_device,const std::string & output_device)389 	virtual std::vector<uint32_t> available_buffer_sizes2 (const std::string& input_device, const std::string& output_device) const
390 	{
391 		std::vector<uint32_t> input_rates  = available_buffer_sizes (input_device);
392 		std::vector<uint32_t> output_rates = available_buffer_sizes (output_device);
393 		std::vector<uint32_t> rv;
394 		std::set_union (input_rates.begin (), input_rates.end (),
395 		                output_rates.begin (), output_rates.end (),
396 		                std::back_inserter (rv));
397 		return rv;
398 	}
399 	/* Returns the default buffer size that will be shown to the user when
400 	 * configuration options are first presented. If the derived class
401 	 * needs or wants to override this, it can. It also MUST override this
402 	 * if there is any chance that a buffer size of 1024 is not in the list
403 	 * returned by available_buffer_sizes()
404 	 */
default_buffer_size(const std::string & device)405 	virtual uint32_t default_buffer_size (const std::string& device) const
406 	{
407 		return 1024;
408 	}
409 
410 	/** Returns the maximum number of input channels that are potentially
411 	 * usable with the hardware identified by \p device . Any number from 1
412 	 * to the value returned may be supplied in other calls to this backend as
413 	 * the input channel count to use with the name device, but the requested
414 	 * count may turn out to be unavailable, or become invalid at any time.
415 	 */
416 	virtual uint32_t available_input_channel_count (const std::string& device) const = 0;
417 
418 	/** Returns the maximum number of output channels that are potentially
419 	 * usable with the hardware identified by \p device . Any number from 1
420 	 * to the value returned may be supplied in other calls to this backend as
421 	 * the output channel count to use with the name device, but the requested
422 	 * count may turn out to be unavailable, or become invalid at any time.
423 	 */
424 	virtual uint32_t available_output_channel_count (const std::string& device) const = 0;
425 
426 	/* Return true if the derived class can change the sample rate of the
427 	 * device in use while the device is already being used. Return false
428 	 * otherwise. (example: JACK cannot do this as of September 2013)
429 	 */
430 	virtual bool can_change_sample_rate_when_running () const = 0;
431 	/* Return true if the derived class can change the buffer size of the
432 	 * device in use while the device is already being used. Return false
433 	 * otherwise.
434 	 */
435 	virtual bool can_change_buffer_size_when_running () const = 0;
436 
437 	/** return true if the backend is configured using a single
438 	 * full-duplex device and measuring systemic latency can
439 	 * produce meaningful results.
440 	 */
441 	virtual bool can_measure_systemic_latency () const = 0;
442 
443 	/** return true if the backend can measure and update
444 	 * systemic latencies without restart.
445 	 */
can_change_systemic_latency_when_running()446 	virtual bool can_change_systemic_latency_when_running () const
447 	{
448 		return false;
449 	}
450 
451 	/* Set the hardware parameters.
452 	 *
453 	 * If called when the current state is stopped or paused,
454 	 * the changes will not take effect until the state changes to running.
455 	 *
456 	 * If called while running, the state will change as fast as the
457 	 * implementation allows.
458 	 *
459 	 * All set_*() methods return zero on success, non-zero otherwise.
460 	 */
461 
462 	/** Set the name of the device to be used */
463 	virtual int set_device_name (const std::string&) = 0;
464 
465 	/** Set the name of the input device to be used if using separate
466 	 * input/output devices.
467 	 *
468 	 * @see use_separate_input_and_output_devices()
469 	 */
set_input_device_name(const std::string &)470 	virtual int set_input_device_name (const std::string&)
471 	{
472 		return 0;
473 	}
474 
475 	/** Set the name of the output device to be used if using separate
476 	 * input/output devices.
477 	 *
478 	 * @see use_separate_input_and_output_devices()
479 	 */
set_output_device_name(const std::string &)480 	virtual int set_output_device_name (const std::string&)
481 	{
482 		return 0;
483 	}
484 
485 	/** Deinitialize and destroy current device */
drop_device()486 	virtual int drop_device ()
487 	{
488 		return 0;
489 	};
490 
491 	/** Set the sample rate to be used */
492 	virtual int set_sample_rate (float) = 0;
493 
494 	/** Set the buffer size to be used.
495 	 *
496 	 * The device is assumed to use a double buffering scheme, so that one
497 	 * buffer's worth of data can be processed by hardware while software works
498 	 * on the other buffer. All known suitable audio APIs support this model
499 	 * (though ALSA allows for alternate numbers of buffers, and CoreAudio
500 	 * doesn't directly expose the concept).
501 	 */
502 	virtual int set_buffer_size (uint32_t) = 0;
503 
504 	/** Set the preferred underlying hardware data layout.
505 	 * If \p yn is true, then the hardware will interleave
506 	 * samples for successive channels; otherwise, the hardware will store
507 	 * samples for a single channel contiguously.
508 	 *
509 	 * Setting this does not change the fact that all data streams
510 	 * to and from Ports are mono (essentially, non-interleaved)
511 	 */
512 	virtual int set_interleaved (bool yn) = 0;
513 
514 	/** Set the number of input channels that should be used */
515 	virtual int set_input_channels (uint32_t) = 0;
516 
517 	/** Set the number of output channels that should be used */
518 	virtual int set_output_channels (uint32_t) = 0;
519 
520 	/** Set the (additional) input latency that cannot be determined via
521 	 * the implementation's underlying code (e.g. latency from
522 	 * external D-A/D-A converters. Units are samples.
523 	 */
524 	virtual int set_systemic_input_latency (uint32_t) = 0;
525 
526 	/** Set the (additional) output latency that cannot be determined via
527 	 * the implementation's underlying code (e.g. latency from
528 	 * external D-A/D-A converters. Units are samples.
529 	 */
530 	virtual int set_systemic_output_latency (uint32_t) = 0;
531 
532 	/** Set the (additional) input latency for a specific midi device,
533 	 * or if the identifier is empty, apply to all midi devices.
534 	 */
535 	virtual int set_systemic_midi_input_latency (std::string const, uint32_t) = 0;
536 
537 	/** Set the (additional) output latency for a specific midi device,
538 	 * or if the identifier is empty, apply to all midi devices.
539 	 */
540 	virtual int set_systemic_midi_output_latency (std::string const, uint32_t) = 0;
541 
542 	/* Retrieving parameters */
543 
544 	virtual std::string device_name () const = 0;
input_device_name()545 	virtual std::string input_device_name () const
546 	{
547 		return std::string ();
548 	}
549 
output_device_name()550 	virtual std::string output_device_name () const
551 	{
552 		return std::string ();
553 	}
554 
555 	virtual float    sample_rate () const                                   = 0;
556 	virtual uint32_t buffer_size () const                                   = 0;
557 	virtual bool     interleaved () const                                   = 0;
558 	virtual uint32_t input_channels () const                                = 0;
559 	virtual uint32_t output_channels () const                               = 0;
560 	virtual uint32_t systemic_input_latency () const                        = 0;
561 	virtual uint32_t systemic_output_latency () const                       = 0;
562 	virtual uint32_t systemic_midi_input_latency (std::string const) const  = 0;
563 	virtual uint32_t systemic_midi_output_latency (std::string const) const = 0;
564 
565 	/* defaults as reported by device driver */
systemic_hw_input_latency()566 	virtual uint32_t systemic_hw_input_latency () const { return 0; }
systemic_hw_output_latency()567 	virtual uint32_t systemic_hw_output_latency () const { return 0; }
568 
period_size()569 	virtual uint32_t period_size () const { return 0; }
570 
571 	/** override this if this implementation returns true from
572 	 * requires_driver_selection()
573 	 */
driver_name()574 	virtual std::string driver_name () const
575 	{
576 		return std::string ();
577 	}
578 
579 	/** Return the name of a control application for the
580 	 * selected/in-use device. If no such application exists,
581 	 * or if no device has been selected or is in-use,
582 	 * return an empty string.
583 	 */
584 	virtual std::string control_app_name () const = 0;
585 
586 	/** Launch the control app for the currently in-use or
587 	 * selected device. May do nothing if the control
588 	 * app is undefined or cannot be launched.
589 	 */
590 	virtual void launch_control_app () = 0;
591 
592 	/* @return a vector of strings that describe the available
593 	 * MIDI options.
594 	 *
595 	 * These can be presented to the user to decide which
596 	 * MIDI drivers, options etc. can be used. The returned strings
597 	 * should be thought of as the key to a map of possible
598 	 * approaches to handling MIDI within the backend. Ensure that
599 	 * the strings will make sense to the user.
600 	 */
601 	virtual std::vector<std::string> enumerate_midi_options () const = 0;
602 
603 	/* Request the use of the MIDI option named \p option, which
604 	 * should be one of the strings returned by enumerate_midi_options()
605 	 *
606 	 * @return zero if successful, non-zero otherwise
607 	 */
608 	virtual int set_midi_option (const std::string& option) = 0;
609 
610 	virtual std::string midi_option () const = 0;
611 
612 	/** Detailed MIDI device list - if available */
613 	virtual std::vector<DeviceStatus> enumerate_midi_devices () const = 0;
614 
615 	/** mark a midi-devices as enabled */
616 	virtual int set_midi_device_enabled (std::string const, bool) = 0;
617 
618 	/** query if a midi-device is enabled */
619 	virtual bool midi_device_enabled (std::string const) const = 0;
620 
621 	/** if backend supports systemic_midi_[in|ou]tput_latency() */
622 	virtual bool can_set_systemic_midi_latencies () const = 0;
623 
624 	/* State Control */
625 
626 	/** Start using the device named in the most recent call
627 	 * to set_device(), with the parameters set by various
628 	 * the most recent calls to set_sample_rate() etc. etc.
629 	 *
630 	 * At some undetermined time after this function is successfully called,
631 	 * the backend will start calling the process_callback method of
632 	 * the AudioEngine referenced by \ref engine. These calls will
633 	 * occur in a thread created by and/or under the control of the backend.
634 	 *
635 	 * @param for_latency_measurement if true, the device is being started
636 	 *        to carry out latency measurements and the backend should this
637 	 *        take care to return latency numbers that do not reflect
638 	 *        any existing systemic latency settings.
639 	 *
640 	 * Return zero if successful, negative values otherwise.
641 	 *
642 	 *
643 	 * Why is this non-virtual but \ref _start() is virtual ?
644 	 * Virtual methods with default parameters create possible ambiguity
645 	 * because a derived class may implement the same method with a different
646 	 * type or value of default parameter.
647 	 *
648 	 * So we make this non-virtual method to avoid possible overrides of
649 	 * default parameters. See Scott Meyers or other books on C++ to understand
650 	 * this pattern, or possibly just this:
651 	 *
652 	 * http://stackoverflow.com/questions/12139786/good-pratice-default-arguments-for-pure-virtual-method
653 	 */
654 	int start (bool for_latency_measurement = false)
655 	{
656 		return _start (for_latency_measurement);
657 	}
658 
659 	/** Stop using the device currently in use.
660 	 *
661 	 * If the function is successfully called, no subsequent calls to the
662 	 * process_callback() of \ref engine will be made after the function
663 	 * returns, until parameters are reset and start() are called again.
664 	 *
665 	 * The backend is considered to be un-configured after a successful
666 	 * return, and requires calls to set hardware parameters before it can be
667 	 * start()-ed again. See pause() for a way to avoid this. stop() should
668 	 * only be used when reconfiguration is required OR when there are no
669 	 * plans to use the backend in the future with a reconfiguration.
670 	 *
671 	 * Return zero if successful, 1 if the device is not in use, negative values on error
672 	 */
673 	virtual int stop () = 0;
674 
675 	/** Reset device.
676 	 *
677 	 * Return zero if successful, negative values on error
678 	 */
679 	virtual int reset_device () = 0;
680 
681 	/** While remaining connected to the device, and without changing its
682 	 * configuration, start (or stop) calling the process_callback of the engine
683 	 * without waiting for the device. Once process_callback() has returned, it
684 	 * will be called again immediately, thus allowing for faster-than-realtime
685 	 * processing.
686 	 *
687 	 * All registered ports remain in existence and all connections remain
688 	 * unaltered. However, any physical ports should NOT be used by the
689 	 * process_callback() during freewheeling - the data behaviour is undefined.
690 	 *
691 	 * If \p start_stop is true, begin this behaviour; otherwise cease this
692 	 * behaviour if it currently occuring, and return to calling
693 	 * process_callback() of the engine by waiting for the device.
694 	 *
695 	 * @param start_stop true to engage freewheel processing
696 	 * @return zero on success, non-zero otherwise.
697 	 */
698 	virtual int freewheel (bool start_stop) = 0;
699 
700 	/** return the fraction of the time represented by the current buffer
701 	 * size that is being used for each buffer process cycle, as a value
702 	 * from 0.0 to 1.0
703 	 *
704 	 * E.g. if the buffer size represents 5msec and current processing
705 	 * takes 1msec, the returned value should be 0.2.
706 	 *
707 	 * Implementations can feel free to smooth the values returned over
708 	 * time (e.g. high pass filtering, or its equivalent).
709 	 */
710 	virtual float dsp_load () const = 0;
711 
712 	/* Transport Control (JACK is the only audio API that currently offers
713 	 * the concept of shared transport control)
714 	 */
715 
716 	/** Attempt to change the transport state to TransportRolling.  */
transport_start()717 	virtual void transport_start () {}
718 
719 	/** Attempt to change the transport state to TransportStopped.  */
transport_stop()720 	virtual void transport_stop () {}
721 
722 	/** return the current transport state */
transport_state()723 	virtual TransportState transport_state () const
724 	{
725 		return TransportStopped;
726 	}
727 
728 	/** Attempt to locate the transport to \p pos */
transport_locate(samplepos_t pos)729 	virtual void transport_locate (samplepos_t pos) {}
730 
731 	/** Return the current transport location, in samples measured
732 	 * from the origin (defined by the transport time master)
733 	 */
transport_sample()734 	virtual samplepos_t transport_sample () const
735 	{
736 		return 0;
737 	}
738 
739 	/** If \p yn is true, become the time master for any inter-application transport
740 	 * timebase, otherwise cease to be the time master for the same.
741 	 *
742 	 * Return zero on success, non-zero otherwise
743 	 *
744 	 * JACK is the only currently known audio API with the concept of a shared
745 	 * transport timebase.
746 	 */
set_time_master(bool yn)747 	virtual int set_time_master (bool yn)
748 	{
749 		return 0;
750 	}
751 
usecs_per_cycle()752 	virtual int usecs_per_cycle () const
753 	{
754 		return 1000000 * (buffer_size () / sample_rate ());
755 	}
756 	virtual size_t raw_buffer_size (DataType t) = 0;
757 
758 	/* Process time */
759 
760 	/** return the time according to the sample clock in use, measured in
761 	 * samples since an arbitrary zero time in the past. The value should
762 	 * increase monotonically and linearly, without interruption from any
763 	 * source (including CPU frequency scaling).
764 	 *
765 	 * It is extremely likely that any implementation will use a DLL, since
766 	 * this function can be called from any thread, at any time, and must be
767 	 * able to accurately determine the correct sample time.
768 	 *
769 	 * Can be called from any thread.
770 	 */
771 	virtual samplepos_t sample_time () = 0;
772 
773 	/** Return the time according to the sample clock in use when the most
774 	 * recent buffer process cycle began. Can be called from any thread.
775 	 */
776 	virtual samplepos_t sample_time_at_cycle_start () = 0;
777 
778 	/** Return the time since the current buffer process cycle started,
779 	 * in samples, according to the sample clock in use.
780 	 *
781 	 * Can ONLY be called from within a process() callback tree (which
782 	 * implies that it can only be called by a process thread)
783 	 */
784 	virtual pframes_t samples_since_cycle_start () = 0;
785 
786 	/** Return true if it possible to determine the offset in samples of the
787 	 * first video frame that starts within the current buffer process cycle,
788 	 * measured from the first sample of the cycle. If returning true,
789 	 * set \p offset to that offset.
790 	 *
791 	 * Eg. if it can be determined that the first video frame within the cycle
792 	 * starts 28 samples after the first sample of the cycle, then this method
793 	 * should return true and set \p offset to 28.
794 	 *
795 	 * May be impossible to support outside of JACK, which has specific support
796 	 * (in some cases, hardware support) for this feature.
797 	 *
798 	 * Can ONLY be called from within a process() callback tree (which implies
799 	 * that it can only be called by a process thread)
800 	 */
get_sync_offset(pframes_t & offset)801 	virtual bool get_sync_offset (pframes_t& offset) const
802 	{
803 		return false;
804 	}
805 
806 	/** Create a new thread suitable for running part of the buffer process
807 	 * cycle (i.e. Realtime scheduling, memory allocation, stacksize, etc.
808 	 * are all correctly setup).
809 	 * The thread will begin executing func, and will exit
810 	 * when that function returns.
811 	 *
812 	 * @param func process function to run
813 	 */
814 	virtual int create_process_thread (boost::function<void()> func) = 0;
815 
816 	/** Wait for all processing threads to exit.
817 	 *
818 	 * Return zero on success, non-zero on failure.
819 	 */
820 	virtual int join_process_threads () = 0;
821 
822 	/** Return true if execution context is in a backend thread */
823 	virtual bool in_process_thread () = 0;
824 
825 	/** Return the minimum stack size of audio threads in bytes */
thread_stack_size()826 	static size_t thread_stack_size ()
827 	{
828 		return 100000;
829 	}
830 
831 	/** Return number of processing threads */
832 	virtual uint32_t process_thread_count () = 0;
833 
834 	virtual void update_latencies () = 0;
835 
836 	/** Set \p speed and \p position to the current speed and position
837 	 * indicated by some transport sync signal.  Return whether the current
838 	 * transport state is pending, or finalized.
839 	 *
840 	 * Derived classes only need implement this if they provide some way to
841 	 * sync to a transport sync signal (e.g. Sony 9 Pin) that is not
842 	 * handled by Ardour itself (LTC and MTC are both handled by Ardour).
843 	 * The canonical example is JACK Transport.
844 	 */
speed_and_position(double & speed,samplepos_t & position)845 	virtual bool speed_and_position (double& speed, samplepos_t& position)
846 	{
847 		speed    = 0.0;
848 		position = 0;
849 		return false;
850 	}
851 
852 	enum TimingTypes {
853 		DeviceWait = 0,
854 		RunLoop,
855 		/* end */
856 		NTT
857 	};
858 
859 	PBD::TimingStats dsp_stats[NTT];
860 
861 protected:
862 	AudioBackendInfo& _info;
863 	AudioEngine&      engine;
864 
865 	virtual int _start (bool for_latency_measurement) = 0;
866 };
867 
868 } // namespace ARDOUR
869 
870 #endif /* __libardour_audiobackend_h__ */
871