slesTestPlayUri.cpp revision ee21d26b4b66d0f19b826685b3070497523994d5
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#define LOG_NDEBUG 0
41#define LOG_TAG "slesTestPlayUri"
42
43#ifdef ANDROID
44#include <utils/Log.h>
45#else
46#define LOGV printf
47#endif
48#include <getopt.h>
49#include <stdlib.h>
50#include <stdio.h>
51#include <string.h>
52#include <unistd.h>
53#include <sys/time.h>
54
55#include "SLES/OpenSLES.h"
56
57
58#define MAX_NUMBER_INTERFACES 3
59#define MAX_NUMBER_OUTPUT_DEVICES 6
60
61//-----------------------------------------------------------------
62//* Exits the application if an error is encountered */
63#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
64
65void ExitOnErrorFunc( SLresult result , int line)
66{
67    if (SL_RESULT_SUCCESS != result) {
68        fprintf(stdout, "%lu error code encountered at line %d, exiting\n", result, line);
69        exit(1);
70    }
71}
72
73//-----------------------------------------------------------------
74/* PrefetchStatusItf callback for an audio player */
75void PrefetchEventCallback( SLPrefetchStatusItf caller,  void *pContext, SLuint32 event)
76{
77    SLpermille level = 0;
78    (*caller)->GetFillLevel(caller, &level);
79    SLuint32 status;
80    fprintf(stderr, "\t\tPrefetchEventCallback: received event %lu\n", event);
81    (*caller)->GetPrefetchStatus(caller, &status);
82    if ((event & (SL_PREFETCHEVENT_STATUSCHANGE|SL_PREFETCHEVENT_FILLLEVELCHANGE))
83            && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
84        fprintf(stderr, "\t\tPrefetchEventCallback: Error while prefetching data, exiting\n");
85        exit(1);
86    }
87    if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
88        fprintf(stderr, "\t\tPrefetchEventCallback: Buffer fill level is = %d\n", level);
89    }
90    if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
91        fprintf(stderr, "\t\tPrefetchEventCallback: Prefetch Status is = %lu\n", status);
92    }
93
94}
95
96
97//-----------------------------------------------------------------
98
99/* Play some music from a URI  */
100void TestPlayUri( SLObjectItf sl, const char* path)
101{
102    SLEngineItf                EngineItf;
103
104    SLint32                    numOutputs = 0;
105    SLuint32                   deviceID = 0;
106
107    SLresult                   res;
108
109    SLDataSource               audioSource;
110    SLDataLocator_URI          uri;
111    SLDataFormat_MIME          mime;
112
113    SLDataSink                 audioSink;
114    SLDataLocator_OutputMix    locator_outputmix;
115
116    SLObjectItf                player;
117    SLPlayItf                  playItf;
118    SLVolumeItf                volItf;
119    SLPrefetchStatusItf        prefetchItf;
120
121    SLObjectItf                OutputMix;
122
123    SLboolean required[MAX_NUMBER_INTERFACES];
124    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
125
126    /* Get the SL Engine Interface which is implicit */
127    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
128    CheckErr(res);
129
130    /* Initialize arrays required[] and iidArray[] */
131    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
132        required[i] = SL_BOOLEAN_FALSE;
133        iidArray[i] = SL_IID_NULL;
134    }
135
136    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
137    required[0] = SL_BOOLEAN_TRUE;
138    iidArray[0] = SL_IID_VOLUME;
139    required[1] = SL_BOOLEAN_TRUE;
140    iidArray[1] = SL_IID_PREFETCHSTATUS;
141    // Create Output Mix object to be used by player
142    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 1,
143            iidArray, required); CheckErr(res);
144
145    // Realizing the Output Mix object in synchronous mode.
146    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
147    CheckErr(res);
148
149    /* Setup the data source structure for the URI */
150    uri.locatorType = SL_DATALOCATOR_URI;
151    uri.URI         =  (SLchar*) path;
152    mime.formatType    = SL_DATAFORMAT_MIME;
153    mime.mimeType      = (SLchar*)NULL;
154    mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
155
156    audioSource.pFormat      = (void *)&mime;
157    audioSource.pLocator     = (void *)&uri;
158
159    /* Setup the data sink structure */
160    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
161    locator_outputmix.outputMix    = OutputMix;
162    audioSink.pLocator           = (void *)&locator_outputmix;
163    audioSink.pFormat            = NULL;
164
165    /* Create the audio player */
166    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player,
167            &audioSource, &audioSink, 2, iidArray, required); CheckErr(res);
168
169    /* Realizing the player in synchronous mode. */
170    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
171    //fprintf(stdout, "URI example: after Realize\n");
172
173    /* Get interfaces */
174    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
175    CheckErr(res);
176
177    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf);
178    CheckErr(res);
179
180    res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
181    CheckErr(res);
182    res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, &prefetchItf);
183    CheckErr(res);
184    res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
185            SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
186
187
188    /* Display duration */
189    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
190    res = (*playItf)->GetDuration(playItf, &durationInMsec);
191    CheckErr(res);
192    if (durationInMsec == SL_TIME_UNKNOWN) {
193        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
194    } else {
195        fprintf(stdout, "Content duration is %lu ms (before starting to prefetch)\n",
196                durationInMsec);
197    }
198
199    /* Set the player volume */
200    res = (*volItf)->SetVolumeLevel( volItf, -300);
201    CheckErr(res);
202
203    /* Play the URI */
204    /*     first cause the player to prefetch the data */
205    fprintf(stderr, "\nbefore set to PAUSED\n\n");
206    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
207    fprintf(stderr, "\nafter set to PAUSED\n\n");
208    CheckErr(res);
209
210    /*     wait until there's data to play */
211    //SLpermille fillLevel = 0;
212    SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
213    SLuint32 timeOutIndex = 100; // 10s
214    while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0)) {
215        usleep(100 * 1000);
216        (*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
217        timeOutIndex--;
218    }
219
220    if (timeOutIndex == 0) {
221        fprintf(stderr, "We\'re done here, failed to prefetch data in time, exiting\n");
222        goto destroyRes;
223    }
224
225    /* Display duration again, */
226    res = (*playItf)->GetDuration(playItf, &durationInMsec);
227    CheckErr(res);
228    if (durationInMsec == SL_TIME_UNKNOWN) {
229        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
230    } else {
231        fprintf(stdout, "Content duration is %lu ms (after prefetch completed)\n", durationInMsec);
232    }
233
234    fprintf(stdout, "URI example: starting to play\n");
235    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
236    CheckErr(res);
237
238    /* Wait as long as the duration of the content before stopping */
239    usleep(durationInMsec * 1000);
240
241    /* Make sure player is stopped */
242    fprintf(stdout, "URI example: stopping playback\n");
243    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
244    CheckErr(res);
245
246destroyRes:
247
248    /* Destroy the player */
249    (*player)->Destroy(player);
250
251    /* Destroy Output Mix object */
252    (*OutputMix)->Destroy(OutputMix);
253}
254
255//-----------------------------------------------------------------
256int main(int argc, char* const argv[])
257{
258    LOGV("Starting slesTestPlayUri\n");
259
260    SLresult    res;
261    SLObjectItf sl;
262
263    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf ", argv[0]);
264    fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
265    fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
266
267    if (argc == 1) {
268        fprintf(stdout, "Usage: \n\t%s path \n\t%s url\n", argv[0], argv[0]);
269        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n", argv[0], argv[0]);
270        exit(1);
271    }
272
273    SLEngineOption EngineOption[] = {
274            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
275            (SLuint32) SL_BOOLEAN_TRUE}};
276
277    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
278    CheckErr(res);
279    /* Realizing the SL Engine in synchronous mode. */
280    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
281    CheckErr(res);
282
283    TestPlayUri(sl, argv[1]);
284
285    /* Shutdown OpenSL ES */
286    (*sl)->Destroy(sl);
287    exit(0);
288
289    return 0;
290}
291