Debian Codegraph @

core/jni/android_media_AudioRecord.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2008 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 //#define LOG_NDEBUG 0
18
19 #define LOG_TAG "AudioRecord-JNI"
20
21 #include <android/content/AttributionSourceState.h>
22 #include <android_os_Parcel.h>
23 #include <inttypes.h>
24 #include <jni.h>
25 #include <media/AudioRecord.h>
26 #include <nativehelper/JNIHelp.h>
27 #include <nativehelper/ScopedUtfChars.h>
28 #include <utils/Log.h>
29
30 #include <vector>
31
32 #include "android_media_AudioAttributes.h"
33 #include "android_media_AudioErrors.h"
34 #include "android_media_AudioFormat.h"
35 #include "android_media_DeviceCallback.h"
36 #include "android_media_JNIUtils.h"
37 #include "android_media_MediaMetricsJNI.h"
38 #include "android_media_MicrophoneInfo.h"
39 #include "core_jni_helpers.h"
40
41 // ----------------------------------------------------------------------------
42
43 using namespace android;
44
45 // ----------------------------------------------------------------------------
46 static const char* const kClassPathName = "android/media/AudioRecord";
47
48 static jclass gArrayListClass;
49 static struct {
50 jmethodID add;
51 } gArrayListMethods;
52
53 struct audio_record_fields_t {
54 // these fields provide access from C++ to the...
55 jmethodID postNativeEventInJava; //... event post callback method
56 jfieldID nativeRecorderInJavaObj; // provides access to the C++ AudioRecord object
57 jfieldID jniData; // provides access to AudioRecord JNI Handle
58 };
59 static audio_record_fields_t javaAudioRecordFields;
60 static struct {
61 jfieldID fieldFramePosition; // AudioTimestamp.framePosition
62 jfieldID fieldNanoTime; // AudioTimestamp.nanoTime
63 } javaAudioTimestampFields;
64
65
66 class AudioRecordJNIStorage : public AudioRecord::IAudioRecordCallback {
67 private:
68 // Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*.
69 enum class EventType {
70 EVENT_MORE_DATA = 0, // Request to read available data from buffer.
71 // If this event is delivered but the callback handler
72 // does not want to read the available data, the handler must
73 // explicitly ignore the event by setting frameCount to zero.
74 EVENT_OVERRUN = 1, // Buffer overrun occurred.
75 EVENT_MARKER = 2, // Record head is at the specified marker position
76 // (See setMarkerPosition()).
77 EVENT_NEW_POS = 3, // Record head is at a new position
78 // (See setPositionUpdatePeriod()).
79 EVENT_NEW_IAUDIORECORD = 4, // IAudioRecord was re-created, either due to re-routing and
80 // voluntary invalidation by mediaserver, or mediaserver crash.
81 };
82
83 public:
84 AudioRecordJNIStorage(jclass audioRecordClass, jobject audioRecordWeakRef)
85 : mAudioRecordClass(audioRecordClass), mAudioRecordWeakRef(audioRecordWeakRef) {}
86 AudioRecordJNIStorage(const AudioRecordJNIStorage &) = delete;
87 AudioRecordJNIStorage& operator=(const AudioRecordJNIStorage &) = delete;
88
89 void onMarker(uint32_t) override {
90 postEvent(EventType::EVENT_MARKER);
91 }
92
93 void onNewPos(uint32_t) override {
94 postEvent(EventType::EVENT_NEW_POS);
95 }
96
97 void setDeviceCallback(const sp<JNIDeviceCallback>& callback) {
98 mDeviceCallback = callback;
99 }
100
101 sp<JNIDeviceCallback> getDeviceCallback() const { return mDeviceCallback; }
102
103 jobject getAudioTrackWeakRef() const & { return mAudioRecordWeakRef.get(); }
104
105 // If we attempt to get a jobject from a rvalue, it will soon go out of
106 // scope, and the reference count can drop to zero, which is unsafe.
107 jobject getAudioTrackWeakRef() const && = delete;
108
109 private:
110 void postEvent(EventType event, int arg = 0) const {
111 JNIEnv *env = getJNIEnvOrDie();
112 env->CallStaticVoidMethod(
113 static_cast<jclass>(mAudioRecordClass.get()),
114 javaAudioRecordFields.postNativeEventInJava,
115 mAudioRecordWeakRef.get(), static_cast<int>(event), arg, 0, nullptr);
116 if (env->ExceptionCheck()) {
117 env->ExceptionDescribe();
118 env->ExceptionClear();
119 }
120 }
121
122 // Mutation of this object is protected using Java concurrency constructs
123 sp<JNIDeviceCallback> mDeviceCallback;
124 const GlobalRef mAudioRecordClass;
125 const GlobalRef mAudioRecordWeakRef;
126 };
127
128 // ----------------------------------------------------------------------------
129
130 #define AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT (-16)
131 #define AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK (-17)
132 #define AUDIORECORD_ERROR_SETUP_INVALIDFORMAT (-18)
133 #define AUDIORECORD_ERROR_SETUP_INVALIDSOURCE (-19)
134 #define AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED (-20)
135
136 // ----------------------------------------------------------------------------
137 static sp<AudioRecord> getAudioRecord(JNIEnv* env, jobject thiz)
138 {
139 return getFieldSp<AudioRecord>(env, thiz, javaAudioRecordFields.nativeRecorderInJavaObj);
140 }
141
142 // ----------------------------------------------------------------------------
143 static jint android_media_AudioRecord_setup(JNIEnv *env, jobject thiz, jobject weak_this,
144 jobject jaa, jintArray jSampleRate, jint channelMask,
145 jint channelIndexMask, jint audioFormat,
146 jint buffSizeInBytes, jintArray jSession,
147 jobject jAttributionSource, jlong nativeRecordInJavaObj,
148 jint sharedAudioHistoryMs) {
149 //ALOGV(">> Entering android_media_AudioRecord_setup");
150 //ALOGV("sampleRate=%d, audioFormat=%d, channel mask=%x, buffSizeInBytes=%d "
151 // "nativeRecordInJavaObj=0x%llX",
152 // sampleRateInHertz, audioFormat, channelMask, buffSizeInBytes, nativeRecordInJavaObj);
153 audio_channel_mask_t localChanMask = inChannelMaskToNative(channelMask);
154
155 if (jSession == NULL) {
156 ALOGE("Error creating AudioRecord: invalid session ID pointer");
157 return (jint) AUDIO_JAVA_ERROR;
158 }
159
160 jint* nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL);
161 if (nSession == NULL) {
162 ALOGE("Error creating AudioRecord: Error retrieving session id pointer");
163 return (jint) AUDIO_JAVA_ERROR;
164 }
165 audio_session_t sessionId = (audio_session_t) nSession[0];
166 env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
167 nSession = NULL;
168
169 sp<AudioRecord> lpRecorder;
170 sp<AudioRecordJNIStorage> callbackData;
171 jclass clazz = env->GetObjectClass(thiz);
172 if (clazz == NULL) {
173 ALOGE("Can't find %s when setting up callback.", kClassPathName);
174 return (jint) AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED;
175 }
176
177 // if we pass in an existing *Native* AudioRecord, we don't need to create/initialize one.
178 if (nativeRecordInJavaObj == 0) {
179 if (jaa == 0) {
180 ALOGE("Error creating AudioRecord: invalid audio attributes");
181 return (jint) AUDIO_JAVA_ERROR;
182 }
183
184 if (jSampleRate == 0) {
185 ALOGE("Error creating AudioRecord: invalid sample rates");
186 return (jint) AUDIO_JAVA_ERROR;
187 }
188 jint elements[1];
189 env->GetIntArrayRegion(jSampleRate, 0, 1, elements);
190 int sampleRateInHertz = elements[0];
191
192 // channel index mask takes priority over channel position masks.
193 if (channelIndexMask) {
194 // Java channel index masks need the representation bits set.
195 localChanMask = audio_channel_mask_from_representation_and_bits(
196 AUDIO_CHANNEL_REPRESENTATION_INDEX,
197 channelIndexMask);
198 }
199 // Java channel position masks map directly to the native definition
200
201 if (!audio_is_input_channel(localChanMask)) {
202 ALOGE("Error creating AudioRecord: channel mask %#x is not valid.", localChanMask);
203 return (jint) AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK;
204 }
205 uint32_t channelCount = audio_channel_count_from_in_mask(localChanMask);
206
207 // compare the format against the Java constants
208 audio_format_t format = audioFormatToNative(audioFormat);
209 if (format == AUDIO_FORMAT_INVALID) {
210 ALOGE("Error creating AudioRecord: unsupported audio format %d.", audioFormat);
211 return (jint) AUDIORECORD_ERROR_SETUP_INVALIDFORMAT;
212 }
213
214 size_t bytesPerSample = audio_bytes_per_sample(format);
215
216 if (buffSizeInBytes == 0) {
217 ALOGE("Error creating AudioRecord: frameCount is 0.");
218 return (jint) AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT;
219 }
220 size_t frameSize = channelCount * bytesPerSample;
221 size_t frameCount = buffSizeInBytes / frameSize;
222
223 // create an uninitialized AudioRecord object
224 Parcel* parcel = parcelForJavaObject(env, jAttributionSource);
225 android::content::AttributionSourceState attributionSource;
226 attributionSource.readFromParcel(parcel);
227
228 lpRecorder = new AudioRecord(attributionSource);
229
230 // read the AudioAttributes values
231 auto paa = JNIAudioAttributeHelper::makeUnique();
232 jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
233 if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
234 return jStatus;
235 }
236 ALOGV("AudioRecord_setup for source=%d tags=%s flags=%08x", paa->source, paa->tags, paa->flags);
237
238 audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE;
239 if (paa->flags & AUDIO_FLAG_HW_HOTWORD) {
240 flags = AUDIO_INPUT_FLAG_HW_HOTWORD;
241 }
242 // create the callback information:
243 // this data will be passed with every AudioRecord callback
244 // we use a weak reference so the AudioRecord object can be garbage collected.
245 callbackData = sp<AudioRecordJNIStorage>::make(clazz, weak_this);
246
247 const status_t status =
248 lpRecorder->set(paa->source, sampleRateInHertz,
249 format, // word length, PCM
250 localChanMask, frameCount,
251 callbackData, // callback
252 0, // notificationFrames,
253 true, // threadCanCallJava
254 sessionId, AudioRecord::TRANSFER_DEFAULT, flags, -1,
255 -1, // default uid, pid
256 paa.get(), AUDIO_PORT_HANDLE_NONE, MIC_DIRECTION_UNSPECIFIED,
257 MIC_FIELD_DIMENSION_DEFAULT, sharedAudioHistoryMs);
258
259 if (status != NO_ERROR) {
260 ALOGE("Error creating AudioRecord instance: initialization check failed with status %d.",
261 status);
262 goto native_init_failure;
263 }
264 // Set caller name so it can be logged in destructor.
265 // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_JAVA
266 lpRecorder->setCallerName("java");
267 } else { // end if nativeRecordInJavaObj == 0)
268 lpRecorder = (AudioRecord*)nativeRecordInJavaObj;
269 // TODO: We need to find out which members of the Java AudioRecord might need to be
270 // initialized from the Native AudioRecord
271 // these are directly returned from getters:
272 // mSampleRate
273 // mRecordSource
274 // mAudioFormat
275 // mChannelMask
276 // mChannelCount
277 // mState (?)
278 // mRecordingState (?)
279 // mPreferredDevice
280
281 // create the callback information:
282 // this data will be passed with every AudioRecord callback
283 // This next line makes little sense
284 // callbackData = sp<AudioRecordJNIStorage>::make(clazz, weak_this);
285 }
286
287 nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL);
288 if (nSession == NULL) {
289 ALOGE("Error creating AudioRecord: Error retrieving session id pointer");
290 goto native_init_failure;
291 }
292 // read the audio session ID back from AudioRecord in case a new session was created during set()
293 nSession[0] = lpRecorder->getSessionId();
294 env->ReleasePrimitiveArrayCritical(jSession, nSession, 0);
295 nSession = NULL;
296
297 {
298 const jint elements[1] = { (jint) lpRecorder->getSampleRate() };
299 env->SetIntArrayRegion(jSampleRate, 0, 1, elements);
300 }
301
302 // save our newly created C++ AudioRecord in the "nativeRecorderInJavaObj" field
303 // of the Java object
304 setFieldSp(env, thiz, lpRecorder, javaAudioRecordFields.nativeRecorderInJavaObj);
305
306 // save our newly created callback information in the "jniData" field
307 // of the Java object (in mNativeJNIDataHandle) so we can free the memory in finalize()
308 setFieldSp(env, thiz, callbackData, javaAudioRecordFields.jniData);
309
310 return (jint) AUDIO_JAVA_SUCCESS;
311
312 // failure:
313 native_init_failure:
314 setFieldSp(env, thiz, sp<AudioRecord>{}, javaAudioRecordFields.nativeRecorderInJavaObj);
315 setFieldSp(env, thiz, sp<AudioRecordJNIStorage>{}, javaAudioRecordFields.jniData);
316
317 // lpRecorder goes out of scope, so reference count drops to zero
318 return (jint) AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED;
319 }
320
321 // ----------------------------------------------------------------------------
322 static jint
323 android_media_AudioRecord_start(JNIEnv *env, jobject thiz, jint event, jint triggerSession)
324 {
325 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
326 if (lpRecorder == NULL ) {
327 jniThrowException(env, "java/lang/IllegalStateException", NULL);
328 return (jint) AUDIO_JAVA_ERROR;
329 }
330
331 return nativeToJavaStatus(
332 lpRecorder->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
333 }
334
335
336 // ----------------------------------------------------------------------------
337 static void
338 android_media_AudioRecord_stop(JNIEnv *env, jobject thiz)
339 {
340 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
341 if (lpRecorder == NULL ) {
342 jniThrowException(env, "java/lang/IllegalStateException", NULL);
343 return;
344 }
345
346 lpRecorder->stop();
347 //ALOGV("Called lpRecorder->stop()");
348 }
349
350
351 // ----------------------------------------------------------------------------
352
353 #define CALLBACK_COND_WAIT_TIMEOUT_MS 1000
354 static void android_media_AudioRecord_release(JNIEnv *env, jobject thiz) {
355
356 setFieldSp(env, thiz, sp<AudioRecord>{}, javaAudioRecordFields.nativeRecorderInJavaObj);
357 setFieldSp(env, thiz, sp<AudioRecordJNIStorage>{}, javaAudioRecordFields.jniData);
358 }
359
360
361 // ----------------------------------------------------------------------------
362 static void android_media_AudioRecord_finalize(JNIEnv *env, jobject thiz) {
363 android_media_AudioRecord_release(env, thiz);
364 }
365
366 // overloaded JNI array helper functions
367 static inline
368 jbyte *envGetArrayElements(JNIEnv *env, jbyteArray array, jboolean *isCopy) {
369 return env->GetByteArrayElements(array, isCopy);
370 }
371
372 static inline
373 void envReleaseArrayElements(JNIEnv *env, jbyteArray array, jbyte *elems, jint mode) {
374 env->ReleaseByteArrayElements(array, elems, mode);
375 }
376
377 static inline
378 jshort *envGetArrayElements(JNIEnv *env, jshortArray array, jboolean *isCopy) {
379 return env->GetShortArrayElements(array, isCopy);
380 }
381
382 static inline
383 void envReleaseArrayElements(JNIEnv *env, jshortArray array, jshort *elems, jint mode) {
384 env->ReleaseShortArrayElements(array, elems, mode);
385 }
386
387 static inline
388 jfloat *envGetArrayElements(JNIEnv *env, jfloatArray array, jboolean *isCopy) {
389 return env->GetFloatArrayElements(array, isCopy);
390 }
391
392 static inline
393 void envReleaseArrayElements(JNIEnv *env, jfloatArray array, jfloat *elems, jint mode) {
394 env->ReleaseFloatArrayElements(array, elems, mode);
395 }
396
397 static inline
398 jint interpretReadSizeError(ssize_t readSize) {
399 if (readSize == WOULD_BLOCK) {
400 return (jint)0;
401 } else if (readSize == NO_INIT) {
402 return AUDIO_JAVA_DEAD_OBJECT;
403 } else {
404 ALOGE("Error %zd during AudioRecord native read", readSize);
405 return nativeToJavaStatus(readSize);
406 }
407 }
408
409 template <typename T>
410 static jint android_media_AudioRecord_readInArray(JNIEnv *env, jobject thiz,
411 T javaAudioData,
412 jint offsetInSamples, jint sizeInSamples,
413 jboolean isReadBlocking) {
414 // get the audio recorder from which we'll read new audio samples
415 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
416 if (lpRecorder == NULL) {
417 ALOGE("Unable to retrieve AudioRecord object");
418 return (jint)AUDIO_JAVA_INVALID_OPERATION;
419 }
420
421 if (javaAudioData == NULL) {
422 ALOGE("Invalid Java array to store recorded audio");
423 return (jint)AUDIO_JAVA_BAD_VALUE;
424 }
425
426 // NOTE: We may use GetPrimitiveArrayCritical() when the JNI implementation changes in such
427 // a way that it becomes much more efficient. When doing so, we will have to prevent the
428 // AudioSystem callback to be called while in critical section (in case of media server
429 // process crash for instance)
430
431 // get the pointer to where we'll record the audio
432 auto *recordBuff = envGetArrayElements(env, javaAudioData, NULL);
433 if (recordBuff == NULL) {
434 ALOGE("Error retrieving destination for recorded audio data");
435 return (jint)AUDIO_JAVA_BAD_VALUE;
436 }
437
438 // read the new audio data from the native AudioRecord object
439 const size_t sizeInBytes = sizeInSamples * sizeof(*recordBuff);
440 ssize_t readSize = lpRecorder->read(
441 recordBuff + offsetInSamples, sizeInBytes, isReadBlocking == JNI_TRUE /* blocking */);
442
443 envReleaseArrayElements(env, javaAudioData, recordBuff, 0);
444
445 if (readSize < 0) {
446 return interpretReadSizeError(readSize);
447 }
448 return (jint)(readSize / sizeof(*recordBuff));
449 }
450
451 // ----------------------------------------------------------------------------
452 static jint android_media_AudioRecord_readInDirectBuffer(JNIEnv *env, jobject thiz,
453 jobject jBuffer, jint sizeInBytes,
454 jboolean isReadBlocking) {
455 // get the audio recorder from which we'll read new audio samples
456 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
457 if (lpRecorder==NULL)
458 return (jint)AUDIO_JAVA_INVALID_OPERATION;
459
460 // direct buffer and direct access supported?
461 long capacity = env->GetDirectBufferCapacity(jBuffer);
462 if (capacity == -1) {
463 // buffer direct access is not supported
464 ALOGE("Buffer direct access is not supported, can't record");
465 return (jint)AUDIO_JAVA_BAD_VALUE;
466 }
467 //ALOGV("capacity = %ld", capacity);
468 jbyte* nativeFromJavaBuf = (jbyte*) env->GetDirectBufferAddress(jBuffer);
469 if (nativeFromJavaBuf==NULL) {
470 ALOGE("Buffer direct access is not supported, can't record");
471 return (jint)AUDIO_JAVA_BAD_VALUE;
472 }
473
474 // read new data from the recorder
475 ssize_t readSize = lpRecorder->read(nativeFromJavaBuf,
476 capacity < sizeInBytes ? capacity : sizeInBytes,
477 isReadBlocking == JNI_TRUE /* blocking */);
478 if (readSize < 0) {
479 return interpretReadSizeError(readSize);
480 }
481 return (jint)readSize;
482 }
483
484 // ----------------------------------------------------------------------------
485 static jint android_media_AudioRecord_get_buffer_size_in_frames(JNIEnv *env, jobject thiz) {
486 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
487 if (lpRecorder == NULL) {
488 jniThrowException(env, "java/lang/IllegalStateException",
489 "Unable to retrieve AudioRecord pointer for frameCount()");
490 return (jint)AUDIO_JAVA_ERROR;
491 }
492 return lpRecorder->frameCount();
493 }
494
495 // ----------------------------------------------------------------------------
496 static jint android_media_AudioRecord_set_marker_pos(JNIEnv *env, jobject thiz,
497 jint markerPos) {
498
499 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
500 if (lpRecorder == NULL) {
501 jniThrowException(env, "java/lang/IllegalStateException",
502 "Unable to retrieve AudioRecord pointer for setMarkerPosition()");
503 return (jint)AUDIO_JAVA_ERROR;
504 }
505 return nativeToJavaStatus( lpRecorder->setMarkerPosition(markerPos) );
506 }
507
508
509 // ----------------------------------------------------------------------------
510 static jint android_media_AudioRecord_get_marker_pos(JNIEnv *env, jobject thiz) {
511
512 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
513 uint32_t markerPos = 0;
514
515 if (lpRecorder == NULL) {
516 jniThrowException(env, "java/lang/IllegalStateException",
517 "Unable to retrieve AudioRecord pointer for getMarkerPosition()");
518 return (jint)AUDIO_JAVA_ERROR;
519 }
520 lpRecorder->getMarkerPosition(&markerPos);
521 return (jint)markerPos;
522 }
523
524
525 // ----------------------------------------------------------------------------
526 static jint android_media_AudioRecord_set_pos_update_period(JNIEnv *env, jobject thiz,
527 jint period) {
528
529 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
530
531 if (lpRecorder == NULL) {
532 jniThrowException(env, "java/lang/IllegalStateException",
533 "Unable to retrieve AudioRecord pointer for setPositionUpdatePeriod()");
534 return (jint)AUDIO_JAVA_ERROR;
535 }
536 return nativeToJavaStatus( lpRecorder->setPositionUpdatePeriod(period) );
537 }
538
539
540 // ----------------------------------------------------------------------------
541 static jint android_media_AudioRecord_get_pos_update_period(JNIEnv *env, jobject thiz) {
542
543 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
544 uint32_t period = 0;
545
546 if (lpRecorder == NULL) {
547 jniThrowException(env, "java/lang/IllegalStateException",
548 "Unable to retrieve AudioRecord pointer for getPositionUpdatePeriod()");
549 return (jint)AUDIO_JAVA_ERROR;
550 }
551 lpRecorder->getPositionUpdatePeriod(&period);
552 return (jint)period;
553 }
554
555
556 // ----------------------------------------------------------------------------
557 // returns the minimum required size for the successful creation of an AudioRecord instance.
558 // returns 0 if the parameter combination is not supported.
559 // return -1 if there was an error querying the buffer size.
560 static jint android_media_AudioRecord_get_min_buff_size(JNIEnv *env, jobject thiz,
561 jint sampleRateInHertz, jint channelCount, jint audioFormat) {
562
563 ALOGV(">> android_media_AudioRecord_get_min_buff_size(%d, %d, %d)",
564 sampleRateInHertz, channelCount, audioFormat);
565
566 size_t frameCount = 0;
567 audio_format_t format = audioFormatToNative(audioFormat);
568 status_t result = AudioRecord::getMinFrameCount(&frameCount,
569 sampleRateInHertz,
570 format,
571 audio_channel_in_mask_from_count(channelCount));
572
573 if (result == BAD_VALUE) {
574 return 0;
575 }
576 if (result != NO_ERROR) {
577 return -1;
578 }
579 return frameCount * channelCount * audio_bytes_per_sample(format);
580 }
581
582 static jboolean android_media_AudioRecord_setInputDevice(
583 JNIEnv *env, jobject thiz, jint device_id) {
584
585 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
586 if (lpRecorder == 0) {
587 return false;
588 }
589 return lpRecorder->setInputDevice(device_id) == NO_ERROR;
590 }
591
592 static jint android_media_AudioRecord_getRoutedDeviceId(
593 JNIEnv *env, jobject thiz) {
594
595 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
596 if (lpRecorder == 0) {
597 return 0;
598 }
599 return (jint)lpRecorder->getRoutedDeviceId();
600 }
601
602 // Enable and Disable Callback methods are synchronized on the Java side
603 static void android_media_AudioRecord_enableDeviceCallback(
604 JNIEnv *env, jobject thiz) {
605
606 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
607 if (lpRecorder == nullptr) {
608 return;
609 }
610 const auto pJniStorage =
611 getFieldSp<AudioRecordJNIStorage>(env, thiz, javaAudioRecordFields.jniData);
612 if (pJniStorage == nullptr || pJniStorage->getDeviceCallback() != nullptr) {
613 return;
614 }
615
616 pJniStorage->setDeviceCallback(
617 sp<JNIDeviceCallback>::make(env, thiz, pJniStorage->getAudioTrackWeakRef(),
618 javaAudioRecordFields.postNativeEventInJava));
619 lpRecorder->addAudioDeviceCallback(pJniStorage->getDeviceCallback());
620 }
621
622 static void android_media_AudioRecord_disableDeviceCallback(
623 JNIEnv *env, jobject thiz) {
624 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
625 if (lpRecorder == nullptr) {
626 return;
627 }
628 const auto pJniStorage =
629 getFieldSp<AudioRecordJNIStorage>(env, thiz, javaAudioRecordFields.jniData);
630
631 if (pJniStorage == nullptr || pJniStorage->getDeviceCallback() == nullptr) {
632 return;
633 }
634 lpRecorder->removeAudioDeviceCallback(pJniStorage->getDeviceCallback());
635 pJniStorage->setDeviceCallback(nullptr);
636 }
637
638 // ----------------------------------------------------------------------------
639 static jint android_media_AudioRecord_get_timestamp(JNIEnv *env, jobject thiz,
640 jobject timestamp, jint timebase) {
641 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
642
643 if (lpRecorder == NULL) {
644 jniThrowException(env, "java/lang/IllegalStateException",
645 "Unable to retrieve AudioRecord pointer for getTimestamp()");
646 return (jint)AUDIO_JAVA_ERROR;
647 }
648
649 ExtendedTimestamp ts;
650 jint status = nativeToJavaStatus(lpRecorder->getTimestamp(&ts));
651
652 if (status == AUDIO_JAVA_SUCCESS) {
653 // set the data
654 int64_t position, time;
655
656 status = nativeToJavaStatus(ts.getBestTimestamp(&position, &time, timebase));
657 if (status == AUDIO_JAVA_SUCCESS) {
658 env->SetLongField(
659 timestamp, javaAudioTimestampFields.fieldFramePosition, position);
660 env->SetLongField(
661 timestamp, javaAudioTimestampFields.fieldNanoTime, time);
662 }
663 }
664 return status;
665 }
666
667 // ----------------------------------------------------------------------------
668 static jobject
669 android_media_AudioRecord_native_getMetrics(JNIEnv *env, jobject thiz)
670 {
671 ALOGV("android_media_AudioRecord_native_getMetrics");
672
673 sp<AudioRecord> lpRecord = getAudioRecord(env, thiz);
674
675 if (lpRecord == NULL) {
676 ALOGE("Unable to retrieve AudioRecord pointer for getMetrics()");
677 jniThrowException(env, "java/lang/IllegalStateException", NULL);
678 return (jobject) NULL;
679 }
680
681 // get what we have for the metrics from the record session
682 mediametrics::Item *item = NULL;
683
684 status_t err = lpRecord->getMetrics(item);
685 if (err != OK) {
686 ALOGE("getMetrics failed");
687 jniThrowException(env, "java/lang/IllegalStateException", NULL);
688 return (jobject) NULL;
689 }
690
691 jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item, NULL /* mybundle */);
692
693 // housekeeping
694 delete item;
695 item = NULL;
696
697 return mybundle;
698 }
699
700 // ----------------------------------------------------------------------------
701 static jint android_media_AudioRecord_get_active_microphones(JNIEnv *env,
702 jobject thiz, jobject jActiveMicrophones) {
703 if (jActiveMicrophones == NULL) {
704 ALOGE("jActiveMicrophones is null");
705 return (jint)AUDIO_JAVA_BAD_VALUE;
706 }
707 if (!env->IsInstanceOf(jActiveMicrophones, gArrayListClass)) {
708 ALOGE("getActiveMicrophones not an arraylist");
709 return (jint)AUDIO_JAVA_BAD_VALUE;
710 }
711
712 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
713 if (lpRecorder == NULL) {
714 jniThrowException(env, "java/lang/IllegalStateException",
715 "Unable to retrieve AudioRecord pointer for getActiveMicrophones()");
716 return (jint)AUDIO_JAVA_ERROR;
717 }
718
719 jint jStatus = AUDIO_JAVA_SUCCESS;
720 std::vector<media::MicrophoneInfoFw> activeMicrophones;
721 status_t status = lpRecorder->getActiveMicrophones(&activeMicrophones);
722 if (status != NO_ERROR) {
723 ALOGE_IF(status != NO_ERROR, "AudioRecord::getActiveMicrophones error %d", status);
724 jStatus = nativeToJavaStatus(status);
725 return jStatus;
726 }
727
728 for (size_t i = 0; i < activeMicrophones.size(); i++) {
729 jobject jMicrophoneInfo;
730 jStatus = convertMicrophoneInfoFromNative(env, &jMicrophoneInfo, &activeMicrophones[i]);
731 if (jStatus != AUDIO_JAVA_SUCCESS) {
732 return jStatus;
733 }
734 env->CallBooleanMethod(jActiveMicrophones, gArrayListMethods.add, jMicrophoneInfo);
735 env->DeleteLocalRef(jMicrophoneInfo);
736 }
737 return jStatus;
738 }
739
740 static int android_media_AudioRecord_set_preferred_microphone_direction(
741 JNIEnv *env, jobject thiz, jint direction) {
742 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
743 if (lpRecorder == NULL) {
744 jniThrowException(env, "java/lang/IllegalStateException",
745 "Unable to retrieve AudioRecord pointer for setPreferredMicrophoneDirection()");
746 return (jint)AUDIO_JAVA_ERROR;
747 }
748
749 jint jStatus = AUDIO_JAVA_SUCCESS;
750 status_t status = lpRecorder->setPreferredMicrophoneDirection(
751 static_cast<audio_microphone_direction_t>(direction));
752 if (status != NO_ERROR) {
753 jStatus = nativeToJavaStatus(status);
754 }
755
756 return jStatus;
757 }
758
759 static int android_media_AudioRecord_set_preferred_microphone_field_dimension(
760 JNIEnv *env, jobject thiz, jfloat zoom) {
761 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
762 if (lpRecorder == NULL) {
763 jniThrowException(env, "java/lang/IllegalStateException",
764 "Unable to retrieve AudioRecord pointer for setPreferredMicrophoneFieldDimension()");
765 return (jint)AUDIO_JAVA_ERROR;
766 }
767
768 jint jStatus = AUDIO_JAVA_SUCCESS;
769 status_t status = lpRecorder->setPreferredMicrophoneFieldDimension(zoom);
770 if (status != NO_ERROR) {
771 jStatus = nativeToJavaStatus(status);
772 }
773
774 return jStatus;
775 }
776
777 static void android_media_AudioRecord_setLogSessionId(JNIEnv *env, jobject thiz,
778 jstring jlogSessionId) {
779 sp<AudioRecord> record = getAudioRecord(env, thiz);
780 if (record == nullptr) {
781 jniThrowException(env, "java/lang/IllegalStateException",
782 "Unable to retrieve AudioRecord pointer for setLogSessionId()");
783 }
784 if (jlogSessionId == nullptr) {
785 ALOGV("%s: logSessionId nullptr", __func__);
786 record->setLogSessionId(nullptr);
787 return;
788 }
789 ScopedUtfChars logSessionId(env, jlogSessionId);
790 ALOGV("%s: logSessionId '%s'", __func__, logSessionId.c_str());
791 record->setLogSessionId(logSessionId.c_str());
792 }
793
794 static jint android_media_AudioRecord_shareAudioHistory(JNIEnv *env, jobject thiz,
795 jstring jSharedPackageName,
796 jlong jSharedStartMs) {
797 sp<AudioRecord> record = getAudioRecord(env, thiz);
798 if (record == nullptr) {
799 jniThrowException(env, "java/lang/IllegalStateException",
800 "Unable to retrieve AudioRecord pointer for setLogSessionId()");
801 }
802 if (jSharedPackageName == nullptr) {
803 jniThrowException(env, "java/lang/IllegalArgumentException", "package name cannot be null");
804 }
805 ScopedUtfChars nSharedPackageName(env, jSharedPackageName);
806 ALOGV("%s: nSharedPackageName '%s'", __func__, nSharedPackageName.c_str());
807 return nativeToJavaStatus(record->shareAudioHistory(nSharedPackageName.c_str(),
808 static_cast<int64_t>(jSharedStartMs)));
809 }
810
811 // ----------------------------------------------------------------------------
812 static jint android_media_AudioRecord_get_port_id(JNIEnv *env, jobject thiz) {
813 sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
814 if (lpRecorder == NULL) {
815 jniThrowException(env, "java/lang/IllegalStateException",
816 "Unable to retrieve AudioRecord pointer for getId()");
817 return (jint)AUDIO_PORT_HANDLE_NONE;
818 }
819 return (jint)lpRecorder->getPortId();
820 }
821
822
823 // ----------------------------------------------------------------------------
824 // ----------------------------------------------------------------------------
825 static const JNINativeMethod gMethods[] = {
826 // name, signature, funcPtr
827 {"native_start", "(II)I", (void *)android_media_AudioRecord_start},
828 {"native_stop", "()V", (void *)android_media_AudioRecord_stop},
829 {"native_setup",
830 "(Ljava/lang/Object;Ljava/lang/Object;[IIIII[ILandroid/os/Parcel;JI)I",
831 (void *)android_media_AudioRecord_setup},
832 {"native_finalize", "()V", (void *)android_media_AudioRecord_finalize},
833 {"native_release", "()V", (void *)android_media_AudioRecord_release},
834 {"native_read_in_byte_array", "([BIIZ)I",
835 (void *)android_media_AudioRecord_readInArray<jbyteArray>},
836 {"native_read_in_short_array", "([SIIZ)I",
837 (void *)android_media_AudioRecord_readInArray<jshortArray>},
838 {"native_read_in_float_array", "([FIIZ)I",
839 (void *)android_media_AudioRecord_readInArray<jfloatArray>},
840 {"native_read_in_direct_buffer", "(Ljava/lang/Object;IZ)I",
841 (void *)android_media_AudioRecord_readInDirectBuffer},
842 {"native_get_buffer_size_in_frames", "()I",
843 (void *)android_media_AudioRecord_get_buffer_size_in_frames},
844 {"native_set_marker_pos", "(I)I", (void *)android_media_AudioRecord_set_marker_pos},
845 {"native_get_marker_pos", "()I", (void *)android_media_AudioRecord_get_marker_pos},
846 {"native_set_pos_update_period", "(I)I",
847 (void *)android_media_AudioRecord_set_pos_update_period},
848 {"native_get_pos_update_period", "()I",
849 (void *)android_media_AudioRecord_get_pos_update_period},
850 {"native_get_min_buff_size", "(III)I", (void *)android_media_AudioRecord_get_min_buff_size},
851 {"native_getMetrics", "()Landroid/os/PersistableBundle;",
852 (void *)android_media_AudioRecord_native_getMetrics},
853 {"native_setInputDevice", "(I)Z", (void *)android_media_AudioRecord_setInputDevice},
854 {"native_getRoutedDeviceId", "()I", (void *)android_media_AudioRecord_getRoutedDeviceId},
855 {"native_enableDeviceCallback", "()V",
856 (void *)android_media_AudioRecord_enableDeviceCallback},
857 {"native_disableDeviceCallback", "()V",
858 (void *)android_media_AudioRecord_disableDeviceCallback},
859 {"native_get_timestamp", "(Landroid/media/AudioTimestamp;I)I",
860 (void *)android_media_AudioRecord_get_timestamp},
861 {"native_get_active_microphones", "(Ljava/util/ArrayList;)I",
862 (void *)android_media_AudioRecord_get_active_microphones},
863 {"native_getPortId", "()I", (void *)android_media_AudioRecord_get_port_id},
864 {"native_set_preferred_microphone_direction", "(I)I",
865 (void *)android_media_AudioRecord_set_preferred_microphone_direction},
866 {"native_set_preferred_microphone_field_dimension", "(F)I",
867 (void *)android_media_AudioRecord_set_preferred_microphone_field_dimension},
868 {"native_setLogSessionId", "(Ljava/lang/String;)V",
869 (void *)android_media_AudioRecord_setLogSessionId},
870 {"native_shareAudioHistory", "(Ljava/lang/String;J)I",
871 (void *)android_media_AudioRecord_shareAudioHistory},
872 };
873
874 // field names found in android/media/AudioRecord.java
875 #define JAVA_POSTEVENT_CALLBACK_NAME "postEventFromNative"
876 #define JAVA_NATIVEAUDIORECORDERHANDLE_FIELD_NAME "mNativeAudioRecordHandle"
877 #define JAVA_NATIVEJNIDATAHANDLE_FIELD_NAME "mNativeJNIDataHandle"
878
879 // ----------------------------------------------------------------------------
880 int register_android_media_AudioRecord(JNIEnv *env)
881 {
882 javaAudioRecordFields.postNativeEventInJava = NULL;
883 javaAudioRecordFields.nativeRecorderInJavaObj = NULL;
884 javaAudioRecordFields.jniData = NULL;
885
886
887 // Get the AudioRecord class
888 jclass audioRecordClass = FindClassOrDie(env, kClassPathName);
889 // Get the postEvent method
890 javaAudioRecordFields.postNativeEventInJava = GetStaticMethodIDOrDie(env,
891 audioRecordClass, JAVA_POSTEVENT_CALLBACK_NAME,
892 "(Ljava/lang/Object;IIILjava/lang/Object;)V");
893
894 // Get the variables
895 // mNativeAudioRecordHandle
896 javaAudioRecordFields.nativeRecorderInJavaObj = GetFieldIDOrDie(env,
897 audioRecordClass, JAVA_NATIVEAUDIORECORDERHANDLE_FIELD_NAME, "J");
898 // mNativeJNIDataHandle
899 javaAudioRecordFields.jniData = GetFieldIDOrDie(env,
900 audioRecordClass, JAVA_NATIVEJNIDATAHANDLE_FIELD_NAME, "J");
901
902 // Get the RecordTimestamp class and fields
903 jclass audioTimestampClass = FindClassOrDie(env, "android/media/AudioTimestamp");
904 javaAudioTimestampFields.fieldFramePosition =
905 GetFieldIDOrDie(env, audioTimestampClass, "framePosition", "J");
906 javaAudioTimestampFields.fieldNanoTime =
907 GetFieldIDOrDie(env, audioTimestampClass, "nanoTime", "J");
908
909 jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
910 gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
911 gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
912
913 return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
914 }
915
916 // ----------------------------------------------------------------------------