slesTestRecBuffQueue.cpp revision 9bc234ed758273259e334144cc6e1643b2494175
1/*
2 * Copyright (C) 2010 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#include <getopt.h>
18#include <stdlib.h>
19#include <stdio.h>
20#include <string.h>
21#include <unistd.h>
22#include <sys/time.h>
23#include <fcntl.h>
24
25#include "OpenSLES.h"
26#include "OpenSLES_Android.h"
27#include "OpenSLES_AndroidConfiguration.h"
28
29/* Explicitly requesting SL_IID_BUFFERQUEUE and SL_IID_ANDROIDCONFIGURATION
30 * on the AudioRecorder object */
31#define NUM_EXPLICIT_INTERFACES_FOR_RECORDER 2
32
33/* Size of the recording buffer queue */
34#define NB_BUFFERS_IN_QUEUE 1
35/* Size of each buffer in the queue */
36#define BUFFER_SIZE_IN_SAMPLES 1024
37#define BUFFER_SIZE_IN_BYTES   (2*BUFFER_SIZE_IN_SAMPLES)
38
39/* Local storage for Audio data */
40int8_t pcmData[NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES];
41
42/* destination for recorded data */
43static FILE* gFp;
44
45//-----------------------------------------------------------------
46/* Exits the application if an error is encountered */
47#define ExitOnError(x) ExitOnErrorFunc(x,__LINE__)
48
49void ExitOnErrorFunc( SLresult result , int line)
50{
51    if (SL_RESULT_SUCCESS != result) {
52        fprintf(stdout, "%lu error code encountered at line %d, exiting\n", result, line);
53        exit(1);
54    }
55}
56
57//-----------------------------------------------------------------
58/* Structure for passing information to callback function */
59typedef struct CallbackCntxt_ {
60    SLPlayItf  playItf;
61    SLuint32   size;
62    SLint8*   pDataBase;    // Base address of local audio data storage
63    SLint8*   pData;        // Current address of local audio data storage
64} CallbackCntxt;
65
66
67//-----------------------------------------------------------------
68/* Callback for recording buffer queue events */
69void RecCallback(
70        SLRecordItf caller,
71        void *pContext,
72        SLuint32 event)
73{
74    if (SL_RECORDEVENT_HEADATNEWPOS & event) {
75        SLmillisecond pMsec = 0;
76        (*caller)->GetPosition(caller, &pMsec);
77        fprintf(stdout, "SL_RECORDEVENT_HEADATNEWPOS current position=%lums\n", pMsec);
78    }
79
80    if (SL_RECORDEVENT_HEADATMARKER & event) {
81        SLmillisecond pMsec = 0;
82        (*caller)->GetPosition(caller, &pMsec);
83        fprintf(stdout, "SL_RECORDEVENT_HEADATMARKER current position=%lums\n", pMsec);
84    }
85}
86
87//-----------------------------------------------------------------
88/* Callback for recording buffer queue events */
89void RecBufferQueueCallback(
90        SLBufferQueueItf queueItf,
91        void *pContext)
92{
93    fprintf(stdout, "RecBufferQueueCallback called\n");
94
95    CallbackCntxt *pCntxt = (CallbackCntxt*)pContext;
96
97    /* Save the recorded data  */
98    fwrite(pCntxt->pDataBase, BUFFER_SIZE_IN_BYTES, 1, gFp);
99
100    /* Increase data pointer by buffer size */
101    pCntxt->pData += BUFFER_SIZE_IN_BYTES;
102
103    if (pCntxt->pData >= pCntxt->pDataBase + (NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES)) {
104        pCntxt->pData = pCntxt->pDataBase;
105    }
106
107    ExitOnError( (*queueItf)->Enqueue(queueItf, pCntxt->pDataBase, BUFFER_SIZE_IN_BYTES) );
108
109    SLBufferQueueState recQueueState;
110    ExitOnError( (*queueItf)->GetState(queueItf, &recQueueState) );
111
112    fprintf(stderr, "\tRecBufferQueueCallback now has pCntxt->pData=%p queue: "
113            "count=%lu playIndex=%lu\n",
114            pCntxt->pData, recQueueState.count, recQueueState.playIndex);
115}
116
117//-----------------------------------------------------------------
118
119/* Play an audio path by opening a file descriptor on that path  */
120void TestRecToBuffQueue( SLObjectItf sl, const char* path, SLAint64 durationInSeconds)
121{
122    gFp = fopen(path, "w");
123    if (NULL == gFp) {
124        ExitOnError(SL_RESULT_RESOURCE_ERROR);
125    }
126
127    SLresult  result;
128    SLEngineItf EngineItf;
129
130    /* Objects this application uses: one audio recorder */
131    SLObjectItf  recorder;
132
133    /* Interfaces for the audio recorder */
134    SLBufferQueueItf          recBuffQueueItf;
135    SLRecordItf               recordItf;
136    SLAndroidConfigurationItf configItf;
137
138    /* Source of audio data for the recording */
139    SLDataSource           recSource;
140    SLDataLocator_IODevice ioDevice;
141
142    /* Data sink for recorded audio */
143    SLDataSink                recDest;
144    SLDataLocator_BufferQueue recBuffQueue;
145    SLDataFormat_PCM          pcm;
146
147    SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_RECORDER];
148    SLInterfaceID iidArray[NUM_EXPLICIT_INTERFACES_FOR_RECORDER];
149
150    /* Get the SL Engine Interface which is implicit */
151    result = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
152    ExitOnError(result);
153
154    /* Initialize arrays required[] and iidArray[] */
155    for (int i=0 ; i < NUM_EXPLICIT_INTERFACES_FOR_RECORDER ; i++) {
156        required[i] = SL_BOOLEAN_FALSE;
157        iidArray[i] = SL_IID_NULL;
158    }
159
160
161    /* ------------------------------------------------------ */
162    /* Configuration of the recorder  */
163
164    /* Request the BufferQueue and AndroidConfiguration interfaces */
165    required[0] = SL_BOOLEAN_TRUE;
166    iidArray[0] = SL_IID_BUFFERQUEUE;
167    required[1] = SL_BOOLEAN_TRUE;
168    iidArray[1] = SL_IID_ANDROIDCONFIGURATION;
169
170    /* Setup the data source */
171    ioDevice.locatorType = SL_DATALOCATOR_IODEVICE;
172    ioDevice.deviceType = SL_IODEVICE_AUDIOINPUT;
173    ioDevice.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
174    ioDevice.device = NULL;
175    recSource.pLocator = (void *) &ioDevice;
176
177    /* Setup the data sink */
178    recBuffQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE;
179    recBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE;
180    /*    set up the format of the data in the buffer queue */
181    pcm.formatType = SL_DATAFORMAT_PCM;
182    pcm.numChannels = 1;
183    pcm.samplesPerSec = SL_SAMPLINGRATE_22_05;
184    pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
185    pcm.containerSize = 16;
186    pcm.channelMask = SL_SPEAKER_FRONT_LEFT;
187    pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
188
189    recDest.pLocator = (void *) &recBuffQueue;
190    recDest.pFormat = (void * ) &pcm;
191
192    /* Create the audio recorder */
193    result = (*EngineItf)->CreateAudioRecorder(EngineItf, &recorder, &recSource, &recDest,
194            NUM_EXPLICIT_INTERFACES_FOR_RECORDER, iidArray, required);
195    ExitOnError(result);
196    fprintf(stdout, "Recorder created\n");
197
198    /* Get the Android configuration interface which is explicit */
199    result = (*recorder)->GetInterface(recorder, SL_IID_ANDROIDCONFIGURATION, (void*)&configItf);
200    ExitOnError(result);
201
202    /* Use the configuration interface to configure the recorder before it's realized */
203    SLuint32 presetValue = SL_ANDROID_RECORDING_PRESET_CAMCORDER;
204    result = (*configItf)->SetConfiguration(configItf, SL_ANDROID_KEY_RECORDING_PRESET,
205            &presetValue, sizeof(SLuint32));
206    ExitOnError(result);
207    fprintf(stdout, "Recorder parametrized\n");
208
209    presetValue = SL_ANDROID_RECORDING_PRESET_NONE;
210    SLuint32 presetSize = 2*sizeof(SLuint32); // intentionally too big
211    result = (*configItf)->GetConfiguration(configItf, SL_ANDROID_KEY_RECORDING_PRESET,
212            &presetSize, (void*)&presetValue);
213    ExitOnError(result);
214    if (presetValue != SL_ANDROID_RECORDING_PRESET_CAMCORDER) {
215        fprintf(stderr, "Error retrieved recording preset\n");
216        ExitOnError(SL_RESULT_INTERNAL_ERROR);
217    }
218
219    /* Realize the recorder in synchronous mode. */
220    result = (*recorder)->Realize(recorder, SL_BOOLEAN_FALSE);
221    ExitOnError(result);
222    fprintf(stdout, "Recorder realized\n");
223
224    /* Get the record interface which is implicit */
225    result = (*recorder)->GetInterface(recorder, SL_IID_RECORD, (void*)&recordItf);
226    ExitOnError(result);
227
228    /* Set up the recorder callback to get events during the recording */
229    result = (*recordItf)->SetMarkerPosition(recordItf, 2000);
230    ExitOnError(result);
231    result = (*recordItf)->SetPositionUpdatePeriod(recordItf, 500);
232    ExitOnError(result);
233    result = (*recordItf)->SetCallbackEventsMask(recordItf,
234            SL_RECORDEVENT_HEADATMARKER | SL_RECORDEVENT_HEADATNEWPOS);
235    ExitOnError(result);
236    result = (*recordItf)->RegisterCallback(recordItf, RecCallback, NULL);
237    ExitOnError(result);
238    fprintf(stdout, "Recorder callback registered\n");
239
240    /* Get the buffer queue interface which was explicitly requested */
241    result = (*recorder)->GetInterface(recorder, SL_IID_BUFFERQUEUE, (void*)&recBuffQueueItf);
242    ExitOnError(result);
243
244    /* ------------------------------------------------------ */
245    /* Initialize the callback and its context for the recording buffer queue */
246    CallbackCntxt cntxt;
247    cntxt.pDataBase = (int8_t*)&pcmData;
248    cntxt.pData = cntxt.pDataBase;
249    cntxt.size = sizeof(pcmData);
250    result = (*recBuffQueueItf)->RegisterCallback(recBuffQueueItf, RecBufferQueueCallback, &cntxt);
251    ExitOnError(result);
252
253    /* Enqueue buffers to map the region of memory allocated to store the recorded data */
254    fprintf(stdout,"Enqueueing buffer ");
255    for(int i = 0 ; i < NB_BUFFERS_IN_QUEUE ; i++) {
256        fprintf(stdout,"%d ", i);
257        result = (*recBuffQueueItf)->Enqueue(recBuffQueueItf, cntxt.pData, BUFFER_SIZE_IN_BYTES);
258        ExitOnError(result);
259        cntxt.pData += BUFFER_SIZE_IN_BYTES;
260    }
261    fprintf(stdout,"\n");
262    cntxt.pData = cntxt.pDataBase;
263
264    /* ------------------------------------------------------ */
265    /* Start recording */
266    result = (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_RECORDING);
267    ExitOnError(result);
268    fprintf(stdout, "Starting to record\n");
269
270    /* Record for at least a second */
271    if (durationInSeconds < 1) {
272        durationInSeconds = 1;
273    }
274    usleep(durationInSeconds * 1000 * 1000);
275
276    /* ------------------------------------------------------ */
277    /* End of recording */
278
279    /* Stop recording */
280    result = (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED);
281    ExitOnError(result);
282    fprintf(stdout, "Stopped recording\n");
283
284    /* Destroy the AudioRecorder object */
285    (*recorder)->Destroy(recorder);
286
287    fclose(gFp);
288}
289
290//-----------------------------------------------------------------
291int main(int argc, char* const argv[])
292{
293    //LOGV("Starting %s\n", argv[0]);
294
295    SLresult    result;
296    SLObjectItf sl;
297
298    fprintf(stdout, "OpenSL ES test %s: exercises SLRecordItf and SLBufferQueueItf ", argv[0]);
299    fprintf(stdout, "on an AudioRecorder object\n");
300
301    if (argc < 2) {
302        fprintf(stdout, "Usage: \t%s destination_file duration_in_seconds\n", argv[0]);
303        fprintf(stdout, "Example: \"%s /sdcard/myrec.raw 4\" \n", argv[0]);
304        exit(1);
305    }
306
307    SLEngineOption EngineOption[] = {
308            {(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE}
309    };
310
311    result = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
312    ExitOnError(result);
313
314    /* Realizing the SL Engine in synchronous mode. */
315    result = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
316    ExitOnError(result);
317
318    TestRecToBuffQueue(sl, argv[1], (SLAint64)atoi(argv[2]));
319
320    /* Shutdown OpenSL ES */
321    (*sl)->Destroy(sl);
322    exit(0);
323
324    return 0;
325}
326