slesTestPlayStream.cpp revision be59fc5cfd9354d70d4b0e28bb2bca24a6ca6f22
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
18#include <stdlib.h>
19#include <stdio.h>
20//#include <string.h>
21#include <unistd.h>
22//#include <sys/time.h>
23
24#include "SLES/OpenSLES.h"
25#include "SLES/OpenSLES_Android.h"
26
27
28#define MAX_NUMBER_INTERFACES 2
29
30#define PREFETCHEVENT_ERROR_CANDIDATE \
31        (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
32
33FILE *file;
34
35//-----------------------------------------------------------------
36//* Exits the application if an error is encountered */
37#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
38
39void ExitOnErrorFunc( SLresult result , int line)
40{
41    if (SL_RESULT_SUCCESS != result) {
42        fprintf(stderr, "%lu error code encountered at line %d, exiting\n", result, line);
43        exit(EXIT_FAILURE);
44    }
45}
46
47bool prefetchError = false;
48
49//-----------------------------------------------------------------
50/* AndroidBufferQueueItf callback for an audio player */
51SLresult AndroidBufferQueueCallback(
52        SLAndroidBufferQueueItf caller,
53            void *pContext,
54            SLuint32 bufferId,
55            SLAint64 bufferLength,
56            void *pBufferDataLocation)
57
58{
59    fprintf(stdout, "cb ");
60
61    size_t nbRead = fread(pBufferDataLocation, 1, bufferLength, file);
62
63    SLAbufferQueueEvent event = SL_ANDROIDBUFFERQUEUE_EVENT_NONE;
64    if (nbRead <= 0) {
65        event = SL_ANDROIDBUFFERQUEUE_EVENT_EOS;
66    } else {
67        event = SL_ANDROIDBUFFERQUEUE_EVENT_NONE; // no event to report
68    }
69
70    //fprintf(stdout, "caller = %p\n", caller);
71
72    // enqueue the data right-away because in this example we're reading from a file, so we
73    // can afford to do that. When streaming from the network, we would write from our cache
74    // to this queue.
75    // last param is NULL because we've already written the data in the buffer queue
76    (*caller)->Enqueue(caller, bufferId, nbRead, event, NULL);
77    //(*abqItf)->Enqueue(abqItf, bufferId, nbRead, event, NULL);
78
79    return SL_RESULT_SUCCESS;
80}
81
82
83//-----------------------------------------------------------------
84
85/* Play some music from a URI  */
86void TestPlayStream( SLObjectItf sl, const char* path)
87{
88    SLEngineItf                EngineItf;
89
90    SLint32                    numOutputs = 0;
91    SLuint32                   deviceID = 0;
92
93    SLresult                   res;
94
95    SLDataSource               audioSource;
96    SLDataLocator_AndroidBufferQueue streamLocator;
97    SLDataFormat_MIME          mime;
98
99    SLDataSink                 audioSink;
100    SLDataLocator_OutputMix    locator_outputmix;
101
102    SLObjectItf                player;
103    SLPlayItf                  playItf;
104    SLVolumeItf                volItf;
105    SLAndroidBufferQueueItf    abqItf;
106
107    SLObjectItf                OutputMix;
108
109    SLboolean required[MAX_NUMBER_INTERFACES];
110    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
111
112    file = fopen(path, "rb");
113
114    /* Get the SL Engine Interface which is implicit */
115    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
116    CheckErr(res);
117
118    /* Initialize arrays required[] and iidArray[] */
119    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
120        required[i] = SL_BOOLEAN_FALSE;
121        iidArray[i] = SL_IID_NULL;
122    }
123
124    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
125    required[0] = SL_BOOLEAN_TRUE;
126    iidArray[0] = SL_IID_VOLUME;
127    required[1] = SL_BOOLEAN_TRUE;
128    iidArray[1] = SL_IID_ANDROIDBUFFERQUEUE;
129    // Create Output Mix object to be used by player
130    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
131            iidArray, required); CheckErr(res);
132
133    // Realizing the Output Mix object in synchronous mode.
134    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
135    CheckErr(res);
136
137    /* Setup the data source structure for the URI */
138    streamLocator.locatorType  = SL_DATALOCATOR_ANDROIDBUFFERQUEUE;
139    streamLocator.numBuffers   = 0; // ignored at the moment
140    streamLocator.queueSize    = 0; // ignored at the moment
141    mime.formatType    = SL_DATAFORMAT_MIME;
142    mime.mimeType      = (SLchar*)NULL;
143    mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
144
145    audioSource.pFormat      = (void *)&mime;
146    audioSource.pLocator     = (void *)&streamLocator;
147
148    /* Setup the data sink structure */
149    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
150    locator_outputmix.outputMix    = OutputMix;
151    audioSink.pLocator           = (void *)&locator_outputmix;
152    audioSink.pFormat            = NULL;
153
154    /* Create the audio player */
155    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
156            MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
157
158    /* Realizing the player in synchronous mode. */
159    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
160    fprintf(stdout, "URI example: after Realize\n");
161
162    /* Get interfaces */
163    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf); CheckErr(res);
164
165    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf); CheckErr(res);
166
167    res = (*player)->GetInterface(player, SL_IID_ANDROIDBUFFERQUEUE, (void*)&abqItf);
168    CheckErr(res);
169
170    res = (*abqItf)->RegisterCallback(abqItf, AndroidBufferQueueCallback, &abqItf); CheckErr(res);
171
172    /* Display duration */
173    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
174    res = (*playItf)->GetDuration(playItf, &durationInMsec);
175    CheckErr(res);
176    if (durationInMsec == SL_TIME_UNKNOWN) {
177        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
178    } else {
179        fprintf(stdout, "Content duration is %lu ms (before starting to prefetch)\n",
180                durationInMsec);
181    }
182
183    /* Set the player volume */
184    res = (*volItf)->SetVolumeLevel( volItf, 0);//-300);
185    CheckErr(res);
186
187    /* Play the URI */
188    /*     first cause the player to prefetch the data */
189    fprintf(stdout, "Before set to PAUSED\n");
190    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
191    fprintf(stdout, "After set to PAUSED\n");
192    CheckErr(res);
193
194    /*     wait until there's data to play */
195    //SLpermille fillLevel = 0;
196 /*   SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
197    SLuint32 timeOutIndex = 2;
198    while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
199            !prefetchError) {
200        usleep(1 * 1000 * 1000); // 1s
201        //(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
202        timeOutIndex--;
203    }
204
205    if (timeOutIndex == 0 || prefetchError) {
206        fprintf(stderr, "We\'re done waiting, failed to prefetch data in time, exiting\n");
207        goto destroyRes;
208    }*/
209
210    /* Display duration again, */
211    res = (*playItf)->GetDuration(playItf, &durationInMsec);
212    CheckErr(res);
213    if (durationInMsec == SL_TIME_UNKNOWN) {
214        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
215    } else {
216        fprintf(stdout, "Content duration is %lu ms (after prefetch completed)\n", durationInMsec);
217    }
218
219    fprintf(stdout, "URI example: starting to play\n");
220    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
221    CheckErr(res);
222
223    /* Wait as long as the duration of the content before stopping */
224    //usleep(durationInMsec * 1000);
225    usleep(15 /*s*/ * 1000 * 1000);
226
227
228    /* Make sure player is stopped */
229    fprintf(stdout, "URI example: stopping playback\n");
230    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
231    CheckErr(res);
232
233    fprintf(stdout, "sleeping to verify playback stopped\n");
234    usleep(2 /*s*/ * 1000 * 1000);
235
236destroyRes:
237
238    /* Destroy the player */
239    (*player)->Destroy(player);
240
241    /* Destroy Output Mix object */
242    (*OutputMix)->Destroy(OutputMix);
243
244    fclose(file);
245}
246
247//-----------------------------------------------------------------
248int main(int argc, char* const argv[])
249{
250    SLresult    res;
251    SLObjectItf sl;
252
253    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf, SLAndroidBufferQueue \n",
254            argv[0]);
255    fprintf(stdout, "and AudioPlayer with SL_DATALOCATOR_ANDROIDBUFFERQUEUE source / OutputMix sink\n");
256    fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
257
258    if (argc == 1) {
259        fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
260        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
261                argv[0], argv[0]);
262        exit(EXIT_FAILURE);
263    }
264
265    SLEngineOption EngineOption[] = {
266            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
267            (SLuint32) SL_BOOLEAN_TRUE}};
268
269    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
270    CheckErr(res);
271    /* Realizing the SL Engine in synchronous mode. */
272    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
273    CheckErr(res);
274
275    TestPlayStream(sl, argv[1]);
276
277    /* Shutdown OpenSL ES */
278    (*sl)->Destroy(sl);
279
280    return EXIT_SUCCESS;
281}
282