xref: /aosp_15_r20/external/oboe/docs/FullGuide.md (revision 05767d913155b055644481607e6fa1e35e2fe72c)
1# Full Guide To Oboe
2Oboe is a C++ library which makes it easy to build high-performance audio apps on Android. Apps communicate with Oboe by reading and writing data to streams.
3
4## Audio streams
5
6Oboe moves audio data between your app and the audio inputs and outputs on your Android device. Your app passes data in and out using a callback function or by reading from and writing to *audio streams*, represented by the class `AudioStream`. The read/write calls can be blocking or non-blocking.
7
8A stream is defined by the following:
9
10*   The *audio* *device* that is the source or sink for the data in the stream.
11*   The *sharing mode* that determines whether a stream has exclusive access to an audio device that might otherwise be shared among multiple streams.
12*   The *format* of the audio data in the stream.
13
14### Audio device
15
16Each stream is attached to a single audio device.
17
18An audio device is a hardware interface or virtual endpoint that acts as a source or sink for a continuous stream of digital audio data. Don't confuse an *audio device*
19(a built-in mic or bluetooth headset) with the *Android device* (the phone or watch) that is running your app.
20
21On API 23 and above you can use the `AudioManager` method [getDevices()](https://developer.android.com/reference/android/media/AudioManager.html#getDevices(int)) to discover the audio devices that are available on your Android device. The method returns information about the [type](https://developer.android.com/reference/android/media/AudioDeviceInfo.html) of each device.
22
23Each audio device has a unique ID on the Android device. You can  use the ID to bind an audio stream to a specific audio device.  However, in most cases you can let Oboe choose the default primary device rather than specifying one yourself.
24
25The audio device attached to a stream determines whether the stream is for input or output. A stream can only move data in one direction. When you define a stream you also set its direction. When you open a stream Android checks to ensure that the audio device and stream direction agree.
26
27### Sharing mode
28
29A stream has a sharing mode:
30
31*   `SharingMode::Exclusive` (available on API 26+) means the stream has exclusive access to an endpoint on its audio device; the endpoint cannot be used by any other audio stream. If the exclusive endpoint is already in use, it might not be possible for the stream to obtain access to it. Exclusive streams provide the lowest possible latency by bypassing the mixer stage, but they are also more likely to get disconnected. You should close exclusive streams as soon as you no longer need them, so that other apps can access that endpoint. Not all audio devices provide exclusive endpoints. System sounds and sounds from other apps can still be heard when an exclusive stream is in use as they use a different endpoint.
32
33![Oboe exclusive sharing mode diagram](images/oboe-sharing-mode-exclusive.jpg)
34
35*   `SharingMode::Shared` allows Oboe streams to share an endpoint. The operating system will mix all the shared streams assigned to the same endpoint on the audio device.
36
37![Oboe exclusive sharing mode diagram](images/oboe-sharing-mode-shared.jpg)
38
39
40You can explicitly request the sharing mode when you create a stream, although you are not guaranteed to receive that mode. By default, the sharing mode is `Shared`.
41
42### Audio format
43
44The data passed through a stream has the usual digital audio attributes, which you must specify when you define a stream. These are as follows:
45
46*   Sample format
47*   Samples per frame
48*   Sample rate
49
50Oboe permits these sample formats:
51
52| AudioFormat | C data type | Notes |
53| :------------ | :---------- | :---- |
54| I16 | int16_t | common 16-bit samples, [Q0.15 format](https://source.android.com/devices/audio/data_formats#androidFormats) |
55| Float | float | -1.0 to +1.0 |
56
57Oboe might perform sample conversion on its own. For example, if an app is writing AudioFormat::Float data but the HAL uses AudioFormat::I16, Oboe might convert the samples automatically. Conversion can happen in either direction. If your app processes audio input, it is wise to verify the input format and be prepared to convert data if necessary, as in this example:
58
59    AudioFormat dataFormat = stream->getDataFormat();
60    //... later
61    if (dataFormat == AudioFormat::I16) {
62         convertFloatToPcm16(...)
63    }
64
65## Creating an audio stream
66
67The Oboe library follows a [builder design pattern](https://en.wikipedia.org/wiki/Builder_pattern) and provides the class `AudioStreamBuilder`.
68
69### Set the audio stream configuration using an AudioStreamBuilder.
70
71Use the builder functions that correspond to the stream parameters. These optional set functions are available:
72
73    AudioStreamBuilder streamBuilder;
74
75    streamBuilder.setDeviceId(deviceId);
76    streamBuilder.setDirection(direction);
77    streamBuilder.setSharingMode(shareMode);
78    streamBuilder.setSampleRate(sampleRate);
79    streamBuilder.setChannelCount(channelCount);
80    streamBuilder.setFormat(format);
81    streamBuilder.setPerformanceMode(perfMode);
82
83Note that these methods do not report errors, such as an undefined constant or value out of range. They will be checked when the stream is opened.
84
85If you do not specify the deviceId, the default is the primary output device.
86If you do not specify the stream direction, the default is an output stream.
87For all parameters, you can explicitly set a value, or let the system
88assign the optimal value by not specifying the parameter at all or setting
89it to `kUnspecified`.
90
91To be safe, check the state of the audio stream after you create it, as explained in step 3, below.
92
93### Open the Stream
94
95Declare a **shared pointer** for the stream. Make sure it is declared with the appropriate scope. The best place is as a member variable in a managing class or as a global. Avoid declaring it as a local variable because the stream may get deleted when the function returns.
96
97    std::shared_ptr<oboe::AudioStream> mStream;
98
99After you've configured the `AudioStreamBuilder`, call `openStream()` to open the stream:
100
101    Result result = streamBuilder.openStream(mStream);
102    if (result != OK){
103        __android_log_print(ANDROID_LOG_ERROR,
104                            "AudioEngine",
105                            "Error opening stream %s",
106                            convertToText(result));
107    }
108
109
110### Verifying stream configuration and additional properties
111
112You should verify the stream's configuration after opening it.
113
114The following properties are guaranteed to be set. However, if these properties
115are unspecified, a default value will still be set, and should be queried by the
116appropriate accessor.
117
118* framesPerCallback
119* sampleRate
120* channelCount
121* format
122* direction
123
124The following properties may be changed by the underlying stream construction
125*even if explicitly set* and therefore should always be queried by the appropriate
126accessor. The property settings will depend on device capabilities.
127
128* bufferCapacityInFrames
129* sharingMode (exclusive provides lowest latency)
130* performanceMode
131
132The following properties are only set by the underlying stream. They cannot be
133set by the application, but should be queried by the appropriate accessor.
134
135* framesPerBurst
136
137The following properties have unusual behavior
138
139* deviceId is respected when the underlying API is AAudio (API level >=28), but not when it
140is OpenSLES. It can be set regardless, but *will not* throw an error if an OpenSLES stream
141is used. The default device will be used, rather than whatever is specified.
142
143* mAudioApi is only a property of the builder, however
144AudioStream::getAudioApi() can be used to query the underlying API which the
145stream uses. The property set in the builder is not guaranteed, and in
146general, the API should be chosen by Oboe to allow for best performance and
147stability considerations. Since Oboe is designed to be as uniform across both
148APIs as possible, this property should not generally be needed.
149
150* mBufferSizeInFrames can only be set on an already open stream (as opposed to a
151builder), since it depends on run-time behavior.
152The actual size used may not be what was requested.
153Oboe or the underlyng API will limit the size between zero and the buffer capacity.
154It may also be limited further to reduce glitching on particular devices.
155This feature is not supported when using a callback with OpenSL ES.
156
157Many of the stream's properties may vary (whether or not you set
158them) depending on the capabilities of the audio device and the Android device on
159which it's running. If you need to know these values then you must query them using
160the accessor after the stream has been opened. Additionally,
161the underlying parameters a stream is granted are useful to know if
162they have been left unspecified. As a matter of good defensive programming, you
163should check the stream's configuration before using it.
164
165
166There are functions to retrieve the stream setting that corresponds to each
167builder setting:
168
169
170| AudioStreamBuilder set methods | AudioStream get methods |
171| :------------------------ | :----------------- |
172| `setDataCallback()` |  `getDataCallback()` |
173| `setErrorCallback()` |  `getErrorCallback()` |
174| `setDirection()` | `getDirection()` |
175| `setSharingMode()` | `getSharingMode()` |
176| `setPerformanceMode()` | `getPerformanceMode()` |
177| `setSampleRate()` | `getSampleRate()` |
178| `setChannelCount()` | `getChannelCount()` |
179| `setFormat()` | `getFormat()` |
180| `setBufferCapacityInFrames()` | `getBufferCapacityInFrames()` |
181| `setFramesPerCallback()` | `getFramesPerCallback()` |
182|  --  | `getFramesPerBurst()` |
183| `setDeviceId()` (not respected on OpenSLES) | `getDeviceId()` |
184| `setAudioApi()` (mainly for debugging) | `getAudioApi()` |
185
186The following AudioStreamBuilder fields were added in API 28 to
187specify additional information about the AudioStream to the device. Currently,
188they have little effect on the stream, but setting them helps applications
189interact better with other services.
190
191For more information see: [Usage/ContentTypes](https://source.android.com/devices/audio/attributes).
192The InputPreset may be used by the device to process the input stream (such as gain control). By default
193it is set to VoiceRecognition, which is optimized for low latency.
194
195* `setUsage(oboe::Usage usage)`  - The purpose for creating the stream.
196* `setContentType(oboe::ContentType contentType)` - The type of content carried
197  by the stream.
198* `setInputPreset(oboe::InputPreset inputPreset)` - The recording configuration
199  for an audio input.
200* `setSessionId(SessionId sessionId)` - Allocate SessionID to connect to the
201  Java AudioEffects API.
202
203
204## Using an audio stream
205
206### State transitions
207
208An Oboe stream is usually in one of five stable states (the error state, Disconnected, is described at the end of this section):
209
210*   Open
211*   Started
212*   Paused
213*   Flushed
214*   Stopped
215
216Data only flows through a stream when the stream is in the Started state. To
217move a stream between states, use one of the functions that request a state
218transition:
219
220    Result result;
221    result = stream->requestStart();
222    result = stream->requestStop();
223    result = stream->requestPause();
224    result = stream->requestFlush();
225
226Note that you can only request pause or flush on an output stream:
227
228These functions are asynchronous, and the state change doesn't happen
229immediately. When you request a state change, the stream moves to one of the
230corresponding transient states:
231
232*   Starting
233*   Pausing
234*   Flushing
235*   Stopping
236*   Closing
237
238The state diagram below shows the stable states as rounded rectangles, and the transient states as dotted rectangles.
239Though it's not shown, you can call `close()` from any state
240
241![Oboe Lifecycle](images/oboe-lifecycle.png)
242
243Oboe doesn't provide callbacks to alert you to state changes. One special
244function,
245`AudioStream::waitForStateChange()` can be used to wait for a state change.
246Note that most apps will not need to call `waitForStateChange()` and can just
247request state changes whenever they are needed.
248
249The function does not detect a state change on its own, and does not wait for a
250specific state. It waits until the current state
251is *different* than `inputState`, which you specify.
252
253For example, after requesting to pause, a stream should immediately enter
254the transient state Pausing, and arrive sometime later at the Paused state - though there's no guarantee it will.
255Since you can't wait for the Paused state, use `waitForStateChange()` to wait for *any state
256other than Pausing*. Here's how that's done:
257
258```
259StreamState inputState = StreamState::Pausing;
260StreamState nextState = StreamState::Uninitialized;
261int64_t timeoutNanos = 100 * kNanosPerMillisecond;
262result = stream->requestPause();
263result = stream->waitForStateChange(inputState, &nextState, timeoutNanos);
264```
265
266
267If the stream's state is not Pausing (the `inputState`, which we assumed was the
268current state at call time), the function returns immediately. Otherwise, it
269blocks until the state is no longer Pausing or the timeout expires. When the
270function returns, the parameter `nextState` shows the current state of the
271stream.
272
273You can use this same technique after calling request start, stop, or flush,
274using the corresponding transient state as the inputState. Do not call
275`waitForStateChange()` after calling `AudioStream::close()` since the underlying stream resources
276will be deleted as soon as it closes. And do not call `close()`
277while `waitForStateChange()` is running in another thread.
278
279### Reading and writing to an audio stream
280
281There are two ways to move data in or out of a stream.
2821) Read from or write directly to the stream.
2832) Specify a data callback object that will get called when the stream is ready.
284
285The callback technique offers the lowest latency performance because the callback code can run in a high priority thread.
286Also, attempting to open a low latency output stream without an audio callback (with the intent to use writes)
287may result in a non low latency stream.
288
289The read/write technique may be easier when you do not need low latency. Or, when doing both input and output, it is common to use a callback for output and then just do a non-blocking read from the input stream. Then you have both the input and output data available in one high priority thread.
290
291After the stream is started you can read or write to it using the methods
292`AudioStream::read(buffer, numFrames, timeoutNanos)`
293and
294`AudioStream::write(buffer, numFrames, timeoutNanos)`.
295
296For a blocking read or write that transfers the specified number of frames, set timeoutNanos greater than zero. For a non-blocking call, set timeoutNanos to zero. In this case the result is the actual number of frames transferred.
297
298When you read input, you should verify the correct number of
299frames was read. If not, the buffer might contain unknown data that could cause an
300audio glitch. You can pad the buffer with zeros to create a
301silent dropout:
302
303    Result result = mStream->read(audioData, numFrames, timeout);
304    if (result < 0) {
305        // Error!
306    }
307    if (result != numFrames) {
308        // pad the buffer with zeros
309        memset(static_cast<sample_type*>(audioData) + result * samplesPerFrame, 0,
310               (numFrames - result) * mStream->getBytesPerFrame());
311    }
312
313You can prime the stream's buffer before starting the stream by writing data or silence into it. This must be done in a non-blocking call with timeoutNanos set to zero.
314
315The data in the buffer must match the data format returned by `mStream->getDataFormat()`.
316
317### Closing an audio stream
318
319When you are finished using a stream, close it:
320
321    stream->close();
322
323Do not close a stream while it is being written to or read from another thread as this will cause your app to crash. After you close a stream you should not call any of its methods except for quering it properties.
324
325### Disconnected audio stream
326
327An audio stream can become disconnected at any time if one of these events happens:
328
329*   The associated audio device is no longer connected (for example when headphones are unplugged).
330*   An error occurs internally.
331*   An audio device is no longer the primary audio device.
332
333When a stream is disconnected, it has the state "Disconnected" and calls to `write()` or other functions will return `Result::ErrorDisconnected`.  When a stream is disconnected, all you can do is close it.
334
335If you need to be informed when an audio device is disconnected, write a class
336which extends `AudioStreamErrorCallback` and then register your class using `builder.setErrorCallback(yourCallbackClass)`. It is recommended to pass a shared_ptr.
337If you register a callback, then it will automatically close the stream in a separate thread if the stream is disconnected.
338
339Your callback can implement the following methods (called in a separate thread):
340
341* `onErrorBeforeClose(stream, error)` - called when the stream has been disconnected but not yet closed,
342  so you can still reference the underlying stream (e.g.`getXRunCount()`).
343You can also inform any other threads that may be calling the stream to stop doing so.
344Do not delete the stream or modify its stream state in this callback.
345* `onErrorAfterClose(stream, error)` - called when the stream has been stopped and closed by Oboe so the stream cannot be used and calling getState() will return closed.
346During this callback, stream properties (those requested by the builder) can be queried, as well as frames written and read.
347The stream can be deleted at the end of this method (as long as it not referenced in other threads).
348Methods that reference the underlying stream should not be called (e.g. `getTimestamp()`, `getXRunCount()`, `read()`, `write()`, etc.).
349Opening a separate stream is also a valid use of this callback, especially if the error received is `Error::Disconnected`.
350However, it is important to note that the new audio device may have vastly different properties than the stream that was disconnected.
351
352See the SoundBoard sample for an example of setErrorCallback.
353
354## Optimizing performance
355
356You can optimize the performance of an audio application by using special high-priority threads.
357
358### Using a high priority data callback
359
360If your app reads or writes audio data from an ordinary thread, it may be preempted or experience timing jitter. This can cause audio glitches.
361Using larger buffers might guard against such glitches, but a large buffer also introduces longer audio latency.
362For applications that require low latency, an audio stream can use an asynchronous callback function to transfer data to and from your app.
363The callback runs in a high-priority thread that has better performance.
364
365Your code can access the callback mechanism by implementing the virtual class
366`AudioStreamDataCallback`. The stream periodically executes `onAudioReady()` (the
367callback function) to acquire the data for its next burst.
368
369The total number of samples that you need to fill is numFrames * numChannels.
370
371    class AudioEngine : AudioStreamDataCallback {
372    public:
373        DataCallbackResult AudioEngine::onAudioReady(
374                AudioStream *oboeStream,
375                void *audioData,
376                int32_t numFrames){
377            // Fill the output buffer with random white noise.
378            const int numChannels = AAudioStream_getChannelCount(stream);
379            // This code assumes the format is AAUDIO_FORMAT_PCM_FLOAT.
380            float *output = (float *)audioData;
381            for (int frameIndex = 0; frameIndex < numFrames; frameIndex++) {
382                for (int channelIndex = 0; channelIndex < numChannels; channelIndex++) {
383                    float noise = (float)(drand48() - 0.5);
384                    *output++ = noise;
385                }
386            }
387            return DataCallbackResult::Continue;
388        }
389
390        bool AudioEngine::start() {
391            ...
392            // register the callback
393            streamBuilder.setDataCallback(this);
394        }
395    private:
396        // application data goes here
397    }
398
399
400Note that the callback must be registered on the stream with `setDataCallback`. Any
401application-specific data can be included within the class itself.
402
403The callback function should not perform a read or write on the stream that invoked it. If the callback belongs to an input stream, your code should process the data that is supplied in the audioData buffer (specified as the second argument). If the callback belongs to an output stream, your code should place data into the buffer.
404
405It is possible to process more than one stream in the callback. You can use one stream as the master, and pass pointers to other streams in the class's private data. Register a callback for the master stream. Then use non-blocking I/O on the other streams.  Here is an example of a round-trip callback that passes an input stream to an output stream. The master calling stream is the output
406stream. The input stream is included in the class.
407
408The callback does a non-blocking read from the input stream placing the data into the buffer of the output stream.
409
410    class AudioEngine : AudioStreamDataCallback {
411    public:
412
413        DataCallbackResult AudioEngine::onAudioReady(
414                AudioStream *oboeStream,
415                void *audioData,
416                int32_t numFrames) {
417            const int64_t timeoutNanos = 0; // for a non-blocking read
418            auto result = recordingStream->read(audioData, numFrames, timeoutNanos);
419            // result has type ResultWithValue<int32_t>, which for convenience is coerced
420            // to a Result type when compared with another Result.
421            if (result == Result::OK) {
422                if (result.value() < numFrames) {
423                    // replace the missing data with silence
424                    memset(static_cast<sample_type*>(audioData) + result.value() * samplesPerFrame, 0,
425                        (numFrames - result.value()) * oboeStream->getBytesPerFrame());
426
427                }
428                return DataCallbackResult::Continue;
429            }
430            return DataCallbackResult::Stop;
431        }
432
433        bool AudioEngine::start() {
434            ...
435            streamBuilder.setDataCallback(this);
436        }
437
438        void setRecordingStream(AudioStream *stream) {
439          recordingStream = stream;
440        }
441
442    private:
443        AudioStream *recordingStream;
444    }
445
446
447Note that in this example it is assumed the input and output streams have the same number of channels, format and sample rate. The format of the streams can be mismatched - as long as the code handles the translations properly.
448
449#### Data Callback - Do's and Don'ts
450You should never perform an operation which could block inside `onAudioReady`. Examples of blocking operations include:
451
452- allocate memory using, for example, malloc() or new
453- file operations such as opening, closing, reading or writing
454- network operations such as streaming
455- use mutexes or other synchronization primitives
456- sleep
457- stop or close the stream
458- Call read() or write() on the stream which invoked it
459
460The following methods are OK to call:
461
462- AudioStream::get*()
463- oboe::convertResultToText()
464
465### Setting performance mode
466
467Every AudioStream has a *performance mode* which has a large effect on your app's behavior. There are three modes:
468
469* `PerformanceMode::None` is the default mode. It uses a basic stream that balances latency and power savings.
470* `PerformanceMode::LowLatency` uses smaller buffers and an optimized data path for reduced latency.
471* `PerformanceMode::PowerSaving` uses larger internal buffers and a data path that trades off latency for lower power.
472
473You can select the performance mode by calling `setPerformanceMode()`,
474and discover the current mode by calling `getPerformanceMode()`.
475
476If low latency is more important than power savings in your application, use `PerformanceMode::LowLatency`.
477This is useful for apps that are very interactive, such as games or keyboard synthesizers.
478
479If saving power is more important than low latency in your application, use `PerformanceMode::PowerSaving`.
480This is typical for apps that play back previously generated music, such as streaming audio or MIDI file players.
481
482In the current version of Oboe, in order to achieve the lowest possible latency you must use the `PerformanceMode::LowLatency` performance mode along with a high-priority data callback. Follow this example:
483
484```
485// Create a callback object
486MyOboeStreamCallback myCallback;
487
488// Create a stream builder
489AudioStreamBuilder builder;
490builder.setDataCallback(myCallback);
491builder.setPerformanceMode(PerformanceMode::LowLatency);
492```
493
494## Thread safety
495
496The Oboe API is not completely [thread safe](https://en.wikipedia.org/wiki/Thread_safety).
497You cannot call some of the Oboe functions concurrently from more than one thread at a time.
498This is because Oboe avoids using mutexes, which can cause thread preemption and glitches.
499
500To be safe, don't call `waitForStateChange()` or read or write to the same stream from two different threads. Similarly, don't close a stream in one thread while reading or writing to it in another thread.
501
502Calls that return stream settings, like `AudioStream::getSampleRate()` and `AudioStream::getChannelCount()`, are thread safe.
503
504These calls are also thread safe:
505
506* `convertToText()`
507* `AudioStream::get*()` except for `getTimestamp()` and `getState()`
508
509<b>Note:</b> When a stream uses an error callback, it's safe to read/write from the callback thread while also closing the stream from the thread in which it is running.
510
511
512## Code samples
513
514Code samples are available in the [samples folder](../samples).
515
516## Known Issues
517
518The following methods are defined, but will return `Result::ErrorUnimplemented` for OpenSLES streams:
519
520* `getFramesRead()`
521* `getFramesWritten()`
522* `getTimestamp()`
523
524Additionally, `setDeviceId()` will not be respected by OpenSLES streams.
525