JAudioTrack.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  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. #ifndef ANDROID_JAUDIOTRACK_H
  17. #define ANDROID_JAUDIOTRACK_H
  18. #include <utility>
  19. #include <jni.h>
  20. #include <media/AudioResamplerPublic.h>
  21. #include <media/AudioSystem.h>
  22. #include <media/VolumeShaper.h>
  23. #include <system/audio.h>
  24. #include <utils/Errors.h>
  25. #include <utils/Vector.h>
  26. #include <mediaplayer2/JObjectHolder.h>
  27. #include <media/AudioTimestamp.h> // It has dependency on audio.h/Errors.h, but doesn't
  28. // include them in it. Therefore it is included here at last.
  29. namespace android {
  30. class JAudioTrack : public RefBase {
  31. public:
  32. /* Events used by AudioTrack callback function (callback_t).
  33. * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*.
  34. */
  35. enum event_type {
  36. EVENT_MORE_DATA = 0, // Request to write more data to buffer.
  37. EVENT_UNDERRUN = 1, // Buffer underrun occurred. This will not occur for
  38. // static tracks.
  39. EVENT_NEW_IAUDIOTRACK = 6, // IAudioTrack was re-created, either due to re-routing and
  40. // voluntary invalidation by mediaserver, or mediaserver crash.
  41. EVENT_STREAM_END = 7, // Sent after all the buffers queued in AF and HW are played
  42. // back (after stop is called) for an offloaded track.
  43. };
  44. class Buffer
  45. {
  46. public:
  47. size_t mSize; // input/output in bytes.
  48. void* mData; // pointer to the audio data.
  49. };
  50. /* As a convenience, if a callback is supplied, a handler thread
  51. * is automatically created with the appropriate priority. This thread
  52. * invokes the callback when a new buffer becomes available or various conditions occur.
  53. *
  54. * Parameters:
  55. *
  56. * event: type of event notified (see enum AudioTrack::event_type).
  57. * user: Pointer to context for use by the callback receiver.
  58. * info: Pointer to optional parameter according to event type:
  59. * - EVENT_MORE_DATA: pointer to JAudioTrack::Buffer struct. The callback must not
  60. * write more bytes than indicated by 'size' field and update 'size' if fewer bytes
  61. * are written.
  62. * - EVENT_NEW_IAUDIOTRACK: unused.
  63. * - EVENT_STREAM_END: unused.
  64. */
  65. typedef void (*callback_t)(int event, void* user, void *info);
  66. /* Creates an JAudioTrack object for non-offload mode.
  67. * Once created, the track needs to be started before it can be used.
  68. * Unspecified values are set to appropriate default values.
  69. *
  70. * Parameters:
  71. *
  72. * streamType: Select the type of audio stream this track is attached to
  73. * (e.g. AUDIO_STREAM_MUSIC).
  74. * sampleRate: Data source sampling rate in Hz. Zero means to use the sink sample rate.
  75. * A non-zero value must be specified if AUDIO_OUTPUT_FLAG_DIRECT is set.
  76. * 0 will not work with current policy implementation for direct output
  77. * selection where an exact match is needed for sampling rate.
  78. * (TODO: Check direct output after flags can be used in Java AudioTrack.)
  79. * format: Audio format. For mixed tracks, any PCM format supported by server is OK.
  80. * For direct and offloaded tracks, the possible format(s) depends on the
  81. * output sink.
  82. * (TODO: How can we check whether a format is supported?)
  83. * channelMask: Channel mask, such that audio_is_output_channel(channelMask) is true.
  84. * cbf: Callback function. If not null, this function is called periodically
  85. * to provide new data and inform of marker, position updates, etc.
  86. * user: Context for use by the callback receiver.
  87. * frameCount: Minimum size of track PCM buffer in frames. This defines the
  88. * application's contribution to the latency of the track.
  89. * The actual size selected by the JAudioTrack could be larger if the
  90. * requested size is not compatible with current audio HAL configuration.
  91. * Zero means to use a default value.
  92. * sessionId: Specific session ID, or zero to use default.
  93. * pAttributes: If not NULL, supersedes streamType for use case selection.
  94. * maxRequiredSpeed: For PCM tracks, this creates an appropriate buffer size that will allow
  95. * maxRequiredSpeed playback. Values less than 1.0f and greater than
  96. * AUDIO_TIMESTRETCH_SPEED_MAX will be clamped. For non-PCM tracks
  97. * and direct or offloaded tracks, this parameter is ignored.
  98. * (TODO: Handle this after offload / direct track is supported.)
  99. *
  100. * TODO: Revive removed arguments after offload mode is supported.
  101. */
  102. JAudioTrack(uint32_t sampleRate,
  103. audio_format_t format,
  104. audio_channel_mask_t channelMask,
  105. callback_t cbf,
  106. void* user,
  107. size_t frameCount = 0,
  108. int32_t sessionId = AUDIO_SESSION_ALLOCATE,
  109. const jobject pAttributes = NULL,
  110. float maxRequiredSpeed = 1.0f);
  111. /*
  112. // Q. May be used in AudioTrack.setPreferredDevice(AudioDeviceInfo)?
  113. audio_port_handle_t selectedDeviceId,
  114. // TODO: No place to use these values.
  115. int32_t notificationFrames,
  116. const audio_offload_info_t *offloadInfo,
  117. */
  118. virtual ~JAudioTrack();
  119. size_t frameCount();
  120. size_t channelCount();
  121. /* Returns this track's estimated latency in milliseconds.
  122. * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
  123. * and audio hardware driver.
  124. */
  125. uint32_t latency();
  126. /* Return the total number of frames played since playback start.
  127. * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
  128. * It is reset to zero by flush(), reload(), and stop().
  129. *
  130. * Parameters:
  131. *
  132. * position: Address where to return play head position.
  133. *
  134. * Returned status (from utils/Errors.h) can be:
  135. * - NO_ERROR: successful operation
  136. * - BAD_VALUE: position is NULL
  137. */
  138. status_t getPosition(uint32_t *position);
  139. // TODO: Does this comment apply same to Java AudioTrack::getTimestamp?
  140. // Changed the return type from status_t to bool, since Java AudioTrack::getTimestamp returns
  141. // boolean. Will Java getTimestampWithStatus() be public?
  142. /* Poll for a timestamp on demand.
  143. * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs,
  144. * or if you need to get the most recent timestamp outside of the event callback handler.
  145. * Caution: calling this method too often may be inefficient;
  146. * if you need a high resolution mapping between frame position and presentation time,
  147. * consider implementing that at application level, based on the low resolution timestamps.
  148. * Returns NO_ERROR if timestamp is valid.
  149. * NO_INIT if finds error, and timestamp parameter will be undefined on return.
  150. */
  151. status_t getTimestamp(AudioTimestamp& timestamp);
  152. // TODO: This doc is just copied from AudioTrack.h. Revise it after implemenation.
  153. /* Return the extended timestamp, with additional timebase info and improved drain behavior.
  154. *
  155. * This is similar to the AudioTrack.java API:
  156. * getTimestamp(@NonNull AudioTimestamp timestamp, @AudioTimestamp.Timebase int timebase)
  157. *
  158. * Some differences between this method and the getTimestamp(AudioTimestamp& timestamp) method
  159. *
  160. * 1. stop() by itself does not reset the frame position.
  161. * A following start() resets the frame position to 0.
  162. * 2. flush() by itself does not reset the frame position.
  163. * The frame position advances by the number of frames flushed,
  164. * when the first frame after flush reaches the audio sink.
  165. * 3. BOOTTIME clock offsets are provided to help synchronize with
  166. * non-audio streams, e.g. sensor data.
  167. * 4. Position is returned with 64 bits of resolution.
  168. *
  169. * Parameters:
  170. * timestamp: A pointer to the caller allocated ExtendedTimestamp.
  171. *
  172. * Returns NO_ERROR on success; timestamp is filled with valid data.
  173. * BAD_VALUE if timestamp is NULL.
  174. * WOULD_BLOCK if called immediately after start() when the number
  175. * of frames consumed is less than the
  176. * overall hardware latency to physical output. In WOULD_BLOCK cases,
  177. * one might poll again, or use getPosition(), or use 0 position and
  178. * current time for the timestamp.
  179. * If WOULD_BLOCK is returned, the timestamp is still
  180. * modified with the LOCATION_CLIENT portion filled.
  181. * DEAD_OBJECT if AudioFlinger dies or the output device changes and
  182. * the track cannot be automatically restored.
  183. * The application needs to recreate the AudioTrack
  184. * because the audio device changed or AudioFlinger died.
  185. * This typically occurs for direct or offloaded tracks
  186. * or if mDoNotReconnect is true.
  187. * INVALID_OPERATION if called on a offloaded or direct track.
  188. * Use getTimestamp(AudioTimestamp& timestamp) instead.
  189. */
  190. status_t getTimestamp(ExtendedTimestamp *timestamp);
  191. /* Set source playback rate for timestretch
  192. * 1.0 is normal speed: < 1.0 is slower, > 1.0 is faster
  193. * 1.0 is normal pitch: < 1.0 is lower pitch, > 1.0 is higher pitch
  194. *
  195. * AUDIO_TIMESTRETCH_SPEED_MIN <= speed <= AUDIO_TIMESTRETCH_SPEED_MAX
  196. * AUDIO_TIMESTRETCH_PITCH_MIN <= pitch <= AUDIO_TIMESTRETCH_PITCH_MAX
  197. *
  198. * Speed increases the playback rate of media, but does not alter pitch.
  199. * Pitch increases the "tonal frequency" of media, but does not affect the playback rate.
  200. */
  201. status_t setPlaybackRate(const AudioPlaybackRate &playbackRate);
  202. /* Return current playback rate */
  203. const AudioPlaybackRate getPlaybackRate();
  204. /* Sets the volume shaper object */
  205. media::VolumeShaper::Status applyVolumeShaper(
  206. const sp<media::VolumeShaper::Configuration>& configuration,
  207. const sp<media::VolumeShaper::Operation>& operation);
  208. /* Set the send level for this track. An auxiliary effect should be attached
  209. * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
  210. */
  211. status_t setAuxEffectSendLevel(float level);
  212. /* Attach track auxiliary output to specified effect. Use effectId = 0
  213. * to detach track from effect.
  214. *
  215. * Parameters:
  216. *
  217. * effectId: effectId obtained from AudioEffect::id().
  218. *
  219. * Returned status (from utils/Errors.h) can be:
  220. * - NO_ERROR: successful operation
  221. * - INVALID_OPERATION: The effect is not an auxiliary effect.
  222. * - BAD_VALUE: The specified effect ID is invalid.
  223. */
  224. status_t attachAuxEffect(int effectId);
  225. /* Set volume for this track, mostly used for games' sound effects
  226. * left and right volumes. Levels must be >= 0.0 and <= 1.0.
  227. * This is the older API. New applications should use setVolume(float) when possible.
  228. */
  229. status_t setVolume(float left, float right);
  230. /* Set volume for all channels. This is the preferred API for new applications,
  231. * especially for multi-channel content.
  232. */
  233. status_t setVolume(float volume);
  234. // TODO: Does this comment equally apply to the Java AudioTrack::play()?
  235. /* After it's created the track is not active. Call start() to
  236. * make it active. If set, the callback will start being called.
  237. * If the track was previously paused, volume is ramped up over the first mix buffer.
  238. */
  239. status_t start();
  240. // TODO: Does this comment still applies? It seems not. (obtainBuffer, AudioFlinger, ...)
  241. /* As a convenience we provide a write() interface to the audio buffer.
  242. * Input parameter 'size' is in byte units.
  243. * This is implemented on top of obtainBuffer/releaseBuffer. For best
  244. * performance use callbacks. Returns actual number of bytes written >= 0,
  245. * or one of the following negative status codes:
  246. * INVALID_OPERATION AudioTrack is configured for static buffer or streaming mode
  247. * BAD_VALUE size is invalid
  248. * WOULD_BLOCK when obtainBuffer() returns same, or
  249. * AudioTrack was stopped during the write
  250. * DEAD_OBJECT when AudioFlinger dies or the output device changes and
  251. * the track cannot be automatically restored.
  252. * The application needs to recreate the AudioTrack
  253. * because the audio device changed or AudioFlinger died.
  254. * This typically occurs for direct or offload tracks
  255. * or if mDoNotReconnect is true.
  256. * or any other error code returned by IAudioTrack::start() or restoreTrack_l().
  257. * Default behavior is to only return when all data has been transferred. Set 'blocking' to
  258. * false for the method to return immediately without waiting to try multiple times to write
  259. * the full content of the buffer.
  260. */
  261. ssize_t write(const void* buffer, size_t size, bool blocking = true);
  262. // TODO: Does this comment equally apply to the Java AudioTrack::stop()?
  263. /* Stop a track.
  264. * In static buffer mode, the track is stopped immediately.
  265. * In streaming mode, the callback will cease being called. Note that obtainBuffer() still
  266. * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK.
  267. * In streaming mode the stop does not occur immediately: any data remaining in the buffer
  268. * is first drained, mixed, and output, and only then is the track marked as stopped.
  269. */
  270. void stop();
  271. bool stopped() const;
  272. // TODO: Does this comment equally apply to the Java AudioTrack::flush()?
  273. /* Flush a stopped or paused track. All previously buffered data is discarded immediately.
  274. * This has the effect of draining the buffers without mixing or output.
  275. * Flush is intended for streaming mode, for example before switching to non-contiguous content.
  276. * This function is a no-op if the track is not stopped or paused, or uses a static buffer.
  277. */
  278. void flush();
  279. // TODO: Does this comment equally apply to the Java AudioTrack::pause()?
  280. // At least we are not using obtainBuffer.
  281. /* Pause a track. After pause, the callback will cease being called and
  282. * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works
  283. * and will fill up buffers until the pool is exhausted.
  284. * Volume is ramped down over the next mix buffer following the pause request,
  285. * and then the track is marked as paused. It can be resumed with ramp up by start().
  286. */
  287. void pause();
  288. bool isPlaying() const;
  289. /* Return current source sample rate in Hz.
  290. * If specified as zero in constructor, this will be the sink sample rate.
  291. */
  292. uint32_t getSampleRate();
  293. /* Returns the buffer duration in microseconds at current playback rate. */
  294. status_t getBufferDurationInUs(int64_t *duration);
  295. audio_format_t format();
  296. size_t frameSize();
  297. /*
  298. * Dumps the state of an audio track.
  299. * Not a general-purpose API; intended only for use by media player service to dump its tracks.
  300. */
  301. status_t dump(int fd, const Vector<String16>& args) const;
  302. /* Returns the AudioDeviceInfo used by the output to which this AudioTrack is
  303. * attached.
  304. */
  305. jobject getRoutedDevice();
  306. /* Returns the ID of the audio session this AudioTrack belongs to. */
  307. int32_t getAudioSessionId();
  308. /* Sets the preferred audio device to use for output of this AudioTrack.
  309. *
  310. * Parameters:
  311. * Device: an AudioDeviceInfo object.
  312. *
  313. * Returned value:
  314. * - NO_ERROR: successful operation
  315. * - BAD_VALUE: failed to set the device
  316. */
  317. status_t setPreferredDevice(jobject device);
  318. // TODO: Add AUDIO_OUTPUT_FLAG_DIRECT when it is possible to check.
  319. // TODO: Add AUDIO_FLAG_HW_AV_SYNC when it is possible to check.
  320. /* Returns the flags */
  321. audio_output_flags_t getFlags() const { return mFlags; }
  322. /* We don't keep stream type here,
  323. * instead, we keep attributes and call getVolumeControlStream() to get stream type
  324. */
  325. audio_stream_type_t getAudioStreamType();
  326. /* Obtain the pending duration in milliseconds for playback of pure PCM data remaining in
  327. * AudioTrack.
  328. *
  329. * Returns NO_ERROR if successful.
  330. * INVALID_OPERATION if the AudioTrack does not contain pure PCM data.
  331. * BAD_VALUE if msec is nullptr.
  332. */
  333. status_t pendingDuration(int32_t *msec);
  334. /* Adds an AudioDeviceCallback. The caller will be notified when the audio device to which this
  335. * AudioTrack is routed is updated.
  336. * Replaces any previously installed callback.
  337. *
  338. * Parameters:
  339. * Listener: the listener to receive notification of rerouting events.
  340. * Handler: the handler to handler the rerouting events.
  341. *
  342. * Returns NO_ERROR if successful.
  343. * (TODO) INVALID_OPERATION if the same callback is already installed.
  344. * (TODO) NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
  345. * (TODO) BAD_VALUE if the callback is NULL
  346. */
  347. status_t addAudioDeviceCallback(jobject listener, jobject rd);
  348. /* Removes an AudioDeviceCallback.
  349. *
  350. * Parameters:
  351. * Listener: the listener to receive notification of rerouting events.
  352. *
  353. * Returns NO_ERROR if successful.
  354. * (TODO) INVALID_OPERATION if the callback is not installed
  355. * (TODO) BAD_VALUE if the callback is NULL
  356. */
  357. status_t removeAudioDeviceCallback(jobject listener);
  358. /* Register all backed-up routing delegates.
  359. *
  360. * Parameters:
  361. * routingDelegates: backed-up routing delegates
  362. *
  363. */
  364. void registerRoutingDelegates(
  365. Vector<std::pair<sp<JObjectHolder>, sp<JObjectHolder>>>& routingDelegates);
  366. /* get listener from RoutingDelegate object
  367. */
  368. static jobject getListener(const jobject routingDelegateObj);
  369. /* get handler from RoutingDelegate object
  370. */
  371. static jobject getHandler(const jobject routingDelegateObj);
  372. /*
  373. * Parameters:
  374. * map and key
  375. *
  376. * Returns value if key is in the map
  377. * nullptr if key is not in the map
  378. */
  379. static jobject findByKey(
  380. Vector<std::pair<sp<JObjectHolder>, sp<JObjectHolder>>>& mp, const jobject key);
  381. /*
  382. * Parameters:
  383. * map and key
  384. */
  385. static void eraseByKey(
  386. Vector<std::pair<sp<JObjectHolder>, sp<JObjectHolder>>>& mp, const jobject key);
  387. private:
  388. audio_output_flags_t mFlags;
  389. jclass mAudioTrackCls;
  390. jobject mAudioTrackObj;
  391. /* Creates a Java VolumeShaper.Configuration object from VolumeShaper::Configuration */
  392. jobject createVolumeShaperConfigurationObj(
  393. const sp<media::VolumeShaper::Configuration>& config);
  394. /* Creates a Java VolumeShaper.Operation object from VolumeShaper::Operation */
  395. jobject createVolumeShaperOperationObj(
  396. const sp<media::VolumeShaper::Operation>& operation);
  397. /* Creates a Java StreamEventCallback object */
  398. jobject createStreamEventCallback(callback_t cbf, void* user);
  399. /* Creates a Java Executor object for running a callback */
  400. jobject createCallbackExecutor();
  401. status_t javaToNativeStatus(int javaStatus);
  402. };
  403. }; // namespace android
  404. #endif // ANDROID_JAUDIOTRACK_H