1 /**********************************************************************
2 
3 Audacity: A Digital Audio Editor
4 
5 AudioIOBase.h
6 
7 Paul Licameli split from AudioIO.h
8 
9 **********************************************************************/
10 
11 #ifndef __AUDACITY_AUDIO_IO_BASE__
12 #define __AUDACITY_AUDIO_IO_BASE__
13 
14 
15 
16 
17 #include <cfloat>
18 #include <functional>
19 #include <optional>
20 #include <vector>
21 #include <wx/string.h>
22 #include "MemoryX.h"
23 
24 struct PaDeviceInfo;
25 typedef void PaStream;
26 
27 #if USE_PORTMIXER
28 typedef void PxMixer;
29 #endif
30 
31 class AudioIOBase;
32 
33 class AudacityProject;
34 class AudioIOListener;
35 class BoundedEnvelope;
36 class Meter;
37 using PRCrossfadeData = std::vector< std::vector < float > >;
38 
39 #define BAD_STREAM_TIME (-DBL_MAX)
40 
41 class PlaybackPolicy;
42 
43 // To avoid growing the argument list of StartStream, add fields here
44 struct AudioIOStartStreamOptions
45 {
46    explicit
AudioIOStartStreamOptionsAudioIOStartStreamOptions47    AudioIOStartStreamOptions(
48       const std::shared_ptr<AudacityProject> &pProject, double rate_)
49       : pProject{ pProject }
50       , envelope(nullptr)
51       , rate(rate_)
52       , preRoll(0.0)
53    {}
54 
55    std::shared_ptr<AudacityProject> pProject;
56    std::weak_ptr<Meter> captureMeter, playbackMeter;
57    const BoundedEnvelope *envelope; // for time warping
58    std::shared_ptr< AudioIOListener > listener;
59    double rate;
60    mutable std::optional<double> pStartTime;
61    double preRoll;
62 
63    bool playNonWaveTracks{ true };
64 
65    // contents may get swapped with empty vector
66    PRCrossfadeData      *pCrossfadeData{};
67 
68    // An unfortunate thing needed just to make scrubbing work on Linux when
69    // we can't use a separate polling thread.
70    // The return value is a number of milliseconds to sleep before calling again
71    std::function< unsigned long() > playbackStreamPrimer;
72 
73    using PolicyFactory = std::function<
74       std::unique_ptr<PlaybackPolicy>(const AudioIOStartStreamOptions&) >;
75    PolicyFactory policyFactory;
76 
77    bool loopEnabled{ false };
78    bool variableSpeed{ false };
79 };
80 
81 struct AudioIODiagnostics{
82    wxString filename;    // For crash report bundle
83    wxString text;        // One big string, may be localized
84    wxString description; // Non-localized short description
85 };
86 
87 //! Abstract interface to alternative, concurrent playback with the main audio (such as MIDI events)
88 class AUDIO_DEVICES_API AudioIOExtBase
89 {
90 public:
91    virtual ~AudioIOExtBase();
92 
93    // Formerly in AudioIOBase
94    virtual bool IsOtherStreamActive() const = 0;
95 
96    //! Get diagnostic information for audio devices and also for extensions
97    virtual AudioIODiagnostics Dump() const = 0;
98 };
99 
100 ///\brief A singleton object supporting queries of the state of any active
101 /// audio streams, and audio device capabilities
102 class AUDIO_DEVICES_API AudioIOBase /* not final */
103    : public NonInterferingBase
104 {
105 public:
106    static AudioIOBase *Get();
107 
108    AudioIOBase();
109    virtual ~AudioIOBase();
110 
111    AudioIOBase(const AudioIOBase &) = delete;
112    AudioIOBase &operator=(const AudioIOBase &) = delete;
113 
114    void SetCaptureMeter(
115       const std::shared_ptr<AudacityProject> &project, const std::weak_ptr<Meter> &meter);
116    void SetPlaybackMeter(
117       const std::shared_ptr<AudacityProject> &project, const std::weak_ptr<Meter> &meter);
118 
119    /** \brief update state after changing what audio devices are selected
120     *
121     * Called when the devices stored in the preferences are changed to update
122     * the audio mixer capabilities
123     *
124     * \todo: Make this do a sample rate query and store the result in the
125     * AudioIO object to avoid doing it later? Would simplify the
126     * GetSupported*Rate functions considerably */
127    void HandleDeviceChange();
128 
129    /** \brief Get a list of sample rates the output (playback) device
130     * supports.
131     *
132     * If no information about available sample rates can be fetched,
133     * an empty list is returned.
134     *
135     * You can explicitly give the index of the device.  If you don't
136     * give it, the currently selected device from the preferences will be used.
137     *
138     * You may also specify a rate for which to check in addition to the
139     * standard rates.
140     */
141    static std::vector<long> GetSupportedPlaybackRates(int DevIndex = -1,
142                                                 double rate = 0.0);
143 
144    /** \brief Get a list of sample rates the input (recording) device
145     * supports.
146     *
147     * If no information about available sample rates can be fetched,
148     * an empty list is returned.
149     *
150     * You can explicitly give the index of the device.  If you don't
151     * give it, the currently selected device from the preferences will be used.
152     *
153     * You may also specify a rate for which to check in addition to the
154     * standard rates.
155     */
156    static std::vector<long> GetSupportedCaptureRates(int devIndex = -1,
157                                                double rate = 0.0);
158 
159    /** \brief Get a list of sample rates the current input/output device
160     * combination supports.
161     *
162     * Since there is no concept (yet) for different input/output
163     * sample rates, this currently returns only sample rates that are
164     * supported on both the output and input device. If no information
165     * about available sample rates can be fetched, it returns a default
166     * list.
167     * You can explicitly give the indexes of the playDevice/recDevice.
168     * If you don't give them, the selected devices from the preferences
169     * will be used.
170     * You may also specify a rate for which to check in addition to the
171     * standard rates.
172     */
173    static std::vector<long> GetSupportedSampleRates(int playDevice = -1,
174                                               int recDevice = -1,
175                                        double rate = 0.0);
176 
177    /** \brief Get a supported sample rate which can be used a an optimal
178     * default.
179     *
180     * Currently, this uses the first supported rate in the list
181     * [44100, 48000, highest sample rate]. Used in Project as a default value
182     * for project rates if one cannot be retrieved from the preferences.
183     * So all in all not that useful or important really
184     */
185    static int GetOptimalSupportedSampleRate();
186 
187    /** \brief Array of common audio sample rates
188     *
189     * These are the rates we will always support, regardless of hardware support
190     * for them (by resampling in audacity if needed) */
191    static const int StandardRates[];
192    /** \brief How many standard sample rates there are */
193    static const int NumStandardRates;
194 
195    /** \brief Get diagnostic information on all the available audio I/O devices
196     *
197     */
198    wxString GetDeviceInfo() const;
199 
200    //! Get diagnostic information for audio devices and also for extensions
201    std::vector<AudioIODiagnostics> GetAllDeviceInfo();
202 
203    /** \brief Find out if playback / recording is currently paused */
204    bool IsPaused() const;
205 
206    virtual void StopStream() = 0;
207 
208    /** \brief  Returns true if audio i/o is busy starting, stopping, playing,
209     * or recording.
210     *
211     * When this is false, it's safe to start playing or recording */
212    bool IsBusy() const;
213 
214    /** \brief Returns true if the audio i/o is running at all, but not during
215     * cleanup
216     *
217     * Doesn't return true if the device has been closed but some disk i/o or
218     * cleanup is still going on. If you want to know if it's safe to start a
219     * NEW stream, use IsBusy() */
220    bool IsStreamActive() const;
221    bool IsStreamActive(int token) const;
222 
223    /** \brief Returns true if the stream is active, or even if audio I/O is
224     * busy cleaning up its data or writing to disk.
225     *
226     * This is used by TrackPanel to determine when a track has been completely
227     * recorded, and it's safe to flush to disk. */
228    bool IsAudioTokenActive(int token) const;
229 
230    /** \brief Returns true if we're monitoring input (but not recording or
231     * playing actual audio) */
232    bool IsMonitoring() const;
233 
234    /* Mixer services are always available.  If no stream is running, these
235     * methods use whatever device is specified by the preferences.  If a
236     * stream *is* running, naturally they manipulate the mixer associated
237     * with that stream.  If no mixer is available, output is emulated and
238     * input is stuck at 1.0f (a gain is applied to output samples).
239     */
240    void SetMixer(int inputSource);
241 
242 protected:
243    static std::unique_ptr<AudioIOBase> ugAudioIO;
244    static wxString DeviceName(const PaDeviceInfo* info);
245    static wxString HostName(const PaDeviceInfo* info);
246 
247    std::weak_ptr<AudacityProject> mOwningProject;
248 
249    /// True if audio playback is paused
250    bool                mPaused;
251 
252    volatile int        mStreamToken;
253 
254    /// Audio playback rate in samples per second
255    double              mRate;
256 
257    PaStream           *mPortStreamV19;
258 
259    std::weak_ptr<Meter> mInputMeter{};
260    std::weak_ptr<Meter> mOutputMeter{};
261 
262    #if USE_PORTMIXER
263    PxMixer            *mPortMixer;
264    float               mPreviousHWPlaythrough;
265    #endif /* USE_PORTMIXER */
266 
267    /** @brief Can we control the hardware input level?
268     *
269     * This flag is set to true if using portmixer to control the
270     * input volume seems to be working (and so we offer the user the control),
271     * and to false (locking the control out) otherwise. This avoids stupid
272     * scaled clipping problems when trying to do software emulated input volume
273     * control */
274    bool                mInputMixerWorks;
275 
276    // For cacheing supported sample rates
277    static int mCachedPlaybackIndex;
278    static std::vector<long> mCachedPlaybackRates;
279    static int mCachedCaptureIndex;
280    static std::vector<long> mCachedCaptureRates;
281    static std::vector<long> mCachedSampleRates;
282    static double mCachedBestRateIn;
283 
284 protected:
285    /** \brief get the index of the supplied (named) recording device, or the
286     * device selected in the preferences if none given.
287     *
288     * Pure utility function, but it comes round a number of times in the code
289     * and would be neater done once. If the device isn't found, return the
290     * default device index.
291     */
292    static int getRecordDevIndex(const wxString &devName = {});
293 
294    /** \brief get the index of the device selected in the preferences.
295     *
296     * If the device isn't found, returns -1
297     */
298 #if USE_PORTMIXER
299    static int getRecordSourceIndex(PxMixer *portMixer);
300 #endif
301 
302    /** \brief get the index of the supplied (named) playback device, or the
303     * device selected in the preferences if none given.
304     *
305     * Pure utility function, but it comes round a number of times in the code
306     * and would be neater done once. If the device isn't found, return the
307     * default device index.
308     */
309    static int getPlayDevIndex(const wxString &devName = {});
310 
311    /** \brief Array of audio sample rates to try to use
312     *
313     * These are the rates we will check if a device supports, and is as long
314     * as I can think of (to try and work out what the card can do) */
315    static const int RatesToTry[];
316    /** \brief How many sample rates to try */
317    static const int NumRatesToTry;
318 
319    /*! This class needs to iterate this array for one limited purpose but does
320     not populate it and does not give access to it except to subclasses
321     */
322    std::vector<std::unique_ptr<AudioIOExtBase>> mAudioIOExt;
323 };
324 
325 #include "Prefs.h"
326 
327 extern AUDIO_DEVICES_API StringSetting AudioIOHost;
328 extern AUDIO_DEVICES_API DoubleSetting AudioIOLatencyCorrection;
329 extern AUDIO_DEVICES_API DoubleSetting AudioIOLatencyDuration;
330 extern AUDIO_DEVICES_API StringSetting AudioIOPlaybackDevice;
331 extern AUDIO_DEVICES_API DoubleSetting AudioIOPlaybackVolume;
332 extern AUDIO_DEVICES_API IntSetting    AudioIORecordChannels;
333 extern AUDIO_DEVICES_API StringSetting AudioIORecordingDevice;
334 extern AUDIO_DEVICES_API StringSetting AudioIORecordingSource;
335 extern AUDIO_DEVICES_API IntSetting    AudioIORecordingSourceIndex;
336 
337 #endif
338