slesTestPlayUri.cpp revision b4bdbe2d5d308effc7b9368491b0224d5cce6c1b
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 * Copyright (c) 2009 The Khronos Group Inc.
19 *
20 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
21 * software and /or associated documentation files (the "Materials "), to deal in the
22 * Materials without restriction, including without limitation the rights to use, copy,
23 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials,
24 * and to permit persons to whom the Materials are furnished to do so, subject to
25 * the following conditions:
26 *
27 * The above copyright notice and this permission notice shall be included
28 * in all copies or substantial portions of the Materials.
29 *
30 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
33 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
34 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
35 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
36 * CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE
37 * MATERIALS.
38 */
39
40#include <stdlib.h>
41#include <stdio.h>
42//#include <string.h>
43#include <unistd.h>
44//#include <sys/time.h>
45
46#include <SLES/OpenSLES.h>
47
48//#define TEST_VOLUME_ITF
49//#define TEST_COLD_START
50
51#define MAX_NUMBER_INTERFACES 2
52
53#define PREFETCHEVENT_ERROR_CANDIDATE \
54        (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
55
56//-----------------------------------------------------------------
57//* Exits the application if an error is encountered */
58#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
59
60void ExitOnErrorFunc( SLresult result , int line)
61{
62    if (SL_RESULT_SUCCESS != result) {
63        fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
64        exit(EXIT_FAILURE);
65    }
66}
67
68bool prefetchError = false;
69
70//-----------------------------------------------------------------
71/* PrefetchStatusItf callback for an audio player */
72void PrefetchEventCallback( SLPrefetchStatusItf caller,  void *pContext, SLuint32 event)
73{
74    SLpermille level = 0;
75    SLresult result;
76    result = (*caller)->GetFillLevel(caller, &level);
77    CheckErr(result);
78    SLuint32 status;
79    //fprintf(stdout, "PrefetchEventCallback: received event %u\n", event);
80    result = (*caller)->GetPrefetchStatus(caller, &status);
81    CheckErr(result);
82    if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE))
83            && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
84        fprintf(stdout, "PrefetchEventCallback: Error while prefetching data, exiting\n");
85        prefetchError = true;
86    }
87    if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
88        fprintf(stdout, "PrefetchEventCallback: Buffer fill level is = %d\n", level);
89    }
90    if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
91        fprintf(stdout, "PrefetchEventCallback: Prefetch Status is = %u\n", status);
92    }
93}
94
95
96//-----------------------------------------------------------------
97/* PlayItf callback for playback events */
98void PlayEventCallback(
99        SLPlayItf caller,
100        void *pContext,
101        SLuint32 event)
102{
103    if (SL_PLAYEVENT_HEADATEND & event) {
104        fprintf(stdout, "SL_PLAYEVENT_HEADATEND reached\n");
105        //SignalEos();
106    }
107
108    if (SL_PLAYEVENT_HEADATNEWPOS & event) {
109        SLmillisecond pMsec = 0;
110        (*caller)->GetPosition(caller, &pMsec);
111        fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS current position=%ums\n", pMsec);
112    }
113
114    if (SL_PLAYEVENT_HEADATMARKER & event) {
115        SLmillisecond pMsec = 0;
116        (*caller)->GetPosition(caller, &pMsec);
117        fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER current position=%ums\n", pMsec);
118    }
119}
120
121
122//-----------------------------------------------------------------
123
124/* Play some music from a URI  */
125void TestPlayUri( SLObjectItf sl, const char* path)
126{
127    SLEngineItf                EngineItf;
128
129    SLint32                    numOutputs = 0;
130    SLuint32                   deviceID = 0;
131
132    SLresult                   res;
133
134    SLDataSource               audioSource;
135    SLDataLocator_URI          uri;
136    SLDataFormat_MIME          mime;
137
138    SLDataSink                 audioSink;
139    SLDataLocator_OutputMix    locator_outputmix;
140
141    SLObjectItf                player;
142    SLPlayItf                  playItf;
143    SLVolumeItf                volItf;
144    SLPrefetchStatusItf        prefetchItf;
145
146    SLObjectItf                OutputMix;
147
148    SLboolean required[MAX_NUMBER_INTERFACES];
149    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
150
151    /* Get the SL Engine Interface which is implicit */
152    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
153    CheckErr(res);
154
155    /* Initialize arrays required[] and iidArray[] */
156    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
157        required[i] = SL_BOOLEAN_FALSE;
158        iidArray[i] = SL_IID_NULL;
159    }
160
161    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
162    required[0] = SL_BOOLEAN_TRUE;
163    iidArray[0] = SL_IID_VOLUME;
164    required[1] = SL_BOOLEAN_TRUE;
165    iidArray[1] = SL_IID_PREFETCHSTATUS;
166    // Create Output Mix object to be used by player
167    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
168            iidArray, required); CheckErr(res);
169
170    // Realizing the Output Mix object in synchronous mode.
171    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
172    CheckErr(res);
173
174    /* Setup the data source structure for the URI */
175    uri.locatorType = SL_DATALOCATOR_URI;
176    uri.URI         =  (SLchar*) path;
177    mime.formatType    = SL_DATAFORMAT_MIME;
178    mime.mimeType      = (SLchar*)NULL;
179    mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
180
181    audioSource.pFormat      = (void *)&mime;
182    audioSource.pLocator     = (void *)&uri;
183
184    /* Setup the data sink structure */
185    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
186    locator_outputmix.outputMix    = OutputMix;
187    audioSink.pLocator           = (void *)&locator_outputmix;
188    audioSink.pFormat            = NULL;
189
190    /* Create the audio player */
191    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
192            MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
193
194    /* Realizing the player in synchronous mode. */
195    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
196    fprintf(stdout, "URI example: after Realize\n");
197
198    /* Get interfaces */
199    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
200    CheckErr(res);
201
202    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf);
203    CheckErr(res);
204
205    res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
206    CheckErr(res);
207    res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, &prefetchItf);
208    CheckErr(res);
209    res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
210            SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
211    CheckErr(res);
212
213    /* Configure fill level updates every 5 percent */
214    (*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50);
215
216    /* Set up the player callback to get events during the decoding */
217    res = (*playItf)->SetMarkerPosition(playItf, 2000);
218    CheckErr(res);
219    res = (*playItf)->SetPositionUpdatePeriod(playItf, 500);
220    CheckErr(res);
221    res = (*playItf)->SetCallbackEventsMask(playItf,
222            SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS | SL_PLAYEVENT_HEADATEND);
223    CheckErr(res);
224    res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, NULL);
225    CheckErr(res);
226
227    /* Display duration */
228    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
229    res = (*playItf)->GetDuration(playItf, &durationInMsec);
230    CheckErr(res);
231    if (durationInMsec == SL_TIME_UNKNOWN) {
232        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
233    } else {
234        fprintf(stdout, "Content duration is %u ms (before starting to prefetch)\n",
235                durationInMsec);
236    }
237
238    /* Set the player volume */
239    res = (*volItf)->SetVolumeLevel( volItf, -300);
240    CheckErr(res);
241
242    /* Play the URI */
243    /*     first cause the player to prefetch the data */
244    fprintf(stdout, "Before set to PAUSED\n");
245    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
246    fprintf(stdout, "After set to PAUSED\n");
247    CheckErr(res);
248
249    usleep(100 * 1000);
250    /*     wait until there's data to play */
251    //SLpermille fillLevel = 0;
252    SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
253    SLuint32 timeOutIndex = 100; // 10s
254    while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
255            !prefetchError) {
256        usleep(100 * 1000);
257        (*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
258        timeOutIndex--;
259    }
260
261    if (timeOutIndex == 0 || prefetchError) {
262        fprintf(stderr, "We\'re done waiting, failed to prefetch data in time, exiting\n");
263        goto destroyRes;
264    }
265
266    /* Display duration again, */
267    res = (*playItf)->GetDuration(playItf, &durationInMsec);
268    CheckErr(res);
269    if (durationInMsec == SL_TIME_UNKNOWN) {
270        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
271    } else {
272        fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
273    }
274
275    fprintf(stdout, "URI example: starting to play\n");
276    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
277    CheckErr(res);
278
279#ifdef TEST_VOLUME_ITF
280    usleep(5*1000 * 1000);
281    fprintf(stdout, "setting vol to 0\n");
282    (*volItf)->SetVolumeLevel( volItf, 0);
283    usleep(3*1000 * 1000);
284    fprintf(stdout, "setting vol to -20dB\n");
285    (*volItf)->SetVolumeLevel( volItf, -2000);
286    usleep(3*1000 * 1000);
287    fprintf(stdout, "mute\n");
288    (*volItf)->SetMute( volItf, SL_BOOLEAN_TRUE);
289    usleep(3*1000 * 1000);
290    fprintf(stdout, "setting vol to 0dB while muted\n");
291    (*volItf)->SetVolumeLevel( volItf, 0);
292    usleep(3*1000 * 1000);
293    fprintf(stdout, "unmuting\n");
294    (*volItf)->SetMute( volItf, SL_BOOLEAN_FALSE);
295    usleep(3*1000 * 1000);
296#endif
297
298#ifndef TEST_COLD_START
299    usleep(durationInMsec * 1000);
300#else
301    /* Wait as long as the duration of the content before stopping */
302    /* Experiment: wait for the duration + 200ms: with a cold start of the audio hardware, we */
303    /*    won't see the SL_PLAYEVENT_HEADATEND event, due to hw wake up induced latency, but  */
304    /*    with a warm start it will be received.                                              */
305    usleep((durationInMsec + 200) * 1000);
306#endif
307
308    /* Make sure player is stopped */
309    fprintf(stdout, "URI example: stopping playback\n");
310    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
311    CheckErr(res);
312
313destroyRes:
314
315    /* Destroy the player */
316    (*player)->Destroy(player);
317
318    /* Destroy Output Mix object */
319    (*OutputMix)->Destroy(OutputMix);
320}
321
322//-----------------------------------------------------------------
323int main(int argc, char* const argv[])
324{
325    SLresult    res;
326    SLObjectItf sl;
327
328    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf ", argv[0]);
329    fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
330    fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
331
332    if (argc == 1) {
333        fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
334        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
335                argv[0], argv[0]);
336        exit(EXIT_FAILURE);
337    }
338
339    SLEngineOption EngineOption[] = {
340            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
341            (SLuint32) SL_BOOLEAN_TRUE}};
342
343    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
344    CheckErr(res);
345    /* Realizing the SL Engine in synchronous mode. */
346    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
347    CheckErr(res);
348
349    TestPlayUri(sl, argv[1]);
350
351    /* Shutdown OpenSL ES */
352    (*sl)->Destroy(sl);
353
354    return EXIT_SUCCESS;
355}
356