AudioRecord.java revision ee88bc8ab90696a9e479cf185ec2b8c2be0b7258
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
17package android.media;
18
19import java.lang.ref.WeakReference;
20import java.lang.IllegalArgumentException;
21import java.lang.IllegalStateException;
22import java.nio.ByteBuffer;
23
24import android.os.Handler;
25import android.os.Looper;
26import android.os.Message;
27import android.util.Log;
28
29/**
30 * The AudioRecord class manages the audio resources for Java applications
31 * to record audio from the audio input hardware of the platform. This is
32 * achieved by "pulling" (reading) the data from the AudioRecord object. The
33 * application is responsible for polling the AudioRecord object in time using one of
34 * the following three methods:  {@link #read(byte[],int, int)}, {@link #read(short[], int, int)}
35 * or {@link #read(ByteBuffer, int)}. The choice of which method to use will be based
36 * on the audio data storage format that is the most convenient for the user of AudioRecord.
37 * <p>Upon creation, an AudioRecord object initializes its associated audio buffer that it will
38 * fill with the new audio data. The size of this buffer, specified during the construction,
39 * determines how long an AudioRecord can record before "over-running" data that has not
40 * been read yet. Data should be read from the audio hardware in chunks of sizes inferior to
41 * the total recording buffer size.
42 */
43public class AudioRecord
44{
45    //---------------------------------------------------------
46    // Constants
47    //--------------------
48    /**
49     *  indicates AudioRecord state is not successfully initialized.
50     */
51    public static final int STATE_UNINITIALIZED = 0;
52    /**
53     *  indicates AudioRecord state is ready to be used
54     */
55    public static final int STATE_INITIALIZED   = 1;
56
57    /**
58     * indicates AudioRecord recording state is not recording
59     */
60    public static final int RECORDSTATE_STOPPED = 1;  // matches SL_RECORDSTATE_STOPPED
61    /**
62     * indicates AudioRecord recording state is recording
63     */
64    public static final int RECORDSTATE_RECORDING = 3;// matches SL_RECORDSTATE_RECORDING
65
66    // Error codes:
67    // to keep in sync with frameworks/base/core/jni/android_media_AudioRecord.cpp
68    /**
69     * Denotes a successful operation.
70     */
71    public static final int SUCCESS                 = 0;
72    /**
73     * Denotes a generic operation failure.
74     */
75    public static final int ERROR                   = -1;
76    /**
77     * Denotes a failure due to the use of an invalid value.
78     */
79    public static final int ERROR_BAD_VALUE         = -2;
80    /**
81     * Denotes a failure due to the improper use of a method.
82     */
83    public static final int ERROR_INVALID_OPERATION = -3;
84
85    private static final int AUDIORECORD_ERROR_SETUP_ZEROFRAMECOUNT      = -16;
86    private static final int AUDIORECORD_ERROR_SETUP_INVALIDCHANNELMASK  = -17;
87    private static final int AUDIORECORD_ERROR_SETUP_INVALIDFORMAT       = -18;
88    private static final int AUDIORECORD_ERROR_SETUP_INVALIDSOURCE       = -19;
89    private static final int AUDIORECORD_ERROR_SETUP_NATIVEINITFAILED    = -20;
90
91    // Events:
92    // to keep in sync with frameworks/base/include/media/AudioRecord.h
93    /**
94     * Event id denotes when record head has reached a previously set marker.
95     */
96    private static final int NATIVE_EVENT_MARKER  = 2;
97    /**
98     * Event id denotes when previously set update period has elapsed during recording.
99     */
100    private static final int NATIVE_EVENT_NEW_POS = 3;
101
102    private final static String TAG = "AudioRecord-Java";
103
104
105    //---------------------------------------------------------
106    // Used exclusively by native code
107    //--------------------
108    /**
109     * Accessed by native methods: provides access to C++ AudioRecord object
110     */
111    @SuppressWarnings("unused")
112    private int mNativeRecorderInJavaObj;
113
114    /**
115     * Accessed by native methods: provides access to the callback data.
116     */
117    @SuppressWarnings("unused")
118    private int mNativeCallbackCookie;
119
120
121    //---------------------------------------------------------
122    // Member variables
123    //--------------------
124    /**
125     * The audio data sampling rate in Hz.
126     */
127    private int mSampleRate = 22050;
128    /**
129     * The number of input audio channels (1 is mono, 2 is stereo)
130     */
131    private int mChannelCount = 1;
132    /**
133     * The audio channel mask
134     */
135    private int mChannels = AudioFormat.CHANNEL_IN_MONO;
136    /**
137     * The current audio channel configuration
138     */
139    private int mChannelConfiguration = AudioFormat.CHANNEL_IN_MONO;
140    /**
141     * The encoding of the audio samples.
142     * @see AudioFormat#ENCODING_PCM_8BIT
143     * @see AudioFormat#ENCODING_PCM_16BIT
144     */
145    private int mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
146    /**
147     * Where the audio data is recorded from.
148     */
149    private int mRecordSource = MediaRecorder.AudioSource.DEFAULT;
150    /**
151     * Indicates the state of the AudioRecord instance.
152     */
153    private int mState = STATE_UNINITIALIZED;
154    /**
155     * Indicates the recording state of the AudioRecord instance.
156     */
157    private int mRecordingState = RECORDSTATE_STOPPED;
158    /**
159     * Lock to make sure mRecordingState updates are reflecting the actual state of the object.
160     */
161    private final Object mRecordingStateLock = new Object();
162    /**
163     * The listener the AudioRecord notifies when the record position reaches a marker
164     * or for periodic updates during the progression of the record head.
165     *  @see #setRecordPositionUpdateListener(OnRecordPositionUpdateListener)
166     *  @see #setRecordPositionUpdateListener(OnRecordPositionUpdateListener, Handler)
167     */
168    private OnRecordPositionUpdateListener mPositionListener = null;
169    /**
170     * Lock to protect position listener updates against event notifications
171     */
172    private final Object mPositionListenerLock = new Object();
173    /**
174     * Handler for marker events coming from the native code
175     */
176    private NativeEventHandler mEventHandler = null;
177    /**
178     * Looper associated with the thread that creates the AudioRecord instance
179     */
180    private Looper mInitializationLooper = null;
181    /**
182     * Size of the native audio buffer.
183     */
184    private int mNativeBufferSizeInBytes = 0;
185    /**
186     * Audio session ID
187     */
188    private int mSessionId = 0;
189
190    //---------------------------------------------------------
191    // Constructor, Finalize
192    //--------------------
193    /**
194     * Class constructor.
195     * @param audioSource the recording source. See {@link MediaRecorder.AudioSource} for
196     *    recording source definitions.
197     * @param sampleRateInHz the sample rate expressed in Hertz. 44100Hz is currently the only
198     *   rate that is guaranteed to work on all devices, but other rates such as 22050,
199     *   16000, and 11025 may work on some devices.
200     * @param channelConfig describes the configuration of the audio channels.
201     *   See {@link AudioFormat#CHANNEL_IN_MONO} and
202     *   {@link AudioFormat#CHANNEL_IN_STEREO}.  {@link AudioFormat#CHANNEL_IN_MONO} is guaranteed
203     *   to work on all devices.
204     * @param audioFormat the format in which the audio data is represented.
205     *   See {@link AudioFormat#ENCODING_PCM_16BIT} and
206     *   {@link AudioFormat#ENCODING_PCM_8BIT}
207     * @param bufferSizeInBytes the total size (in bytes) of the buffer where audio data is written
208     *   to during the recording. New audio data can be read from this buffer in smaller chunks
209     *   than this size. See {@link #getMinBufferSize(int, int, int)} to determine the minimum
210     *   required buffer size for the successful creation of an AudioRecord instance. Using values
211     *   smaller than getMinBufferSize() will result in an initialization failure.
212     * @throws java.lang.IllegalArgumentException
213     */
214    public AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat,
215            int bufferSizeInBytes)
216    throws IllegalArgumentException {
217        mState = STATE_UNINITIALIZED;
218        mRecordingState = RECORDSTATE_STOPPED;
219
220        // remember which looper is associated with the AudioRecord instanciation
221        if ((mInitializationLooper = Looper.myLooper()) == null) {
222            mInitializationLooper = Looper.getMainLooper();
223        }
224
225        audioParamCheck(audioSource, sampleRateInHz, channelConfig, audioFormat);
226
227        audioBuffSizeCheck(bufferSizeInBytes);
228
229        // native initialization
230        int[] session = new int[1];
231        session[0] = 0;
232        //TODO: update native initialization when information about hardware init failure
233        //      due to capture device already open is available.
234        int initResult = native_setup( new WeakReference<AudioRecord>(this),
235                mRecordSource, mSampleRate, mChannels, mAudioFormat, mNativeBufferSizeInBytes,
236                session);
237        if (initResult != SUCCESS) {
238            loge("Error code "+initResult+" when initializing native AudioRecord object.");
239            return; // with mState == STATE_UNINITIALIZED
240        }
241
242        mSessionId = session[0];
243
244        mState = STATE_INITIALIZED;
245    }
246
247
248    // Convenience method for the constructor's parameter checks.
249    // This is where constructor IllegalArgumentException-s are thrown
250    // postconditions:
251    //    mRecordSource is valid
252    //    mChannelCount is valid
253    //    mChannels is valid
254    //    mAudioFormat is valid
255    //    mSampleRate is valid
256    private void audioParamCheck(int audioSource, int sampleRateInHz,
257                                 int channelConfig, int audioFormat) {
258
259        //--------------
260        // audio source
261        if ( (audioSource < MediaRecorder.AudioSource.DEFAULT) ||
262             (audioSource > MediaRecorder.getAudioSourceMax()) )  {
263            throw (new IllegalArgumentException("Invalid audio source."));
264        } else {
265            mRecordSource = audioSource;
266        }
267
268        //--------------
269        // sample rate
270        if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) {
271            throw (new IllegalArgumentException(sampleRateInHz
272                    + "Hz is not a supported sample rate."));
273        } else {
274            mSampleRate = sampleRateInHz;
275        }
276
277        //--------------
278        // channel config
279        mChannelConfiguration = channelConfig;
280
281        switch (channelConfig) {
282        case AudioFormat.CHANNEL_IN_DEFAULT: // AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
283        case AudioFormat.CHANNEL_IN_MONO:
284        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
285            mChannelCount = 1;
286            mChannels = AudioFormat.CHANNEL_IN_MONO;
287            break;
288        case AudioFormat.CHANNEL_IN_STEREO:
289        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
290            mChannelCount = 2;
291            mChannels = AudioFormat.CHANNEL_IN_STEREO;
292            break;
293        default:
294            mChannelCount = 0;
295            mChannels = AudioFormat.CHANNEL_INVALID;
296            mChannelConfiguration = AudioFormat.CHANNEL_INVALID;
297            throw (new IllegalArgumentException("Unsupported channel configuration."));
298        }
299
300        //--------------
301        // audio format
302        switch (audioFormat) {
303        case AudioFormat.ENCODING_DEFAULT:
304            mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
305            break;
306        case AudioFormat.ENCODING_PCM_16BIT:
307        case AudioFormat.ENCODING_PCM_8BIT:
308            mAudioFormat = audioFormat;
309            break;
310        default:
311            mAudioFormat = AudioFormat.ENCODING_INVALID;
312        throw (new IllegalArgumentException("Unsupported sample encoding."
313                + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT."));
314        }
315    }
316
317
318    // Convenience method for the contructor's audio buffer size check.
319    // preconditions:
320    //    mChannelCount is valid
321    //    mAudioFormat is AudioFormat.ENCODING_PCM_8BIT OR AudioFormat.ENCODING_PCM_16BIT
322    // postcondition:
323    //    mNativeBufferSizeInBytes is valid (multiple of frame size, positive)
324    private void audioBuffSizeCheck(int audioBufferSize) {
325        // NB: this section is only valid with PCM data.
326        // To update when supporting compressed formats
327        int frameSizeInBytes = mChannelCount
328            * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2);
329        if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) {
330            throw (new IllegalArgumentException("Invalid audio buffer size."));
331        }
332
333        mNativeBufferSizeInBytes = audioBufferSize;
334    }
335
336
337
338    /**
339     * Releases the native AudioRecord resources.
340     * The object can no longer be used and the reference should be set to null
341     * after a call to release()
342     */
343    public void release() {
344        try {
345            stop();
346        } catch(IllegalStateException ise) {
347            // don't raise an exception, we're releasing the resources.
348        }
349        native_release();
350        mState = STATE_UNINITIALIZED;
351    }
352
353
354    @Override
355    protected void finalize() {
356        native_finalize();
357    }
358
359
360    //--------------------------------------------------------------------------
361    // Getters
362    //--------------------
363    /**
364     * Returns the configured audio data sample rate in Hz
365     */
366    public int getSampleRate() {
367        return mSampleRate;
368    }
369
370    /**
371     * Returns the audio recording source.
372     * @see MediaRecorder.AudioSource
373     */
374    public int getAudioSource() {
375        return mRecordSource;
376    }
377
378    /**
379     * Returns the configured audio data format. See {@link AudioFormat#ENCODING_PCM_16BIT}
380     * and {@link AudioFormat#ENCODING_PCM_8BIT}.
381     */
382    public int getAudioFormat() {
383        return mAudioFormat;
384    }
385
386    /**
387     * Returns the configured channel configuration.
388     * See {@link AudioFormat#CHANNEL_IN_MONO}
389     * and {@link AudioFormat#CHANNEL_IN_STEREO}.
390     */
391    public int getChannelConfiguration() {
392        return mChannelConfiguration;
393    }
394
395    /**
396     * Returns the configured number of channels.
397     */
398    public int getChannelCount() {
399        return mChannelCount;
400    }
401
402    /**
403     * Returns the state of the AudioRecord instance. This is useful after the
404     * AudioRecord instance has been created to check if it was initialized
405     * properly. This ensures that the appropriate hardware resources have been
406     * acquired.
407     * @see AudioRecord#STATE_INITIALIZED
408     * @see AudioRecord#STATE_UNINITIALIZED
409     */
410    public int getState() {
411        return mState;
412    }
413
414    /**
415     * Returns the recording state of the AudioRecord instance.
416     * @see AudioRecord#RECORDSTATE_STOPPED
417     * @see AudioRecord#RECORDSTATE_RECORDING
418     */
419    public int getRecordingState() {
420        return mRecordingState;
421    }
422
423    /**
424     * Returns the notification marker position expressed in frames.
425     */
426    public int getNotificationMarkerPosition() {
427        return native_get_marker_pos();
428    }
429
430    /**
431     * Returns the notification update period expressed in frames.
432     */
433    public int getPositionNotificationPeriod() {
434        return native_get_pos_update_period();
435    }
436
437    /**
438     * Returns the minimum buffer size required for the successful creation of an AudioRecord
439     * object.
440     * Note that this size doesn't guarantee a smooth recording under load, and higher values
441     * should be chosen according to the expected frequency at which the AudioRecord instance
442     * will be polled for new data.
443     * @param sampleRateInHz the sample rate expressed in Hertz.
444     * @param channelConfig describes the configuration of the audio channels.
445     *   See {@link AudioFormat#CHANNEL_IN_MONO} and
446     *   {@link AudioFormat#CHANNEL_IN_STEREO}
447     * @param audioFormat the format in which the audio data is represented.
448     *   See {@link AudioFormat#ENCODING_PCM_16BIT}.
449     * @return {@link #ERROR_BAD_VALUE} if the recording parameters are not supported by the
450     *  hardware, or an invalid parameter was passed,
451     *  or {@link #ERROR} if the implementation was unable to query the hardware for its
452     *  output properties,
453     *   or the minimum buffer size expressed in bytes.
454     * @see #AudioRecord(int, int, int, int, int) for more information on valid
455     *   configuration values.
456     */
457    static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) {
458        int channelCount = 0;
459        switch (channelConfig) {
460        case AudioFormat.CHANNEL_IN_DEFAULT: // AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
461        case AudioFormat.CHANNEL_IN_MONO:
462        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
463            channelCount = 1;
464            break;
465        case AudioFormat.CHANNEL_IN_STEREO:
466        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
467            channelCount = 2;
468            break;
469        case AudioFormat.CHANNEL_INVALID:
470        default:
471            loge("getMinBufferSize(): Invalid channel configuration.");
472            return AudioRecord.ERROR_BAD_VALUE;
473        }
474
475        // PCM_8BIT is not supported at the moment
476        if (audioFormat != AudioFormat.ENCODING_PCM_16BIT) {
477            loge("getMinBufferSize(): Invalid audio format.");
478            return AudioRecord.ERROR_BAD_VALUE;
479        }
480
481        int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat);
482        if (size == 0) {
483            return AudioRecord.ERROR_BAD_VALUE;
484        }
485        else if (size == -1) {
486            return AudioRecord.ERROR;
487        }
488        else {
489            return size;
490        }
491    }
492
493    /**
494     * Returns the audio session ID.
495     *
496     * @return the ID of the audio session this AudioRecord belongs to.
497     */
498    public int getAudioSessionId() {
499        return mSessionId;
500    }
501
502    //---------------------------------------------------------
503    // Transport control methods
504    //--------------------
505    /**
506     * Starts recording from the AudioRecord instance.
507     * @throws IllegalStateException
508     */
509    public void startRecording()
510    throws IllegalStateException {
511        if (mState != STATE_INITIALIZED) {
512            throw(new IllegalStateException("startRecording() called on an "
513                    +"uninitialized AudioRecord."));
514        }
515
516        // start recording
517        synchronized(mRecordingStateLock) {
518            if (native_start(MediaSyncEvent.SYNC_EVENT_NONE, 0) == SUCCESS) {
519                mRecordingState = RECORDSTATE_RECORDING;
520            }
521        }
522    }
523
524    /**
525     * Starts recording from the AudioRecord instance when the specified synchronization event
526     * occurs on the specified audio session.
527     * @throws IllegalStateException
528     * @param syncEvent event that triggers the capture.
529     * @see MediaSyncEvent
530     */
531    public void startRecording(MediaSyncEvent syncEvent)
532    throws IllegalStateException {
533        if (mState != STATE_INITIALIZED) {
534            throw(new IllegalStateException("startRecording() called on an "
535                    +"uninitialized AudioRecord."));
536        }
537
538        // start recording
539        synchronized(mRecordingStateLock) {
540            if (native_start(syncEvent.getType(), syncEvent.getAudioSessionId()) == SUCCESS) {
541                mRecordingState = RECORDSTATE_RECORDING;
542            }
543        }
544    }
545
546    /**
547     * Stops recording.
548     * @throws IllegalStateException
549     */
550    public void stop()
551    throws IllegalStateException {
552        if (mState != STATE_INITIALIZED) {
553            throw(new IllegalStateException("stop() called on an uninitialized AudioRecord."));
554        }
555
556        // stop recording
557        synchronized(mRecordingStateLock) {
558            native_stop();
559            mRecordingState = RECORDSTATE_STOPPED;
560        }
561    }
562
563
564    //---------------------------------------------------------
565    // Audio data supply
566    //--------------------
567    /**
568     * Reads audio data from the audio hardware for recording into a buffer.
569     * @param audioData the array to which the recorded audio data is written.
570     * @param offsetInBytes index in audioData from which the data is written expressed in bytes.
571     * @param sizeInBytes the number of requested bytes.
572     * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION}
573     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
574     *    the parameters don't resolve to valid data and indexes.
575     *    The number of bytes will not exceed sizeInBytes.
576     */
577    public int read(byte[] audioData, int offsetInBytes, int sizeInBytes) {
578        if (mState != STATE_INITIALIZED) {
579            return ERROR_INVALID_OPERATION;
580        }
581
582        if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0)
583                || (offsetInBytes + sizeInBytes > audioData.length)) {
584            return ERROR_BAD_VALUE;
585        }
586
587        return native_read_in_byte_array(audioData, offsetInBytes, sizeInBytes);
588    }
589
590
591    /**
592     * Reads audio data from the audio hardware for recording into a buffer.
593     * @param audioData the array to which the recorded audio data is written.
594     * @param offsetInShorts index in audioData from which the data is written expressed in shorts.
595     * @param sizeInShorts the number of requested shorts.
596     * @return the number of shorts that were read or or {@link #ERROR_INVALID_OPERATION}
597     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
598     *    the parameters don't resolve to valid data and indexes.
599     *    The number of shorts will not exceed sizeInShorts.
600     */
601    public int read(short[] audioData, int offsetInShorts, int sizeInShorts) {
602        if (mState != STATE_INITIALIZED) {
603            return ERROR_INVALID_OPERATION;
604        }
605
606        if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0)
607                || (offsetInShorts + sizeInShorts > audioData.length)) {
608            return ERROR_BAD_VALUE;
609        }
610
611        return native_read_in_short_array(audioData, offsetInShorts, sizeInShorts);
612    }
613
614
615    /**
616     * Reads audio data from the audio hardware for recording into a direct buffer. If this buffer
617     * is not a direct buffer, this method will always return 0.
618     * Note that the value returned by {@link java.nio.Buffer#position()} on this buffer is
619     * unchanged after a call to this method.
620     * @param audioBuffer the direct buffer to which the recorded audio data is written.
621     * @param sizeInBytes the number of requested bytes.
622     * @return the number of bytes that were read or or {@link #ERROR_INVALID_OPERATION}
623     *    if the object wasn't properly initialized, or {@link #ERROR_BAD_VALUE} if
624     *    the parameters don't resolve to valid data and indexes.
625     *    The number of bytes will not exceed sizeInBytes.
626     */
627    public int read(ByteBuffer audioBuffer, int sizeInBytes) {
628        if (mState != STATE_INITIALIZED) {
629            return ERROR_INVALID_OPERATION;
630        }
631
632        if ( (audioBuffer == null) || (sizeInBytes < 0) ) {
633            return ERROR_BAD_VALUE;
634        }
635
636        return native_read_in_direct_buffer(audioBuffer, sizeInBytes);
637    }
638
639
640    //--------------------------------------------------------------------------
641    // Initialization / configuration
642    //--------------------
643    /**
644     * Sets the listener the AudioRecord notifies when a previously set marker is reached or
645     * for each periodic record head position update.
646     * @param listener
647     */
648    public void setRecordPositionUpdateListener(OnRecordPositionUpdateListener listener) {
649        setRecordPositionUpdateListener(listener, null);
650    }
651
652    /**
653     * Sets the listener the AudioRecord notifies when a previously set marker is reached or
654     * for each periodic record head position update.
655     * Use this method to receive AudioRecord events in the Handler associated with another
656     * thread than the one in which you created the AudioTrack instance.
657     * @param listener
658     * @param handler the Handler that will receive the event notification messages.
659     */
660    public void setRecordPositionUpdateListener(OnRecordPositionUpdateListener listener,
661                                                    Handler handler) {
662        synchronized (mPositionListenerLock) {
663
664            mPositionListener = listener;
665
666            if (listener != null) {
667                if (handler != null) {
668                    mEventHandler = new NativeEventHandler(this, handler.getLooper());
669                } else {
670                    // no given handler, use the looper the AudioRecord was created in
671                    mEventHandler = new NativeEventHandler(this, mInitializationLooper);
672                }
673            } else {
674                mEventHandler = null;
675            }
676        }
677
678    }
679
680
681    /**
682     * Sets the marker position at which the listener is called, if set with
683     * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener)} or
684     * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener, Handler)}.
685     * @param markerInFrames marker position expressed in frames
686     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
687     *  {@link #ERROR_INVALID_OPERATION}
688     */
689    public int setNotificationMarkerPosition(int markerInFrames) {
690        return native_set_marker_pos(markerInFrames);
691    }
692
693
694    /**
695     * Sets the period at which the listener is called, if set with
696     * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener)} or
697     * {@link #setRecordPositionUpdateListener(OnRecordPositionUpdateListener, Handler)}.
698     * @param periodInFrames update period expressed in frames
699     * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION}
700     */
701    public int setPositionNotificationPeriod(int periodInFrames) {
702        return native_set_pos_update_period(periodInFrames);
703    }
704
705
706    //---------------------------------------------------------
707    // Interface definitions
708    //--------------------
709    /**
710     * Interface definition for a callback to be invoked when an AudioRecord has
711     * reached a notification marker set by {@link AudioRecord#setNotificationMarkerPosition(int)}
712     * or for periodic updates on the progress of the record head, as set by
713     * {@link AudioRecord#setPositionNotificationPeriod(int)}.
714     */
715    public interface OnRecordPositionUpdateListener  {
716        /**
717         * Called on the listener to notify it that the previously set marker has been reached
718         * by the recording head.
719         */
720        void onMarkerReached(AudioRecord recorder);
721
722        /**
723         * Called on the listener to periodically notify it that the record head has reached
724         * a multiple of the notification period.
725         */
726        void onPeriodicNotification(AudioRecord recorder);
727    }
728
729
730
731    //---------------------------------------------------------
732    // Inner classes
733    //--------------------
734
735    /**
736     * Helper class to handle the forwarding of native events to the appropriate listener
737     * (potentially) handled in a different thread
738     */
739    private class NativeEventHandler extends Handler {
740
741        private final AudioRecord mAudioRecord;
742
743        NativeEventHandler(AudioRecord recorder, Looper looper) {
744            super(looper);
745            mAudioRecord = recorder;
746        }
747
748        @Override
749        public void handleMessage(Message msg) {
750            OnRecordPositionUpdateListener listener = null;
751            synchronized (mPositionListenerLock) {
752                listener = mAudioRecord.mPositionListener;
753            }
754
755            switch (msg.what) {
756            case NATIVE_EVENT_MARKER:
757                if (listener != null) {
758                    listener.onMarkerReached(mAudioRecord);
759                }
760                break;
761            case NATIVE_EVENT_NEW_POS:
762                if (listener != null) {
763                    listener.onPeriodicNotification(mAudioRecord);
764                }
765                break;
766            default:
767                Log.e(TAG, "[ android.media.AudioRecord.NativeEventHandler ] " +
768                        "Unknown event type: " + msg.what);
769            break;
770            }
771        }
772    };
773
774
775    //---------------------------------------------------------
776    // Java methods called from the native side
777    //--------------------
778    @SuppressWarnings("unused")
779    private static void postEventFromNative(Object audiorecord_ref,
780            int what, int arg1, int arg2, Object obj) {
781        //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2);
782        AudioRecord recorder = (AudioRecord)((WeakReference)audiorecord_ref).get();
783        if (recorder == null) {
784            return;
785        }
786
787        if (recorder.mEventHandler != null) {
788            Message m =
789                recorder.mEventHandler.obtainMessage(what, arg1, arg2, obj);
790            recorder.mEventHandler.sendMessage(m);
791        }
792
793    }
794
795
796    //---------------------------------------------------------
797    // Native methods called from the Java side
798    //--------------------
799
800    private native final int native_setup(Object audiorecord_this,
801            int recordSource, int sampleRate, int nbChannels, int audioFormat,
802            int buffSizeInBytes, int[] sessionId);
803
804    private native final void native_finalize();
805
806    private native final void native_release();
807
808    private native final int native_start(int syncEvent, int sessionId);
809
810    private native final void native_stop();
811
812    private native final int native_read_in_byte_array(byte[] audioData,
813            int offsetInBytes, int sizeInBytes);
814
815    private native final int native_read_in_short_array(short[] audioData,
816            int offsetInShorts, int sizeInShorts);
817
818    private native final int native_read_in_direct_buffer(Object jBuffer, int sizeInBytes);
819
820    private native final int native_set_marker_pos(int marker);
821    private native final int native_get_marker_pos();
822
823    private native final int native_set_pos_update_period(int updatePeriod);
824    private native final int native_get_pos_update_period();
825
826    static private native final int native_get_min_buff_size(
827            int sampleRateInHz, int channelCount, int audioFormat);
828
829
830    //---------------------------------------------------------
831    // Utility methods
832    //------------------
833
834    private static void logd(String msg) {
835        Log.d(TAG, "[ android.media.AudioRecord ] " + msg);
836    }
837
838    private static void loge(String msg) {
839        Log.e(TAG, "[ android.media.AudioRecord ] " + msg);
840    }
841
842}
843