blob: 659f5f8aa335e85296ee5a49d7f6e3732cf62922 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-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>
29#include <utils/IInterface.h>
30#include <utils/IMemory.h>
31#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.
120 * format: PCM sample format (e.g AudioSystem::PCM_16_BIT for signed
121 * 16 bits per sample).
122 * channelCount: Number of PCM channels (e.g 2 for stereo).
123 * 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,
136 int channelCount = 0,
137 int frameCount = 0,
138 uint32_t flags = 0,
139 callback_t cbf = 0,
140 void* user = 0,
141 int notificationFrames = 0);
142
143 /* Creates an audio track and registers it with AudioFlinger. With this constructor,
144 * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
145 * identified by the argument sharedBuffer. This prototype is for static buffer playback.
146 * PCM data must be present into memory before the AudioTrack is started.
147 * The Write() and Flush() methods are not supported in this case.
148 * It is recommented to pass a callback function to be notified of playback end by an
149 * EVENT_UNDERRUN event.
150 */
151
152 AudioTrack( int streamType,
153 uint32_t sampleRate = 0,
154 int format = 0,
155 int channelCount = 0,
156 const sp<IMemory>& sharedBuffer = 0,
157 uint32_t flags = 0,
158 callback_t cbf = 0,
159 void* user = 0,
160 int notificationFrames = 0);
161
162 /* Terminates the AudioTrack and unregisters it from AudioFlinger.
163 * Also destroys all resources assotiated with the AudioTrack.
164 */
165 ~AudioTrack();
166
167
168 /* Initialize an uninitialized AudioTrack.
169 * Returned status (from utils/Errors.h) can be:
170 * - NO_ERROR: successful intialization
171 * - INVALID_OPERATION: AudioTrack is already intitialized
172 * - BAD_VALUE: invalid parameter (channelCount, format, sampleRate...)
173 * - NO_INIT: audio server or audio hardware not initialized
174 * */
175 status_t set(int streamType =-1,
176 uint32_t sampleRate = 0,
177 int format = 0,
178 int channelCount = 0,
179 int frameCount = 0,
180 uint32_t flags = 0,
181 callback_t cbf = 0,
182 void* user = 0,
183 int notificationFrames = 0,
184 const sp<IMemory>& sharedBuffer = 0,
185 bool threadCanCallJava = false);
186
187
188 /* Result of constructing the AudioTrack. This must be checked
189 * before using any AudioTrack API (except for set()), using
190 * an uninitialized AudioTrack produces undefined results.
191 * See set() method above for possible return codes.
192 */
193 status_t initCheck() const;
194
195 /* Returns this track's latency in milliseconds.
196 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
197 * and audio hardware driver.
198 */
199 uint32_t latency() const;
200
201 /* getters, see constructor */
202
203 int streamType() const;
204 uint32_t sampleRate() const;
205 int format() const;
206 int channelCount() const;
207 uint32_t frameCount() const;
208 int frameSize() const;
209 sp<IMemory>& sharedBuffer();
210
211
212 /* After it's created the track is not active. Call start() to
213 * make it active. If set, the callback will start being called.
214 */
215 void start();
216
217 /* Stop a track. If set, the callback will cease being called and
218 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
219 * and will fill up buffers until the pool is exhausted.
220 */
221 void stop();
222 bool stopped() const;
223
224 /* flush a stopped track. All pending buffers are discarded.
225 * This function has no effect if the track is not stoped.
226 */
227 void flush();
228
229 /* Pause a track. If set, the callback will cease being called and
230 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
231 * and will fill up buffers until the pool is exhausted.
232 */
233 void pause();
234
235 /* mute or unmutes this track.
236 * While mutted, the callback, if set, is still called.
237 */
238 void mute(bool);
239 bool muted() const;
240
241
242 /* set volume for this track, mostly used for games' sound effects
243 */
244 void setVolume(float left, float right);
245 void getVolume(float* left, float* right);
246
247 /* set sample rate for this track, mostly used for games' sound effects
248 */
249 void setSampleRate(int sampleRate);
250 uint32_t getSampleRate();
251
252 /* Enables looping and sets the start and end points of looping.
253 *
254 * Parameters:
255 *
256 * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start.
257 * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start.
258 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
259 * active loop. loopCount = -1 means infinite looping.
260 *
261 * For proper operation the following condition must be respected:
262 * (loopEnd-loopStart) <= framecount()
263 */
264 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
265 status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
266
267
268 /* Sets marker position. When playback reaches the number of frames specified, a callback with event
269 * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification
270 * callback.
271 * If the AudioTrack has been opened with no callback function associated, the operation will fail.
272 *
273 * Parameters:
274 *
275 * marker: marker position expressed in frames.
276 *
277 * Returned status (from utils/Errors.h) can be:
278 * - NO_ERROR: successful operation
279 * - INVALID_OPERATION: the AudioTrack has no callback installed.
280 */
281 status_t setMarkerPosition(uint32_t marker);
282 status_t getMarkerPosition(uint32_t *marker);
283
284
285 /* Sets position update period. Every time the number of frames specified has been played,
286 * a callback with event type EVENT_NEW_POS is called.
287 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
288 * callback.
289 * If the AudioTrack has been opened with no callback function associated, the operation will fail.
290 *
291 * Parameters:
292 *
293 * updatePeriod: position update notification period expressed in frames.
294 *
295 * Returned status (from utils/Errors.h) can be:
296 * - NO_ERROR: successful operation
297 * - INVALID_OPERATION: the AudioTrack has no callback installed.
298 */
299 status_t setPositionUpdatePeriod(uint32_t updatePeriod);
300 status_t getPositionUpdatePeriod(uint32_t *updatePeriod);
301
302
303 /* Sets playback head position within AudioTrack buffer. The new position is specified
304 * in number of frames.
305 * This method must be called with the AudioTrack in paused or stopped state.
306 * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
307 * Therefore using this method makes sense only when playing a "static" audio buffer
308 * as opposed to streaming.
309 * The getPosition() method on the other hand returns the total number of frames played since
310 * playback start.
311 *
312 * Parameters:
313 *
314 * position: New playback head position within AudioTrack buffer.
315 *
316 * Returned status (from utils/Errors.h) can be:
317 * - NO_ERROR: successful operation
318 * - INVALID_OPERATION: the AudioTrack is not stopped.
319 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
320 */
321 status_t setPosition(uint32_t position);
322 status_t getPosition(uint32_t *position);
323
324 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
325 * rewriting the buffer before restarting playback after a stop.
326 * This method must be called with the AudioTrack in paused or stopped state.
327 *
328 * Returned status (from utils/Errors.h) can be:
329 * - NO_ERROR: successful operation
330 * - INVALID_OPERATION: the AudioTrack is not stopped.
331 */
332 status_t reload();
333
334 /* obtains a buffer of "frameCount" frames. The buffer must be
335 * filled entirely. If the track is stopped, obtainBuffer() returns
336 * STOPPED instead of NO_ERROR as long as there are buffers availlable,
337 * at which point NO_MORE_BUFFERS is returned.
338 * Buffers will be returned until the pool (buffercount())
339 * is exhausted, at which point obtainBuffer() will either block
340 * or return WOULD_BLOCK depending on the value of the "blocking"
341 * parameter.
342 */
343
344 enum {
345 NO_MORE_BUFFERS = 0x80000001,
346 STOPPED = 1
347 };
348
349 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
350 void releaseBuffer(Buffer* audioBuffer);
351
352
353 /* As a convenience we provide a write() interface to the audio buffer.
354 * This is implemented on top of lockBuffer/unlockBuffer. For best
355 * performance
356 *
357 */
358 ssize_t write(const void* buffer, size_t size);
359
360 /*
361 * Dumps the state of an audio track.
362 */
363 status_t dump(int fd, const Vector<String16>& args) const;
364
365private:
366 /* copying audio tracks is not allowed */
367 AudioTrack(const AudioTrack& other);
368 AudioTrack& operator = (const AudioTrack& other);
369
370 /* a small internal class to handle the callback */
371 class AudioTrackThread : public Thread
372 {
373 public:
374 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
375 private:
376 friend class AudioTrack;
377 virtual bool threadLoop();
378 virtual status_t readyToRun();
379 virtual void onFirstRef();
380 AudioTrack& mReceiver;
381 Mutex mLock;
382 };
383
384 bool processAudioBuffer(const sp<AudioTrackThread>& thread);
385
386 sp<IAudioFlinger> mAudioFlinger;
387 sp<IAudioTrack> mAudioTrack;
388 sp<IMemory> mCblkMemory;
389 sp<AudioTrackThread> mAudioTrackThread;
390
391 float mVolume[2];
392 uint32_t mSampleRate;
393 uint32_t mFrameCount;
394
395 audio_track_cblk_t* mCblk;
396 uint8_t mStreamType;
397 uint8_t mFormat;
398 uint8_t mChannelCount;
399 uint8_t mMuted;
400 status_t mStatus;
401 uint32_t mLatency;
402
403 volatile int32_t mActive;
404
405 callback_t mCbf;
406 void* mUserData;
407 uint32_t mNotificationFrames;
408 sp<IMemory> mSharedBuffer;
409 int mLoopCount;
410 uint32_t mRemainingFrames;
411 uint32_t mMarkerPosition;
412 uint32_t mNewPosition;
413 uint32_t mUpdatePeriod;
414};
415
416
417}; // namespace android
418
419#endif // ANDROID_AUDIOTRACK_H