• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <assert.h>
18 #include <pthread.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <sys/time.h>
24 
25 #include <SLES/OpenSLES.h>
26 
27 
28 #define MAX_NUMBER_INTERFACES 2
29 
30 #define REPETITIONS 4
31 
32 // These are extensions to OpenSL ES 1.0.1 values
33 
34 #define SL_PREFETCHSTATUS_UNKNOWN 0
35 #define SL_PREFETCHSTATUS_ERROR   (-1)
36 
37 // Mutex and condition shared with main program to protect prefetch_status
38 
39 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
40 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
41 SLuint32 prefetch_status = SL_PREFETCHSTATUS_UNKNOWN;
42 
43 /* used to detect errors likely to have occured when the OpenSL ES framework fails to open
44  * a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond.
45  */
46 #define PREFETCHEVENT_ERROR_CANDIDATE \
47         (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
48 
49 //-----------------------------------------------------------------
50 //* Exits the application if an error is encountered */
51 #define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
52 
ExitOnErrorFunc(SLresult result,int line)53 void ExitOnErrorFunc( SLresult result , int line)
54 {
55     if (SL_RESULT_SUCCESS != result) {
56         fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
57         exit(EXIT_FAILURE);
58     }
59 }
60 
61 //-----------------------------------------------------------------
62 /* PrefetchStatusItf callback for an audio player */
PrefetchEventCallback(SLPrefetchStatusItf caller,void * pContext,SLuint32 event)63 void PrefetchEventCallback( SLPrefetchStatusItf caller, void *pContext, SLuint32 event)
64 {
65     SLresult result;
66     // pContext is unused here, so we pass NULL
67     assert(pContext == NULL);
68     SLpermille level = 0;
69     result = (*caller)->GetFillLevel(caller, &level);
70     CheckErr(result);
71     SLuint32 status;
72     result = (*caller)->GetPrefetchStatus(caller, &status);
73     CheckErr(result);
74     if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
75         fprintf(stdout, "\t\tPrefetchEventCallback: Buffer fill level is = %d\n", level);
76     }
77     if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
78         fprintf(stdout, "\t\tPrefetchEventCallback: Prefetch Status is = %u\n", status);
79     }
80     SLuint32 new_prefetch_status;
81     if ((event & PREFETCHEVENT_ERROR_CANDIDATE) == PREFETCHEVENT_ERROR_CANDIDATE
82             && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
83         fprintf(stdout, "\t\tPrefetchEventCallback: Error while prefetching data, exiting\n");
84         new_prefetch_status = SL_PREFETCHSTATUS_ERROR;
85     } else if (event == SL_PREFETCHEVENT_STATUSCHANGE &&
86             status == SL_PREFETCHSTATUS_SUFFICIENTDATA) {
87         new_prefetch_status = status;
88     } else {
89         return;
90     }
91     int ok;
92     ok = pthread_mutex_lock(&mutex);
93     assert(ok == 0);
94     prefetch_status = new_prefetch_status;
95     ok = pthread_cond_signal(&cond);
96     assert(ok == 0);
97     ok = pthread_mutex_unlock(&mutex);
98     assert(ok == 0);
99 }
100 
101 
102 //-----------------------------------------------------------------
103 /* PlayItf callback for playback events */
PlayEventCallback(SLPlayItf caller,void * pContext,SLuint32 event)104 void PlayEventCallback(
105         SLPlayItf caller,
106         void *pContext,
107         SLuint32 event)
108 {
109     // pContext is unused here, so we pass NULL
110     assert(NULL == pContext);
111     if (SL_PLAYEVENT_HEADATEND == event) {
112         printf("SL_PLAYEVENT_HEADATEND reached\n");
113     } else {
114         fprintf(stderr, "Unexpected play event 0x%x", event);
115     }
116 }
117 
118 
119 //-----------------------------------------------------------------
120 
121 /* Play some music from a URI  */
TestLoopUri(SLObjectItf sl,const char * path)122 void TestLoopUri( SLObjectItf sl, const char* path)
123 {
124     SLEngineItf                EngineItf;
125 
126     SLint32                    numOutputs = 0;
127     SLuint32                   deviceID = 0;
128 
129     SLresult                   res;
130 
131     SLDataSource               audioSource;
132     SLDataLocator_URI          uri;
133     SLDataFormat_MIME          mime;
134 
135     SLDataSink                 audioSink;
136     SLDataLocator_OutputMix    locator_outputmix;
137 
138     SLObjectItf                player;
139     SLPlayItf                  playItf;
140     SLSeekItf                  seekItf;
141     SLPrefetchStatusItf        prefetchItf;
142 
143     SLObjectItf                OutputMix;
144 
145     SLboolean required[MAX_NUMBER_INTERFACES];
146     SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
147 
148     /* Get the SL Engine Interface which is implicit */
149     res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
150     CheckErr(res);
151 
152     /* Initialize arrays required[] and iidArray[] */
153     for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
154         required[i] = SL_BOOLEAN_FALSE;
155         iidArray[i] = SL_IID_NULL;
156     }
157 
158     required[0] = SL_BOOLEAN_TRUE;
159     iidArray[0] = SL_IID_VOLUME;
160     // Create Output Mix object to be used by player
161     res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
162             iidArray, required); CheckErr(res);
163 
164     // Realizing the Output Mix object in synchronous mode.
165     res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
166     CheckErr(res);
167 
168     /* Setup the data source structure for the URI */
169     uri.locatorType = SL_DATALOCATOR_URI;
170     uri.URI         =  (SLchar*) path;
171     mime.formatType    = SL_DATAFORMAT_MIME;
172     mime.mimeType      = (SLchar*)NULL;
173     mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
174 
175     audioSource.pFormat      = (void *)&mime;
176     audioSource.pLocator     = (void *)&uri;
177 
178     /* Setup the data sink structure */
179     locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
180     locator_outputmix.outputMix    = OutputMix;
181     audioSink.pLocator           = (void *)&locator_outputmix;
182     audioSink.pFormat            = NULL;
183 
184     /* Create the audio player */
185     required[0] = SL_BOOLEAN_TRUE;
186     iidArray[0] = SL_IID_SEEK;
187     required[1] = SL_BOOLEAN_TRUE;
188     iidArray[1] = SL_IID_PREFETCHSTATUS;
189     res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
190             MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
191 
192     /* Realizing the player in synchronous mode. */
193     res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
194     fprintf(stdout, "URI example: after Realize\n");
195 
196     /* Get interfaces */
197     res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
198     CheckErr(res);
199 
200     res = (*player)->GetInterface(player, SL_IID_SEEK,  (void*)&seekItf);
201     CheckErr(res);
202 
203     res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
204     CheckErr(res);
205     res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, NULL);
206     CheckErr(res);
207     res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
208             SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
209     CheckErr(res);
210 
211     /* Configure fill level updates every 5 percent */
212     (*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50);
213 
214     /* Set up the player callback to get head-at-end events */
215     res = (*playItf)->SetCallbackEventsMask(playItf, SL_PLAYEVENT_HEADATEND);
216     CheckErr(res);
217     res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, NULL);
218     CheckErr(res);
219 
220     /* Display duration */
221     SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
222     res = (*playItf)->GetDuration(playItf, &durationInMsec);
223     CheckErr(res);
224     if (durationInMsec == SL_TIME_UNKNOWN) {
225         fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
226     } else {
227         fprintf(stdout, "Content duration is %u ms (before starting to prefetch)\n",
228                 durationInMsec);
229     }
230 
231     /* Loop on the whole of the content */
232     res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_TRUE, 0, SL_TIME_UNKNOWN);
233     CheckErr(res);
234 
235     /* Play the URI */
236     /*     first cause the player to prefetch the data */
237     res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
238     CheckErr(res);
239 
240     // wait for prefetch status callback to indicate either sufficient data or error
241     pthread_mutex_lock(&mutex);
242     while (prefetch_status == SL_PREFETCHSTATUS_UNKNOWN) {
243         pthread_cond_wait(&cond, &mutex);
244     }
245     pthread_mutex_unlock(&mutex);
246     if (prefetch_status == SL_PREFETCHSTATUS_ERROR) {
247         fprintf(stderr, "Error during prefetch, exiting\n");
248         goto destroyRes;
249     }
250 
251     /* Display duration again, */
252     res = (*playItf)->GetDuration(playItf, &durationInMsec);
253     CheckErr(res);
254     if (durationInMsec == SL_TIME_UNKNOWN) {
255         fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
256     } else {
257         fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
258     }
259 
260     /* Start playing */
261     fprintf(stdout, "starting to play\n");
262     res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
263     CheckErr(res);
264 
265     /* Wait as long as the duration of the content, times the repetitions,
266      * before stopping the loop */
267     usleep( (REPETITIONS-1) * durationInMsec * 1100);
268     res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_FALSE, 0, SL_TIME_UNKNOWN);
269     CheckErr(res);
270     fprintf(stdout, "As of now, stopped looping (sound shouldn't repeat from now on)\n");
271     /* wait some more to make sure it doesn't repeat */
272     usleep(durationInMsec * 1000);
273 
274     /* Stop playback */
275     fprintf(stdout, "stopping playback\n");
276     res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
277     CheckErr(res);
278 
279 destroyRes:
280 
281     /* Destroy the player */
282     (*player)->Destroy(player);
283 
284     /* Destroy Output Mix object */
285     (*OutputMix)->Destroy(OutputMix);
286 }
287 
288 //-----------------------------------------------------------------
main(int argc,char * const argv[])289 int main(int argc, char* const argv[])
290 {
291     SLresult    res;
292     SLObjectItf sl;
293 
294     fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLSeekItf ", argv[0]);
295     fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
296     fprintf(stdout, "Plays a sound and loops it %d times.\n\n", REPETITIONS);
297 
298     if (argc == 1) {
299         fprintf(stdout, "Usage: \n\t%s path \n\t%s url\n", argv[0], argv[0]);
300         fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
301                 argv[0], argv[0]);
302         exit(EXIT_FAILURE);
303     }
304 
305     SLEngineOption EngineOption[] = {
306             {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
307             (SLuint32) SL_BOOLEAN_TRUE}};
308 
309     res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
310     CheckErr(res);
311     /* Realizing the SL Engine in synchronous mode. */
312     res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
313     CheckErr(res);
314 
315     TestLoopUri(sl, argv[1]);
316 
317     /* Shutdown OpenSL ES */
318     (*sl)->Destroy(sl);
319 
320     return EXIT_SUCCESS;
321 }
322