slesTestPlayStream.cpp revision 16ce39d96d41884c7b0d1676553ab8167baaab74
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
78    return SL_RESULT_SUCCESS;
79}
80
81
82//-----------------------------------------------------------------
83
84/* Play some music from a URI  */
85void TestPlayStream( SLObjectItf sl, const char* path)
86{
87    SLEngineItf                EngineItf;
88
89    SLint32                    numOutputs = 0;
90    SLuint32                   deviceID = 0;
91
92    SLresult                   res;
93
94    SLDataSource               audioSource;
95    SLDataLocator_AndroidBufferQueue streamLocator;
96    SLDataFormat_MIME          mime;
97
98    SLDataSink                 audioSink;
99    SLDataLocator_OutputMix    locator_outputmix;
100
101    SLObjectItf                player;
102    SLPlayItf                  playItf;
103    SLVolumeItf                volItf;
104    SLAndroidBufferQueueItf    abqItf;
105
106    SLObjectItf                OutputMix;
107
108    SLboolean required[MAX_NUMBER_INTERFACES];
109    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
110
111    file = fopen(path, "rb");
112
113    /* Get the SL Engine Interface which is implicit */
114    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
115    CheckErr(res);
116
117    /* Initialize arrays required[] and iidArray[] */
118    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
119        required[i] = SL_BOOLEAN_FALSE;
120        iidArray[i] = SL_IID_NULL;
121    }
122
123    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
124    required[0] = SL_BOOLEAN_TRUE;
125    iidArray[0] = SL_IID_VOLUME;
126    required[1] = SL_BOOLEAN_TRUE;
127    iidArray[1] = SL_IID_ANDROIDBUFFERQUEUE;
128    // Create Output Mix object to be used by player
129    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
130            iidArray, required); CheckErr(res);
131
132    // Realizing the Output Mix object in synchronous mode.
133    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
134    CheckErr(res);
135
136    /* Setup the data source structure for the URI */
137    streamLocator.locatorType  = SL_DATALOCATOR_ANDROIDBUFFERQUEUE;
138    streamLocator.numBuffers   = 0; // ignored at the moment
139    streamLocator.queueSize    = 0; // ignored at the moment
140    mime.formatType    = SL_DATAFORMAT_MIME;
141    mime.mimeType      = (SLchar *) "video/mp2ts";//(SLchar*)NULL;
142    mime.containerType = SL_CONTAINERTYPE_MPEG_TS;
143
144    audioSource.pFormat      = (void *)&mime;
145    audioSource.pLocator     = (void *)&streamLocator;
146
147    /* Setup the data sink structure */
148    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
149    locator_outputmix.outputMix    = OutputMix;
150    audioSink.pLocator           = (void *)&locator_outputmix;
151    audioSink.pFormat            = NULL;
152
153    /* Create the audio player */
154    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
155            MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
156
157    /* Realizing the player in synchronous mode. */
158    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
159    fprintf(stdout, "URI example: after Realize\n");
160
161    /* Get interfaces */
162    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf); CheckErr(res);
163
164    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf); CheckErr(res);
165
166    res = (*player)->GetInterface(player, SL_IID_ANDROIDBUFFERQUEUE, (void*)&abqItf);
167    CheckErr(res);
168
169    res = (*abqItf)->RegisterCallback(abqItf, AndroidBufferQueueCallback, &abqItf); CheckErr(res);
170
171    /* Display duration */
172    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
173    res = (*playItf)->GetDuration(playItf, &durationInMsec);
174    CheckErr(res);
175    if (durationInMsec == SL_TIME_UNKNOWN) {
176        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
177    } else {
178        fprintf(stdout, "Content duration is %lu ms (before starting to prefetch)\n",
179                durationInMsec);
180    }
181
182    /* Set the player volume */
183    res = (*volItf)->SetVolumeLevel( volItf, 0);//-300);
184    CheckErr(res);
185
186    /* Play the URI */
187    /*     first cause the player to prefetch the data */
188    fprintf(stdout, "Before set to PAUSED\n");
189    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
190    fprintf(stdout, "After set to PAUSED\n");
191    CheckErr(res);
192
193    /*     wait until there's data to play */
194    //SLpermille fillLevel = 0;
195 /*
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
211    /* Display duration again, */
212/*    res = (*playItf)->GetDuration(playItf, &durationInMsec);
213    CheckErr(res);
214    if (durationInMsec == SL_TIME_UNKNOWN) {
215        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
216    } else {
217        fprintf(stdout, "Content duration is %lu ms (after prefetch completed)\n", durationInMsec);
218    }
219*/
220
221    fprintf(stdout, "URI example: starting to play\n");
222    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
223    CheckErr(res);
224
225    /* Wait as long as the duration of the content before stopping */
226    //usleep(durationInMsec * 1000);
227    int playTimeInSec = 15;
228    fprintf(stdout, "Letting playback go on for %d sec\n", playTimeInSec);
229    usleep(playTimeInSec /*s*/ * 1000 * 1000);
230
231
232    /* Make sure player is stopped */
233    fprintf(stdout, "URI example: stopping playback\n");
234    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
235    CheckErr(res);
236
237    fprintf(stdout, "sleeping to verify playback stopped\n");
238    usleep(2 /*s*/ * 1000 * 1000);
239
240destroyRes:
241
242    /* Destroy the player */
243    (*player)->Destroy(player);
244
245    /* Destroy Output Mix object */
246    (*OutputMix)->Destroy(OutputMix);
247
248    fclose(file);
249}
250
251//-----------------------------------------------------------------
252int main(int argc, char* const argv[])
253{
254    SLresult    res;
255    SLObjectItf sl;
256
257    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf, SLAndroidBufferQueue \n",
258            argv[0]);
259    fprintf(stdout, "and AudioPlayer with SL_DATALOCATOR_ANDROIDBUFFERQUEUE source / OutputMix sink\n");
260    fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
261
262    if (argc == 1) {
263        fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
264        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
265                argv[0], argv[0]);
266        exit(EXIT_FAILURE);
267    }
268
269    SLEngineOption EngineOption[] = {
270            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
271            (SLuint32) SL_BOOLEAN_TRUE}};
272
273    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
274    CheckErr(res);
275    /* Realizing the SL Engine in synchronous mode. */
276    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
277    CheckErr(res);
278
279    TestPlayStream(sl, argv[1]);
280
281    /* Shutdown OpenSL ES */
282    (*sl)->Destroy(sl);
283
284    return EXIT_SUCCESS;
285}
286