blob: 10fa5e8fcf96334c2a510cb15fb1568446dd3caa [file] [log] [blame]
Hyundo Moon660a74e2017-12-13 11:29:45 +09001/*
2 * Copyright 2018 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_JAUDIOTRACK_H
18#define ANDROID_JAUDIOTRACK_H
19
20#include <jni.h>
Hyundo Moonfd328172017-12-14 10:46:54 +090021#include <media/AudioResamplerPublic.h>
22#include <media/VolumeShaper.h>
Hyundo Moon660a74e2017-12-13 11:29:45 +090023#include <system/audio.h>
Hyundo Moonfd328172017-12-14 10:46:54 +090024#include <utils/Errors.h>
25
26#include <media/AudioTimestamp.h> // It has dependency on audio.h/Errors.h, but doesn't
27 // include them in it. Therefore it is included here at last.
Hyundo Moon660a74e2017-12-13 11:29:45 +090028
29namespace android {
30
31class JAudioTrack {
32public:
33
34 /* Creates an JAudioTrack object for non-offload mode.
35 * Once created, the track needs to be started before it can be used.
36 * Unspecified values are set to appropriate default values.
37 *
38 * Parameters:
39 *
40 * streamType: Select the type of audio stream this track is attached to
41 * (e.g. AUDIO_STREAM_MUSIC).
42 * sampleRate: Data source sampling rate in Hz. Zero means to use the sink sample rate.
43 * A non-zero value must be specified if AUDIO_OUTPUT_FLAG_DIRECT is set.
44 * 0 will not work with current policy implementation for direct output
45 * selection where an exact match is needed for sampling rate.
46 * (TODO: Check direct output after flags can be used in Java AudioTrack.)
47 * format: Audio format. For mixed tracks, any PCM format supported by server is OK.
48 * For direct and offloaded tracks, the possible format(s) depends on the
49 * output sink.
50 * (TODO: How can we check whether a format is supported?)
51 * channelMask: Channel mask, such that audio_is_output_channel(channelMask) is true.
52 * frameCount: Minimum size of track PCM buffer in frames. This defines the
53 * application's contribution to the latency of the track.
54 * The actual size selected by the JAudioTrack could be larger if the
55 * requested size is not compatible with current audio HAL configuration.
56 * Zero means to use a default value.
57 * sessionId: Specific session ID, or zero to use default.
58 * pAttributes: If not NULL, supersedes streamType for use case selection.
59 * maxRequiredSpeed: For PCM tracks, this creates an appropriate buffer size that will allow
60 * maxRequiredSpeed playback. Values less than 1.0f and greater than
61 * AUDIO_TIMESTRETCH_SPEED_MAX will be clamped. For non-PCM tracks
62 * and direct or offloaded tracks, this parameter is ignored.
63 * (TODO: Handle this after offload / direct track is supported.)
64 *
65 * TODO: Revive removed arguments after offload mode is supported.
66 */
67 JAudioTrack(audio_stream_type_t streamType,
68 uint32_t sampleRate,
69 audio_format_t format,
70 audio_channel_mask_t channelMask,
71 size_t frameCount = 0,
72 audio_session_t sessionId = AUDIO_SESSION_ALLOCATE,
73 const audio_attributes_t* pAttributes = NULL,
74 float maxRequiredSpeed = 1.0f);
75
76 /*
77 Temporarily removed constructor arguments:
78
79 // Q. Values are in audio-base.h, but where can we find explanation for them?
80 audio_output_flags_t flags,
81
82 // Q. May be used in AudioTrack.setPreferredDevice(AudioDeviceInfo)?
83 audio_port_handle_t selectedDeviceId,
84
85 // Should be deleted, since we don't use Binder anymore.
86 bool doNotReconnect,
87
88 // Do we need UID and PID?
89 uid_t uid,
90 pid_t pid,
91
92 // TODO: Uses these values when Java AudioTrack supports the offload mode.
93 callback_t cbf,
94 void* user,
95 int32_t notificationFrames,
96 const audio_offload_info_t *offloadInfo,
97
98 // Fixed to false, but what is this?
99 threadCanCallJava
100 */
101
Hyundo Moon9b26e942017-12-14 10:46:54 +0900102 virtual ~JAudioTrack();
103
104 size_t frameCount();
105 size_t channelCount();
106
Hyundo Moon904183e2018-01-21 20:43:41 +0900107 /* Returns this track's estimated latency in milliseconds.
108 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
109 * and audio hardware driver.
110 */
111 uint32_t latency();
112
Hyundo Moon9b26e942017-12-14 10:46:54 +0900113 /* Return the total number of frames played since playback start.
114 * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
115 * It is reset to zero by flush(), reload(), and stop().
116 *
117 * Parameters:
118 *
119 * position: Address where to return play head position.
120 *
121 * Returned status (from utils/Errors.h) can be:
122 * - NO_ERROR: successful operation
123 * - BAD_VALUE: position is NULL
124 */
125 status_t getPosition(uint32_t *position);
126
Hyundo Moonfd328172017-12-14 10:46:54 +0900127 // TODO: Does this comment apply same to Java AudioTrack::getTimestamp?
128 // Changed the return type from status_t to bool, since Java AudioTrack::getTimestamp returns
129 // boolean. Will Java getTimestampWithStatus() be public?
130 /* Poll for a timestamp on demand.
131 * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs,
132 * or if you need to get the most recent timestamp outside of the event callback handler.
133 * Caution: calling this method too often may be inefficient;
134 * if you need a high resolution mapping between frame position and presentation time,
135 * consider implementing that at application level, based on the low resolution timestamps.
136 * Returns true if timestamp is valid.
137 * The timestamp parameter is undefined on return, if false is returned.
138 */
Hyundo Moon904183e2018-01-21 20:43:41 +0900139 bool getTimestamp(AudioTimestamp& timestamp);
Hyundo Moonfd328172017-12-14 10:46:54 +0900140
141 /* Set source playback rate for timestretch
142 * 1.0 is normal speed: < 1.0 is slower, > 1.0 is faster
143 * 1.0 is normal pitch: < 1.0 is lower pitch, > 1.0 is higher pitch
144 *
145 * AUDIO_TIMESTRETCH_SPEED_MIN <= speed <= AUDIO_TIMESTRETCH_SPEED_MAX
146 * AUDIO_TIMESTRETCH_PITCH_MIN <= pitch <= AUDIO_TIMESTRETCH_PITCH_MAX
147 *
148 * Speed increases the playback rate of media, but does not alter pitch.
149 * Pitch increases the "tonal frequency" of media, but does not affect the playback rate.
150 */
151 status_t setPlaybackRate(const AudioPlaybackRate &playbackRate);
152
153 /* Return current playback rate */
154 const AudioPlaybackRate getPlaybackRate();
155
156 /* Sets the volume shaper object */
157 media::VolumeShaper::Status applyVolumeShaper(
158 const sp<media::VolumeShaper::Configuration>& configuration,
159 const sp<media::VolumeShaper::Operation>& operation);
160
Hyundo Moon9b26e942017-12-14 10:46:54 +0900161 /* Set the send level for this track. An auxiliary effect should be attached
Hyundo Moonfd328172017-12-14 10:46:54 +0900162 * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
Hyundo Moon9b26e942017-12-14 10:46:54 +0900163 */
164 status_t setAuxEffectSendLevel(float level);
165
166 /* Attach track auxiliary output to specified effect. Use effectId = 0
167 * to detach track from effect.
168 *
169 * Parameters:
170 *
171 * effectId: effectId obtained from AudioEffect::id().
172 *
173 * Returned status (from utils/Errors.h) can be:
174 * - NO_ERROR: successful operation
Hyundo Moonfd328172017-12-14 10:46:54 +0900175 * - INVALID_OPERATION: The effect is not an auxiliary effect.
176 * - BAD_VALUE: The specified effect ID is invalid.
Hyundo Moon9b26e942017-12-14 10:46:54 +0900177 */
178 status_t attachAuxEffect(int effectId);
179
180 /* Set volume for this track, mostly used for games' sound effects
181 * left and right volumes. Levels must be >= 0.0 and <= 1.0.
182 * This is the older API. New applications should use setVolume(float) when possible.
183 */
184 status_t setVolume(float left, float right);
185
186 /* Set volume for all channels. This is the preferred API for new applications,
187 * especially for multi-channel content.
188 */
189 status_t setVolume(float volume);
190
191 // TODO: Does this comment equally apply to the Java AudioTrack::play()?
192 /* After it's created the track is not active. Call start() to
193 * make it active. If set, the callback will start being called.
194 * If the track was previously paused, volume is ramped up over the first mix buffer.
195 */
196 status_t start();
197
Hyundo Moonfd328172017-12-14 10:46:54 +0900198 // TODO: Does this comment still applies? It seems not. (obtainBuffer, AudioFlinger, ...)
199 /* As a convenience we provide a write() interface to the audio buffer.
200 * Input parameter 'size' is in byte units.
201 * This is implemented on top of obtainBuffer/releaseBuffer. For best
202 * performance use callbacks. Returns actual number of bytes written >= 0,
203 * or one of the following negative status codes:
204 * INVALID_OPERATION AudioTrack is configured for static buffer or streaming mode
205 * BAD_VALUE size is invalid
206 * WOULD_BLOCK when obtainBuffer() returns same, or
207 * AudioTrack was stopped during the write
208 * DEAD_OBJECT when AudioFlinger dies or the output device changes and
209 * the track cannot be automatically restored.
210 * The application needs to recreate the AudioTrack
211 * because the audio device changed or AudioFlinger died.
212 * This typically occurs for direct or offload tracks
213 * or if mDoNotReconnect is true.
214 * or any other error code returned by IAudioTrack::start() or restoreTrack_l().
215 * Default behavior is to only return when all data has been transferred. Set 'blocking' to
216 * false for the method to return immediately without waiting to try multiple times to write
217 * the full content of the buffer.
218 */
219 ssize_t write(const void* buffer, size_t size, bool blocking = true);
220
Hyundo Moon9b26e942017-12-14 10:46:54 +0900221 // TODO: Does this comment equally apply to the Java AudioTrack::stop()?
222 /* Stop a track.
223 * In static buffer mode, the track is stopped immediately.
224 * In streaming mode, the callback will cease being called. Note that obtainBuffer() still
225 * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK.
226 * In streaming mode the stop does not occur immediately: any data remaining in the buffer
227 * is first drained, mixed, and output, and only then is the track marked as stopped.
228 */
Hyundo Moon660a74e2017-12-13 11:29:45 +0900229 void stop();
Hyundo Moon9b26e942017-12-14 10:46:54 +0900230 bool stopped() const;
Hyundo Moon660a74e2017-12-13 11:29:45 +0900231
Hyundo Moon9b26e942017-12-14 10:46:54 +0900232 // TODO: Does this comment equally apply to the Java AudioTrack::flush()?
233 /* Flush a stopped or paused track. All previously buffered data is discarded immediately.
234 * This has the effect of draining the buffers without mixing or output.
235 * Flush is intended for streaming mode, for example before switching to non-contiguous content.
236 * This function is a no-op if the track is not stopped or paused, or uses a static buffer.
237 */
238 void flush();
Hyundo Moon660a74e2017-12-13 11:29:45 +0900239
Hyundo Moon9b26e942017-12-14 10:46:54 +0900240 // TODO: Does this comment equally apply to the Java AudioTrack::pause()?
241 // At least we are not using obtainBuffer.
242 /* Pause a track. After pause, the callback will cease being called and
243 * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works
244 * and will fill up buffers until the pool is exhausted.
245 * Volume is ramped down over the next mix buffer following the pause request,
246 * and then the track is marked as paused. It can be resumed with ramp up by start().
247 */
248 void pause();
249
250 bool isPlaying() const;
251
252 /* Return current source sample rate in Hz.
253 * If specified as zero in constructor, this will be the sink sample rate.
254 */
255 uint32_t getSampleRate();
256
Hyundo Moonfd328172017-12-14 10:46:54 +0900257 /* Returns the buffer duration in microseconds at current playback rate. */
258 status_t getBufferDurationInUs(int64_t *duration);
259
Hyundo Moon9b26e942017-12-14 10:46:54 +0900260 audio_format_t format();
261
Hyundo Moon904183e2018-01-21 20:43:41 +0900262 /*
263 * Dumps the state of an audio track.
264 * Not a general-purpose API; intended only for use by media player service to dump its tracks.
265 */
266 status_t dump(int fd, const Vector<String16>& args) const;
267
268 /* Returns the ID of the audio device actually used by the output to which this AudioTrack is
269 * attached. When the AudioTrack is inactive, it will return AUDIO_PORT_HANDLE_NONE.
270 */
271 audio_port_handle_t getRoutedDeviceId();
272
Hyundo Moon9b26e942017-12-14 10:46:54 +0900273private:
274 jclass mAudioTrackCls;
275 jobject mAudioTrackObj;
276
Hyundo Moonfd328172017-12-14 10:46:54 +0900277 /* Creates a Java VolumeShaper.Configuration object from VolumeShaper::Configuration */
278 jobject createVolumeShaperConfigurationObj(
279 const sp<media::VolumeShaper::Configuration>& config);
280
281 /* Creates a Java VolumeShaper.Operation object from VolumeShaper::Operation */
282 jobject createVolumeShaperOperationObj(
283 const sp<media::VolumeShaper::Operation>& operation);
284
Hyundo Moon9b26e942017-12-14 10:46:54 +0900285 status_t javaToNativeStatus(int javaStatus);
Hyundo Moon660a74e2017-12-13 11:29:45 +0900286};
287
288}; // namespace android
289
290#endif // ANDROID_JAUDIOTRACK_H