slesTestPlayStream.cpp revision 26043f06b7d6cb2f93a2f2e7846a4e59da722206
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//-----------------------------------------------------------------
51/* AndroidStreamSourceItf callback for an audio player */
52SLresult AndroidStreamSourceCallback(
53        SLAndroidStreamSourceItf caller,/* input */
54        void *pContext,                 /* input */
55        SLAint64* pLength,              /* input, output */
56        SLAstreamEvent* pEvent,         /* output */
57        void *pData)                    /* output */
58{
59    fprintf(stdout, "AndroidStreamSourceCallback called\n");
60
61    size_t nbRead = fread(pData, 1, *pLength, file);
62
63    *pLength = nbRead;
64    if (nbRead <= 0) {
65        *pEvent = SL_ANDROID_STREAMEVENT_EOS;
66    } else {
67        *pEvent = SL_ANDROID_STREAMEVENT_NONE; // no event to report
68    }
69    //leaving pData untouched
70    return SL_RESULT_SUCCESS;
71}
72
73
74//-----------------------------------------------------------------
75
76/* Play some music from a URI  */
77void TestPlayStream( SLObjectItf sl, const char* path)
78{
79    SLEngineItf                EngineItf;
80
81    SLint32                    numOutputs = 0;
82    SLuint32                   deviceID = 0;
83
84    SLresult                   res;
85
86    SLDataSource               audioSource;
87    SLDataLocator_AndroidStreamer streamLocator;
88    SLDataFormat_MIME          mime;
89
90    SLDataSink                 audioSink;
91    SLDataLocator_OutputMix    locator_outputmix;
92
93    SLObjectItf                player;
94    SLPlayItf                  playItf;
95    SLVolumeItf                volItf;
96    SLAndroidStreamSourceItf   streamSrcItf;
97
98    SLObjectItf                OutputMix;
99
100    SLboolean required[MAX_NUMBER_INTERFACES];
101    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
102
103    file = fopen(path, "rb");
104
105    /* Get the SL Engine Interface which is implicit */
106    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
107    CheckErr(res);
108
109    /* Initialize arrays required[] and iidArray[] */
110    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
111        required[i] = SL_BOOLEAN_FALSE;
112        iidArray[i] = SL_IID_NULL;
113    }
114
115    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
116    required[0] = SL_BOOLEAN_TRUE;
117    iidArray[0] = SL_IID_VOLUME;
118    required[1] = SL_BOOLEAN_TRUE;
119    iidArray[1] = SL_IID_ANDROIDSTREAMSOURCE;
120    // Create Output Mix object to be used by player
121    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
122            iidArray, required); CheckErr(res);
123
124    // Realizing the Output Mix object in synchronous mode.
125    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
126    CheckErr(res);
127
128    /* Setup the data source structure for the URI */
129    streamLocator.locatorType  = SL_DATALOCATOR_ANDROIDSTREAMER;
130    streamLocator.URI          =  (SLchar*) path;
131    streamLocator.streamOrigin = SL_ANDROID_STREAMORIGIN_FILE;
132    mime.formatType    = SL_DATAFORMAT_MIME;
133    mime.mimeType      = (SLchar*)NULL;
134    mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
135
136    audioSource.pFormat      = (void *)&mime;
137    audioSource.pLocator     = (void *)&streamLocator;
138
139    /* Setup the data sink structure */
140    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
141    locator_outputmix.outputMix    = OutputMix;
142    audioSink.pLocator           = (void *)&locator_outputmix;
143    audioSink.pFormat            = NULL;
144
145    /* Create the audio player */
146    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
147            MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
148
149    /* Realizing the player in synchronous mode. */
150    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
151    fprintf(stdout, "URI example: after Realize\n");
152
153    /* Get interfaces */
154    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf); CheckErr(res);
155
156    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf); CheckErr(res);
157
158    res = (*player)->GetInterface(player, SL_IID_ANDROIDSTREAMSOURCE, (void*)&streamSrcItf);
159    CheckErr(res);
160    res = (*streamSrcItf)->RegisterCallback(streamSrcItf, AndroidStreamSourceCallback,
161            &streamSrcItf); CheckErr(res);
162
163    /* Display duration */
164    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
165    res = (*playItf)->GetDuration(playItf, &durationInMsec);
166    CheckErr(res);
167    if (durationInMsec == SL_TIME_UNKNOWN) {
168        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
169    } else {
170        fprintf(stdout, "Content duration is %lu ms (before starting to prefetch)\n",
171                durationInMsec);
172    }
173
174    /* Set the player volume */
175    res = (*volItf)->SetVolumeLevel( volItf, 0);//-300);
176    CheckErr(res);
177
178    /* Play the URI */
179    /*     first cause the player to prefetch the data */
180    fprintf(stdout, "Before set to PAUSED\n");
181    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
182    fprintf(stdout, "After set to PAUSED\n");
183    CheckErr(res);
184
185    /*     wait until there's data to play */
186    //SLpermille fillLevel = 0;
187 /*   SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
188    SLuint32 timeOutIndex = 2;
189    while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
190            !prefetchError) {
191        usleep(1 * 1000 * 1000); // 1s
192        //(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
193        timeOutIndex--;
194    }
195
196    if (timeOutIndex == 0 || prefetchError) {
197        fprintf(stderr, "We\'re done waiting, failed to prefetch data in time, exiting\n");
198        goto destroyRes;
199    }*/
200
201    /* Display duration again, */
202    res = (*playItf)->GetDuration(playItf, &durationInMsec);
203    CheckErr(res);
204    if (durationInMsec == SL_TIME_UNKNOWN) {
205        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
206    } else {
207        fprintf(stdout, "Content duration is %lu ms (after prefetch completed)\n", durationInMsec);
208    }
209
210    fprintf(stdout, "URI example: starting to play\n");
211    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
212    CheckErr(res);
213
214    /* Wait as long as the duration of the content before stopping */
215    //usleep(durationInMsec * 1000);
216    usleep(30 /*s*/ * 1000 * 1000);
217
218
219    /* Make sure player is stopped */
220    fprintf(stdout, "URI example: stopping playback\n");
221    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
222    CheckErr(res);
223
224destroyRes:
225
226    /* Destroy the player */
227    (*player)->Destroy(player);
228
229    /* Destroy Output Mix object */
230    (*OutputMix)->Destroy(OutputMix);
231
232    fclose(file);
233}
234
235//-----------------------------------------------------------------
236int main(int argc, char* const argv[])
237{
238    SLresult    res;
239    SLObjectItf sl;
240
241    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf, SLAndroidStreamSource ",
242            argv[0]);
243    fprintf(stdout, "and AudioPlayer with SL_DATALOCATOR_ANDROIDSTREAMER source / OutputMix sink\n");
244    fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
245
246    if (argc == 1) {
247        fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
248        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
249                argv[0], argv[0]);
250        exit(EXIT_FAILURE);
251    }
252
253    SLEngineOption EngineOption[] = {
254            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
255            (SLuint32) SL_BOOLEAN_TRUE}};
256
257    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
258    CheckErr(res);
259    /* Realizing the SL Engine in synchronous mode. */
260    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
261    CheckErr(res);
262
263    TestPlayStream(sl, argv[1]);
264
265    /* Shutdown OpenSL ES */
266    (*sl)->Destroy(sl);
267
268    return EXIT_SUCCESS;
269}
270