blob: 3e346db273aa598145b1f85278139e74e6326bc7 [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
Chia-chi Yehbd240c22010-06-16 06:33:13 +0800105 /* Returns the minimum frame count required for the successful creation of
106 * an AudioTrack object.
107 * Returned status (from utils/Errors.h) can be:
108 * - NO_ERROR: successful operation
109 * - NO_INIT: audio server or audio hardware not initialized
110 */
111
112 static status_t getMinFrameCount(int* frameCount,
113 int streamType =-1,
114 uint32_t sampleRate = 0);
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 /* Constructs an uninitialized AudioTrack. No connection with
117 * AudioFlinger takes place.
118 */
119 AudioTrack();
120
121 /* Creates an audio track and registers it with AudioFlinger.
122 * Once created, the track needs to be started before it can be used.
123 * Unspecified values are set to the audio hardware's current
124 * values.
125 *
126 * Parameters:
127 *
128 * streamType: Select the type of audio stream this track is attached to
129 * (e.g. AudioSystem::MUSIC).
130 * sampleRate: Track sampling rate in Hz.
Eric Laurenta553c252009-07-17 12:17:14 -0700131 * format: Audio format (e.g AudioSystem::PCM_16_BIT for signed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 * 16 bits per sample).
Eric Laurenta553c252009-07-17 12:17:14 -0700133 * channels: Channel mask: see AudioSystem::audio_channels.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 * frameCount: Total size of track PCM buffer in frames. This defines the
135 * latency of the track.
136 * flags: Reserved for future use.
137 * cbf: Callback function. If not null, this function is called periodically
138 * to request new PCM data.
139 * notificationFrames: The callback function is called each time notificationFrames PCM
140 * frames have been comsumed from track input buffer.
141 * user Context for use by the callback receiver.
142 */
143
144 AudioTrack( int streamType,
145 uint32_t sampleRate = 0,
146 int format = 0,
Eric Laurenta553c252009-07-17 12:17:14 -0700147 int channels = 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 int frameCount = 0,
149 uint32_t flags = 0,
150 callback_t cbf = 0,
151 void* user = 0,
Eric Laurent65b65452010-06-01 23:49:17 -0700152 int notificationFrames = 0,
153 int sessionId = 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
155 /* Creates an audio track and registers it with AudioFlinger. With this constructor,
156 * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
157 * identified by the argument sharedBuffer. This prototype is for static buffer playback.
158 * PCM data must be present into memory before the AudioTrack is started.
159 * The Write() and Flush() methods are not supported in this case.
160 * It is recommented to pass a callback function to be notified of playback end by an
161 * EVENT_UNDERRUN event.
162 */
163
164 AudioTrack( int streamType,
165 uint32_t sampleRate = 0,
166 int format = 0,
Eric Laurenta553c252009-07-17 12:17:14 -0700167 int channels = 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 const sp<IMemory>& sharedBuffer = 0,
169 uint32_t flags = 0,
170 callback_t cbf = 0,
171 void* user = 0,
Eric Laurent65b65452010-06-01 23:49:17 -0700172 int notificationFrames = 0,
173 int sessionId = 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
175 /* Terminates the AudioTrack and unregisters it from AudioFlinger.
176 * Also destroys all resources assotiated with the AudioTrack.
177 */
178 ~AudioTrack();
179
180
181 /* Initialize an uninitialized AudioTrack.
182 * Returned status (from utils/Errors.h) can be:
183 * - NO_ERROR: successful intialization
184 * - INVALID_OPERATION: AudioTrack is already intitialized
Eric Laurenta553c252009-07-17 12:17:14 -0700185 * - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 * - NO_INIT: audio server or audio hardware not initialized
187 * */
188 status_t set(int streamType =-1,
189 uint32_t sampleRate = 0,
190 int format = 0,
Eric Laurenta553c252009-07-17 12:17:14 -0700191 int channels = 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 int frameCount = 0,
193 uint32_t flags = 0,
194 callback_t cbf = 0,
195 void* user = 0,
196 int notificationFrames = 0,
197 const sp<IMemory>& sharedBuffer = 0,
Eric Laurent65b65452010-06-01 23:49:17 -0700198 bool threadCanCallJava = false,
199 int sessionId = 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201
202 /* Result of constructing the AudioTrack. This must be checked
203 * before using any AudioTrack API (except for set()), using
204 * an uninitialized AudioTrack produces undefined results.
205 * See set() method above for possible return codes.
206 */
207 status_t initCheck() const;
208
209 /* Returns this track's latency in milliseconds.
210 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
211 * and audio hardware driver.
212 */
213 uint32_t latency() const;
214
215 /* getters, see constructor */
216
217 int streamType() const;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 int format() const;
219 int channelCount() const;
220 uint32_t frameCount() const;
221 int frameSize() const;
222 sp<IMemory>& sharedBuffer();
223
224
225 /* After it's created the track is not active. Call start() to
226 * make it active. If set, the callback will start being called.
227 */
228 void start();
229
230 /* Stop a track. If set, the callback will cease being called and
231 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
232 * and will fill up buffers until the pool is exhausted.
233 */
234 void stop();
235 bool stopped() const;
236
237 /* flush a stopped track. All pending buffers are discarded.
238 * This function has no effect if the track is not stoped.
239 */
240 void flush();
241
242 /* Pause a track. If set, the callback will cease being called and
243 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
244 * and will fill up buffers until the pool is exhausted.
245 */
246 void pause();
247
248 /* mute or unmutes this track.
249 * While mutted, the callback, if set, is still called.
250 */
251 void mute(bool);
252 bool muted() const;
253
254
255 /* set volume for this track, mostly used for games' sound effects
Eric Laurent65b65452010-06-01 23:49:17 -0700256 * left and right volumes. Levels must be <= 1.0.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 */
Eric Laurent65b65452010-06-01 23:49:17 -0700258 status_t setVolume(float left, float right);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 void getVolume(float* left, float* right);
260
Eric Laurent65b65452010-06-01 23:49:17 -0700261 /* set the send level for this track. An auxiliary effect should be attached
262 * to the track with attachEffect(). Level must be <= 1.0.
263 */
Eric Laurent7070b362010-07-16 07:43:46 -0700264 status_t setAuxEffectSendLevel(float level);
265 void getAuxEffectSendLevel(float* level);
Eric Laurent65b65452010-06-01 23:49:17 -0700266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 /* set sample rate for this track, mostly used for games' sound effects
268 */
Eric Laurent88e209d2009-07-07 07:10:45 -0700269 status_t setSampleRate(int sampleRate);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 uint32_t getSampleRate();
271
272 /* Enables looping and sets the start and end points of looping.
273 *
274 * Parameters:
275 *
276 * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start.
277 * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start.
278 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
279 * active loop. loopCount = -1 means infinite looping.
280 *
281 * For proper operation the following condition must be respected:
282 * (loopEnd-loopStart) <= framecount()
283 */
284 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
285 status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
286
287
288 /* Sets marker position. When playback reaches the number of frames specified, a callback with event
289 * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification
290 * callback.
291 * If the AudioTrack has been opened with no callback function associated, the operation will fail.
292 *
293 * Parameters:
294 *
295 * marker: marker position expressed in frames.
296 *
297 * Returned status (from utils/Errors.h) can be:
298 * - NO_ERROR: successful operation
299 * - INVALID_OPERATION: the AudioTrack has no callback installed.
300 */
301 status_t setMarkerPosition(uint32_t marker);
302 status_t getMarkerPosition(uint32_t *marker);
303
304
305 /* Sets position update period. Every time the number of frames specified has been played,
306 * a callback with event type EVENT_NEW_POS is called.
307 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
308 * callback.
309 * If the AudioTrack has been opened with no callback function associated, the operation will fail.
310 *
311 * Parameters:
312 *
313 * updatePeriod: position update notification period expressed in frames.
314 *
315 * Returned status (from utils/Errors.h) can be:
316 * - NO_ERROR: successful operation
317 * - INVALID_OPERATION: the AudioTrack has no callback installed.
318 */
319 status_t setPositionUpdatePeriod(uint32_t updatePeriod);
320 status_t getPositionUpdatePeriod(uint32_t *updatePeriod);
321
322
323 /* Sets playback head position within AudioTrack buffer. The new position is specified
324 * in number of frames.
325 * This method must be called with the AudioTrack in paused or stopped state.
326 * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
327 * Therefore using this method makes sense only when playing a "static" audio buffer
328 * as opposed to streaming.
329 * The getPosition() method on the other hand returns the total number of frames played since
330 * playback start.
331 *
332 * Parameters:
333 *
334 * position: New playback head position within AudioTrack buffer.
335 *
336 * Returned status (from utils/Errors.h) can be:
337 * - NO_ERROR: successful operation
338 * - INVALID_OPERATION: the AudioTrack is not stopped.
339 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
340 */
341 status_t setPosition(uint32_t position);
342 status_t getPosition(uint32_t *position);
343
344 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
345 * rewriting the buffer before restarting playback after a stop.
346 * This method must be called with the AudioTrack in paused or stopped state.
347 *
348 * Returned status (from utils/Errors.h) can be:
349 * - NO_ERROR: successful operation
350 * - INVALID_OPERATION: the AudioTrack is not stopped.
351 */
352 status_t reload();
353
Eric Laurenta553c252009-07-17 12:17:14 -0700354 /* returns a handle on the audio output used by this AudioTrack.
355 *
356 * Parameters:
357 * none.
358 *
359 * Returned value:
360 * handle on audio hardware output
361 */
362 audio_io_handle_t getOutput();
363
Eric Laurent65b65452010-06-01 23:49:17 -0700364 /* returns the unique ID associated to this track.
365 *
366 * Parameters:
367 * none.
368 *
369 * Returned value:
370 * AudioTrack ID.
371 */
372 int getSessionId();
373
374
375 /* Attach track auxiliary output to specified effect. Used effectId = 0
376 * to detach track from effect.
377 *
378 * Parameters:
379 *
380 * effectId: effectId obtained from AudioEffect::id().
381 *
382 * Returned status (from utils/Errors.h) can be:
383 * - NO_ERROR: successful operation
384 * - INVALID_OPERATION: the effect is not an auxiliary effect.
385 * - BAD_VALUE: The specified effect ID is invalid
386 */
387 status_t attachAuxEffect(int effectId);
388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 /* obtains a buffer of "frameCount" frames. The buffer must be
390 * filled entirely. If the track is stopped, obtainBuffer() returns
391 * STOPPED instead of NO_ERROR as long as there are buffers availlable,
392 * at which point NO_MORE_BUFFERS is returned.
393 * Buffers will be returned until the pool (buffercount())
394 * is exhausted, at which point obtainBuffer() will either block
395 * or return WOULD_BLOCK depending on the value of the "blocking"
396 * parameter.
397 */
398
399 enum {
400 NO_MORE_BUFFERS = 0x80000001,
401 STOPPED = 1
402 };
403
404 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
405 void releaseBuffer(Buffer* audioBuffer);
406
407
408 /* As a convenience we provide a write() interface to the audio buffer.
409 * This is implemented on top of lockBuffer/unlockBuffer. For best
410 * performance
411 *
412 */
413 ssize_t write(const void* buffer, size_t size);
414
415 /*
416 * Dumps the state of an audio track.
417 */
418 status_t dump(int fd, const Vector<String16>& args) const;
419
420private:
421 /* copying audio tracks is not allowed */
422 AudioTrack(const AudioTrack& other);
423 AudioTrack& operator = (const AudioTrack& other);
424
425 /* a small internal class to handle the callback */
426 class AudioTrackThread : public Thread
427 {
428 public:
429 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
430 private:
431 friend class AudioTrack;
432 virtual bool threadLoop();
433 virtual status_t readyToRun();
434 virtual void onFirstRef();
435 AudioTrack& mReceiver;
436 Mutex mLock;
437 };
438
439 bool processAudioBuffer(const sp<AudioTrackThread>& thread);
Eric Laurent421ddc02011-03-07 14:52:59 -0800440 status_t createTrack_l(int streamType,
Eric Laurentbda74692009-11-04 08:27:26 -0800441 uint32_t sampleRate,
442 int format,
443 int channelCount,
444 int frameCount,
445 uint32_t flags,
446 const sp<IMemory>& sharedBuffer,
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700447 audio_io_handle_t output,
448 bool enforceFrameCount);
Eric Laurent421ddc02011-03-07 14:52:59 -0800449 void flush_l();
450 status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
451 audio_io_handle_t getOutput_l();
452 status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 sp<IAudioTrack> mAudioTrack;
455 sp<IMemory> mCblkMemory;
456 sp<AudioTrackThread> mAudioTrackThread;
457
458 float mVolume[2];
Eric Laurent65b65452010-06-01 23:49:17 -0700459 float mSendLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 uint32_t mFrameCount;
461
462 audio_track_cblk_t* mCblk;
463 uint8_t mStreamType;
464 uint8_t mFormat;
465 uint8_t mChannelCount;
466 uint8_t mMuted;
Eric Laurenta553c252009-07-17 12:17:14 -0700467 uint32_t mChannels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 status_t mStatus;
469 uint32_t mLatency;
470
471 volatile int32_t mActive;
472
473 callback_t mCbf;
474 void* mUserData;
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700475 uint32_t mNotificationFramesReq; // requested number of frames between each notification callback
476 uint32_t mNotificationFramesAct; // actual number of frames between each notification callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 sp<IMemory> mSharedBuffer;
478 int mLoopCount;
479 uint32_t mRemainingFrames;
480 uint32_t mMarkerPosition;
Jean-Michel Trivi4a5c1a72009-03-24 18:11:07 -0700481 bool mMarkerReached;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 uint32_t mNewPosition;
483 uint32_t mUpdatePeriod;
Eric Laurenta553c252009-07-17 12:17:14 -0700484 uint32_t mFlags;
Eric Laurent65b65452010-06-01 23:49:17 -0700485 int mSessionId;
Eric Laurent7070b362010-07-16 07:43:46 -0700486 int mAuxEffectId;
Eric Laurentf3d6dd02010-11-18 08:40:16 -0800487 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488};
489
490
491}; // namespace android
492
493#endif // ANDROID_AUDIOTRACK_H