blob: c46df1e8587231e5834b9fd7adcef79f183c0264 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_AUDIOTRACK_H
18#define ANDROID_AUDIOTRACK_H
19
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <media/IAudioFlinger.h>
24#include <media/IAudioTrack.h>
25#include <media/AudioSystem.h>
26
27#include <utils/RefBase.h>
28#include <utils/Errors.h>
Mathias Agopian07952722009-05-19 19:08:10 -070029#include <binder/IInterface.h>
30#include <binder/IMemory.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031#include <utils/threads.h>
32
33
34namespace android {
35
36// ----------------------------------------------------------------------------
37
38class audio_track_cblk_t;
39
40// ----------------------------------------------------------------------------
41
42class AudioTrack
43{
44public:
45 enum channel_index {
46 MONO = 0,
47 LEFT = 0,
48 RIGHT = 1
49 };
50
51 /* Events used by AudioTrack callback function (audio_track_cblk_t).
52 */
53 enum event_type {
54 EVENT_MORE_DATA = 0, // Request to write more data to PCM buffer.
55 EVENT_UNDERRUN = 1, // PCM buffer underrun occured.
56 EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from loop start if loop count was not 0.
57 EVENT_MARKER = 3, // Playback head is at the specified marker position (See setMarkerPosition()).
58 EVENT_NEW_POS = 4, // Playback head is at a new position (See setPositionUpdatePeriod()).
59 EVENT_BUFFER_END = 5 // Playback head is at the end of the buffer.
60 };
61
62 /* Create Buffer on the stack and pass it to obtainBuffer()
63 * and releaseBuffer().
64 */
65
66 class Buffer
67 {
68 public:
69 enum {
70 MUTE = 0x00000001
71 };
72 uint32_t flags;
73 int channelCount;
74 int format;
75 size_t frameCount;
76 size_t size;
77 union {
78 void* raw;
79 short* i16;
80 int8_t* i8;
81 };
82 };
83
84
85 /* As a convenience, if a callback is supplied, a handler thread
86 * is automatically created with the appropriate priority. This thread
87 * invokes the callback when a new buffer becomes availlable or an underrun condition occurs.
88 * Parameters:
89 *
90 * event: type of event notified (see enum AudioTrack::event_type).
91 * user: Pointer to context for use by the callback receiver.
92 * info: Pointer to optional parameter according to event type:
93 * - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
94 * more bytes than indicated by 'size' field and update 'size' if less bytes are
95 * written.
96 * - EVENT_UNDERRUN: unused.
97 * - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
98 * - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
99 * - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
100 * - EVENT_BUFFER_END: unused.
101 */
102
103 typedef void (*callback_t)(int event, void* user, void *info);
104
105 /* Constructs an uninitialized AudioTrack. No connection with
106 * AudioFlinger takes place.
107 */
108 AudioTrack();
109
110 /* Creates an audio track and registers it with AudioFlinger.
111 * Once created, the track needs to be started before it can be used.
112 * Unspecified values are set to the audio hardware's current
113 * values.
114 *
115 * Parameters:
116 *
117 * streamType: Select the type of audio stream this track is attached to
118 * (e.g. AudioSystem::MUSIC).
119 * sampleRate: Track sampling rate in Hz.
Eric Laurenta553c252009-07-17 12:17:14 -0700120 * format: Audio format (e.g AudioSystem::PCM_16_BIT for signed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * 16 bits per sample).
Eric Laurenta553c252009-07-17 12:17:14 -0700122 * channels: Channel mask: see AudioSystem::audio_channels.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 * frameCount: Total size of track PCM buffer in frames. This defines the
124 * latency of the track.
125 * flags: Reserved for future use.
126 * cbf: Callback function. If not null, this function is called periodically
127 * to request new PCM data.
128 * notificationFrames: The callback function is called each time notificationFrames PCM
129 * frames have been comsumed from track input buffer.
130 * user Context for use by the callback receiver.
131 */
132
133 AudioTrack( int streamType,
134 uint32_t sampleRate = 0,
135 int format = 0,
Eric Laurenta553c252009-07-17 12:17:14 -0700136 int channels = 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 int frameCount = 0,
138 uint32_t flags = 0,
139 callback_t cbf = 0,
140 void* user = 0,
Eric Laurent65b65452010-06-01 23:49:17 -0700141 int notificationFrames = 0,
142 int sessionId = 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 /* Creates an audio track and registers it with AudioFlinger. With this constructor,
145 * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
146 * identified by the argument sharedBuffer. This prototype is for static buffer playback.
147 * PCM data must be present into memory before the AudioTrack is started.
148 * The Write() and Flush() methods are not supported in this case.
149 * It is recommented to pass a callback function to be notified of playback end by an
150 * EVENT_UNDERRUN event.
151 */
152
153 AudioTrack( int streamType,
154 uint32_t sampleRate = 0,
155 int format = 0,
Eric Laurenta553c252009-07-17 12:17:14 -0700156 int channels = 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 const sp<IMemory>& sharedBuffer = 0,
158 uint32_t flags = 0,
159 callback_t cbf = 0,
160 void* user = 0,
Eric Laurent65b65452010-06-01 23:49:17 -0700161 int notificationFrames = 0,
162 int sessionId = 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
164 /* Terminates the AudioTrack and unregisters it from AudioFlinger.
165 * Also destroys all resources assotiated with the AudioTrack.
166 */
167 ~AudioTrack();
168
169
170 /* Initialize an uninitialized AudioTrack.
171 * Returned status (from utils/Errors.h) can be:
172 * - NO_ERROR: successful intialization
173 * - INVALID_OPERATION: AudioTrack is already intitialized
Eric Laurenta553c252009-07-17 12:17:14 -0700174 * - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 * - NO_INIT: audio server or audio hardware not initialized
176 * */
177 status_t set(int streamType =-1,
178 uint32_t sampleRate = 0,
179 int format = 0,
Eric Laurenta553c252009-07-17 12:17:14 -0700180 int channels = 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 int frameCount = 0,
182 uint32_t flags = 0,
183 callback_t cbf = 0,
184 void* user = 0,
185 int notificationFrames = 0,
186 const sp<IMemory>& sharedBuffer = 0,
Eric Laurent65b65452010-06-01 23:49:17 -0700187 bool threadCanCallJava = false,
188 int sessionId = 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
190
191 /* Result of constructing the AudioTrack. This must be checked
192 * before using any AudioTrack API (except for set()), using
193 * an uninitialized AudioTrack produces undefined results.
194 * See set() method above for possible return codes.
195 */
196 status_t initCheck() const;
197
198 /* Returns this track's latency in milliseconds.
199 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
200 * and audio hardware driver.
201 */
202 uint32_t latency() const;
203
204 /* getters, see constructor */
205
206 int streamType() const;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 int format() const;
208 int channelCount() const;
209 uint32_t frameCount() const;
210 int frameSize() const;
211 sp<IMemory>& sharedBuffer();
212
213
214 /* After it's created the track is not active. Call start() to
215 * make it active. If set, the callback will start being called.
216 */
217 void start();
218
219 /* Stop a track. If set, the callback will cease being called and
220 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
221 * and will fill up buffers until the pool is exhausted.
222 */
223 void stop();
224 bool stopped() const;
225
226 /* flush a stopped track. All pending buffers are discarded.
227 * This function has no effect if the track is not stoped.
228 */
229 void flush();
230
231 /* Pause a track. If set, the callback will cease being called and
232 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
233 * and will fill up buffers until the pool is exhausted.
234 */
235 void pause();
236
237 /* mute or unmutes this track.
238 * While mutted, the callback, if set, is still called.
239 */
240 void mute(bool);
241 bool muted() const;
242
243
244 /* set volume for this track, mostly used for games' sound effects
Eric Laurent65b65452010-06-01 23:49:17 -0700245 * left and right volumes. Levels must be <= 1.0.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 */
Eric Laurent65b65452010-06-01 23:49:17 -0700247 status_t setVolume(float left, float right);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 void getVolume(float* left, float* right);
249
Eric Laurent65b65452010-06-01 23:49:17 -0700250 /* set the send level for this track. An auxiliary effect should be attached
251 * to the track with attachEffect(). Level must be <= 1.0.
252 */
253 status_t setSendLevel(float level);
254 void getSendLevel(float* level);
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 /* set sample rate for this track, mostly used for games' sound effects
257 */
Eric Laurent88e209d2009-07-07 07:10:45 -0700258 status_t setSampleRate(int sampleRate);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 uint32_t getSampleRate();
260
261 /* Enables looping and sets the start and end points of looping.
262 *
263 * Parameters:
264 *
265 * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start.
266 * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start.
267 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
268 * active loop. loopCount = -1 means infinite looping.
269 *
270 * For proper operation the following condition must be respected:
271 * (loopEnd-loopStart) <= framecount()
272 */
273 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
274 status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
275
276
277 /* Sets marker position. When playback reaches the number of frames specified, a callback with event
278 * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification
279 * callback.
280 * If the AudioTrack has been opened with no callback function associated, the operation will fail.
281 *
282 * Parameters:
283 *
284 * marker: marker position expressed in frames.
285 *
286 * Returned status (from utils/Errors.h) can be:
287 * - NO_ERROR: successful operation
288 * - INVALID_OPERATION: the AudioTrack has no callback installed.
289 */
290 status_t setMarkerPosition(uint32_t marker);
291 status_t getMarkerPosition(uint32_t *marker);
292
293
294 /* Sets position update period. Every time the number of frames specified has been played,
295 * a callback with event type EVENT_NEW_POS is called.
296 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
297 * callback.
298 * If the AudioTrack has been opened with no callback function associated, the operation will fail.
299 *
300 * Parameters:
301 *
302 * updatePeriod: position update notification period expressed in frames.
303 *
304 * Returned status (from utils/Errors.h) can be:
305 * - NO_ERROR: successful operation
306 * - INVALID_OPERATION: the AudioTrack has no callback installed.
307 */
308 status_t setPositionUpdatePeriod(uint32_t updatePeriod);
309 status_t getPositionUpdatePeriod(uint32_t *updatePeriod);
310
311
312 /* Sets playback head position within AudioTrack buffer. The new position is specified
313 * in number of frames.
314 * This method must be called with the AudioTrack in paused or stopped state.
315 * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
316 * Therefore using this method makes sense only when playing a "static" audio buffer
317 * as opposed to streaming.
318 * The getPosition() method on the other hand returns the total number of frames played since
319 * playback start.
320 *
321 * Parameters:
322 *
323 * position: New playback head position within AudioTrack buffer.
324 *
325 * Returned status (from utils/Errors.h) can be:
326 * - NO_ERROR: successful operation
327 * - INVALID_OPERATION: the AudioTrack is not stopped.
328 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
329 */
330 status_t setPosition(uint32_t position);
331 status_t getPosition(uint32_t *position);
332
333 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
334 * rewriting the buffer before restarting playback after a stop.
335 * This method must be called with the AudioTrack in paused or stopped state.
336 *
337 * Returned status (from utils/Errors.h) can be:
338 * - NO_ERROR: successful operation
339 * - INVALID_OPERATION: the AudioTrack is not stopped.
340 */
341 status_t reload();
342
Eric Laurenta553c252009-07-17 12:17:14 -0700343 /* returns a handle on the audio output used by this AudioTrack.
344 *
345 * Parameters:
346 * none.
347 *
348 * Returned value:
349 * handle on audio hardware output
350 */
351 audio_io_handle_t getOutput();
352
Eric Laurent65b65452010-06-01 23:49:17 -0700353 /* returns the unique ID associated to this track.
354 *
355 * Parameters:
356 * none.
357 *
358 * Returned value:
359 * AudioTrack ID.
360 */
361 int getSessionId();
362
363
364 /* Attach track auxiliary output to specified effect. Used effectId = 0
365 * to detach track from effect.
366 *
367 * Parameters:
368 *
369 * effectId: effectId obtained from AudioEffect::id().
370 *
371 * Returned status (from utils/Errors.h) can be:
372 * - NO_ERROR: successful operation
373 * - INVALID_OPERATION: the effect is not an auxiliary effect.
374 * - BAD_VALUE: The specified effect ID is invalid
375 */
376 status_t attachAuxEffect(int effectId);
377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 /* obtains a buffer of "frameCount" frames. The buffer must be
379 * filled entirely. If the track is stopped, obtainBuffer() returns
380 * STOPPED instead of NO_ERROR as long as there are buffers availlable,
381 * at which point NO_MORE_BUFFERS is returned.
382 * Buffers will be returned until the pool (buffercount())
383 * is exhausted, at which point obtainBuffer() will either block
384 * or return WOULD_BLOCK depending on the value of the "blocking"
385 * parameter.
386 */
387
388 enum {
389 NO_MORE_BUFFERS = 0x80000001,
390 STOPPED = 1
391 };
392
393 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
394 void releaseBuffer(Buffer* audioBuffer);
395
396
397 /* As a convenience we provide a write() interface to the audio buffer.
398 * This is implemented on top of lockBuffer/unlockBuffer. For best
399 * performance
400 *
401 */
402 ssize_t write(const void* buffer, size_t size);
403
404 /*
405 * Dumps the state of an audio track.
406 */
407 status_t dump(int fd, const Vector<String16>& args) const;
408
409private:
410 /* copying audio tracks is not allowed */
411 AudioTrack(const AudioTrack& other);
412 AudioTrack& operator = (const AudioTrack& other);
413
414 /* a small internal class to handle the callback */
415 class AudioTrackThread : public Thread
416 {
417 public:
418 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
419 private:
420 friend class AudioTrack;
421 virtual bool threadLoop();
422 virtual status_t readyToRun();
423 virtual void onFirstRef();
424 AudioTrack& mReceiver;
425 Mutex mLock;
426 };
427
428 bool processAudioBuffer(const sp<AudioTrackThread>& thread);
Eric Laurentbda74692009-11-04 08:27:26 -0800429 status_t createTrack(int streamType,
430 uint32_t sampleRate,
431 int format,
432 int channelCount,
433 int frameCount,
434 uint32_t flags,
435 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700436 audio_io_handle_t output,
437 bool enforceFrameCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 sp<IAudioTrack> mAudioTrack;
440 sp<IMemory> mCblkMemory;
441 sp<AudioTrackThread> mAudioTrackThread;
442
443 float mVolume[2];
Eric Laurent65b65452010-06-01 23:49:17 -0700444 float mSendLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 uint32_t mFrameCount;
446
447 audio_track_cblk_t* mCblk;
448 uint8_t mStreamType;
449 uint8_t mFormat;
450 uint8_t mChannelCount;
451 uint8_t mMuted;
Eric Laurenta553c252009-07-17 12:17:14 -0700452 uint32_t mChannels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 status_t mStatus;
454 uint32_t mLatency;
455
456 volatile int32_t mActive;
457
458 callback_t mCbf;
459 void* mUserData;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700460 uint32_t mNotificationFramesReq; // requested number of frames between each notification callback
461 uint32_t mNotificationFramesAct; // actual number of frames between each notification callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 sp<IMemory> mSharedBuffer;
463 int mLoopCount;
464 uint32_t mRemainingFrames;
465 uint32_t mMarkerPosition;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700466 bool mMarkerReached;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 uint32_t mNewPosition;
468 uint32_t mUpdatePeriod;
Eric Laurenta553c252009-07-17 12:17:14 -0700469 uint32_t mFlags;
Eric Laurent65b65452010-06-01 23:49:17 -0700470 int mSessionId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471};
472
473
474}; // namespace android
475
476#endif // ANDROID_AUDIOTRACK_H