slesTestPlayStream.cpp revision 70c49ae2867094072a4365423417ea452bf82231
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
33#define NB_BUFFERS 16
34#define MPEG2_TS_BLOCK_SIZE 188
35#define BUFFER_SIZE 20*MPEG2_TS_BLOCK_SIZE
36
37/* Where we store the data to play */
38char dataCache[BUFFER_SIZE * NB_BUFFERS];
39/* From where we read the data to play */
40FILE *file;
41/* Has the app reached the end of the file */
42bool reachedEof = false;
43
44//-----------------------------------------------------------------
45//* Exits the application if an error is encountered */
46#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
47
48void ExitOnErrorFunc( SLresult result , int line)
49{
50    if (SL_RESULT_SUCCESS != result) {
51        fprintf(stderr, "%lu error code encountered at line %d, exiting\n", result, line);
52        exit(EXIT_FAILURE);
53    }
54}
55
56bool prefetchError = false;
57
58//-----------------------------------------------------------------
59/* AndroidBufferQueueItf callback for an audio player */
60SLresult AndroidBufferQueueCallback(
61        SLAndroidBufferQueueItf caller,
62        void *pContext,                /* input */
63        const void *pBufferData,       /* input */
64        SLuint32 dataSize,             /* input */
65        SLuint32 dataUsed,             /* input */
66        const SLAndroidBufferItem *pItems,/* input */
67        SLuint32 itemsLength           /* input */)
68{
69    // assert(BUFFER_SIZE <= dataSize);
70    size_t nbRead = fread((void*)pBufferData, 1, BUFFER_SIZE, file);
71    if (nbRead > 0) {
72        (*caller)->Enqueue(caller,
73                pBufferData /*pData*/,
74                nbRead /*dataLength*/,
75                NULL /*pMsg*/,
76                0 /*msgLength*/);
77    } else if (!reachedEof) {
78        // signal EOS
79        SLAndroidBufferItem msgEos;
80        msgEos.itemKey = SL_ANDROID_ITEMKEY_EOS;
81        msgEos.itemSize = 0;
82        // EOS message has no parameters, so the total size of the message is the size of the key
83        //   plus the size if itemSize, both SLuint32
84        (*caller)->Enqueue(caller, NULL /*pData*/, 0 /*dataLength*/,
85                        &msgEos /*pMsg*/,
86                        sizeof(SLuint32)*2 /*msgLength*/);
87        reachedEof = true;
88    }
89
90    return SL_RESULT_SUCCESS;
91}
92
93
94//-----------------------------------------------------------------
95
96/* Play some music from a URI  */
97void TestPlayStream( SLObjectItf sl, const char* path)
98{
99    SLEngineItf                EngineItf;
100
101    SLint32                    numOutputs = 0;
102    SLuint32                   deviceID = 0;
103
104    SLresult                   res;
105
106    SLDataSource               audioSource;
107    SLDataLocator_AndroidBufferQueue streamLocator;
108    SLDataFormat_MIME          mime;
109
110    SLDataSink                 audioSink;
111    SLDataLocator_OutputMix    locator_outputmix;
112
113    SLObjectItf                player;
114    SLPlayItf                  playItf;
115    SLVolumeItf                volItf;
116    SLAndroidBufferQueueItf    abqItf;
117
118    SLObjectItf                OutputMix;
119
120    SLboolean required[MAX_NUMBER_INTERFACES];
121    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
122
123    int playTimeInSec = 60;
124
125    file = fopen(path, "rb");
126
127    /* Get the SL Engine Interface which is implicit */
128    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
129    CheckErr(res);
130
131    /* Initialize arrays required[] and iidArray[] */
132    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
133        required[i] = SL_BOOLEAN_FALSE;
134        iidArray[i] = SL_IID_NULL;
135    }
136
137    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
138    required[0] = SL_BOOLEAN_TRUE;
139    iidArray[0] = SL_IID_VOLUME;
140    required[1] = SL_BOOLEAN_TRUE;
141    iidArray[1] = SL_IID_ANDROIDBUFFERQUEUE;
142    // Create Output Mix object to be used by player
143    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
144            iidArray, required); CheckErr(res);
145
146    // Realizing the Output Mix object in synchronous mode.
147    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
148    CheckErr(res);
149
150    /* Setup the data source structure for the URI */
151    streamLocator.locatorType  = SL_DATALOCATOR_ANDROIDBUFFERQUEUE;
152    streamLocator.numBuffers   = NB_BUFFERS;
153    mime.formatType    = SL_DATAFORMAT_MIME;
154    mime.mimeType      = (SLchar *) "video/mp2ts";//(SLchar*)NULL;
155    mime.containerType = SL_CONTAINERTYPE_MPEG_TS;
156
157    audioSource.pFormat      = (void *)&mime;
158    audioSource.pLocator     = (void *)&streamLocator;
159
160    /* Setup the data sink structure */
161    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
162    locator_outputmix.outputMix    = OutputMix;
163    audioSink.pLocator           = (void *)&locator_outputmix;
164    audioSink.pFormat            = NULL;
165
166    /* Create the audio player */
167    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
168            MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
169
170    /* Realizing the player in synchronous mode. */
171    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
172    fprintf(stdout, "URI example: after Realize\n");
173
174    /* Get interfaces */
175    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf); CheckErr(res);
176
177    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf); CheckErr(res);
178
179    res = (*player)->GetInterface(player, SL_IID_ANDROIDBUFFERQUEUE, (void*)&abqItf);
180    CheckErr(res);
181
182    res = (*abqItf)->RegisterCallback(abqItf, AndroidBufferQueueCallback,
183            // context is not used in the example, but can be used to track who registered
184            // the buffer queue callback
185            NULL /*pContext*/); CheckErr(res);
186
187    /* Display duration */
188    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
189    res = (*playItf)->GetDuration(playItf, &durationInMsec);
190    CheckErr(res);
191    if (durationInMsec == SL_TIME_UNKNOWN) {
192        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
193    } else {
194        fprintf(stdout, "Content duration is %lu ms (before starting to prefetch)\n",
195                durationInMsec);
196    }
197
198    /* Set the player volume */
199    res = (*volItf)->SetVolumeLevel( volItf, 0);//-300);
200    CheckErr(res);
201
202
203    /* Play the URI */
204    /*     first cause the player to prefetch the data */
205    fprintf(stdout, "Before set to PAUSED\n");
206    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
207    fprintf(stdout, "After set to PAUSED\n");
208    CheckErr(res);
209
210    /* Fill our cache */
211    if (fread(dataCache, 1, BUFFER_SIZE * NB_BUFFERS, file) <= 0) {
212        fprintf(stderr, "Error filling cache, exiting\n");
213        goto destroyRes;
214    }
215    /* Enqueue the content of our cache before starting to play,
216         * we don't want to starve the player */
217    for (int i=0 ; i < NB_BUFFERS ; i++) {
218        res = (*abqItf)->Enqueue(abqItf, dataCache + i*BUFFER_SIZE, BUFFER_SIZE, NULL, 0);
219        CheckErr(res);
220    }
221
222#if 0   // used to test ABQ starving where only one buffer is enqueued before playback
223    /* Fill our cache */
224    if (fread(dataCache, 1, BUFFER_SIZE * 1, file) <= 0) {
225        fprintf(stderr, "Error filling cache, exiting\n");
226        goto destroyRes;
227    }
228    /* Enqueue the content of our cache before starting to play,
229         * we don't want to starve the player */
230    for (int i=0 ; i < 1 ; i++) {
231        res = (*abqItf)->Enqueue(abqItf, dataCache + i*BUFFER_SIZE, BUFFER_SIZE, NULL, 0);
232        CheckErr(res);
233    }
234#endif
235    /*     wait until there's data to play */
236    //SLpermille fillLevel = 0;
237 /*
238    SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
239    SLuint32 timeOutIndex = 2;
240    while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
241            !prefetchError) {
242        usleep(1 * 1000 * 1000); // 1s
243        //(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
244        timeOutIndex--;
245    }
246
247    if (timeOutIndex == 0 || prefetchError) {
248        fprintf(stderr, "We\'re done waiting, failed to prefetch data in time, exiting\n");
249        goto destroyRes;
250    }
251*/
252
253    /* Display duration again, */
254/*    res = (*playItf)->GetDuration(playItf, &durationInMsec);
255    CheckErr(res);
256    if (durationInMsec == SL_TIME_UNKNOWN) {
257        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
258    } else {
259        fprintf(stdout, "Content duration is %lu ms (after prefetch completed)\n", durationInMsec);
260    }
261*/
262
263    fprintf(stdout, "URI example: starting to play\n");
264    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
265    CheckErr(res);
266
267    /* Wait as long as the duration of the content before stopping */
268    fprintf(stdout, "Letting playback go on for %d sec\n", playTimeInSec);
269    usleep(playTimeInSec /*s*/ * 1000 * 1000);
270
271
272    /* Make sure player is stopped */
273    fprintf(stdout, "URI example: stopping playback\n");
274    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
275    CheckErr(res);
276
277    fprintf(stdout, "sleeping to verify playback stopped\n");
278    usleep(2 /*s*/ * 1000 * 1000);
279
280destroyRes:
281
282    /* Destroy the player */
283    (*player)->Destroy(player);
284
285    /* Destroy Output Mix object */
286    (*OutputMix)->Destroy(OutputMix);
287
288    fclose(file);
289}
290
291//-----------------------------------------------------------------
292int main(int argc, char* const argv[])
293{
294    SLresult    res;
295    SLObjectItf sl;
296
297    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf, SLAndroidBufferQueue \n",
298            argv[0]);
299    fprintf(stdout, "and AudioPlayer with SL_DATALOCATOR_ANDROIDBUFFERQUEUE source / OutputMix sink\n");
300    fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
301
302    if (argc == 1) {
303        fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
304        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
305                argv[0], argv[0]);
306        exit(EXIT_FAILURE);
307    }
308
309    SLEngineOption EngineOption[] = {
310            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
311            (SLuint32) SL_BOOLEAN_TRUE}};
312
313    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
314    CheckErr(res);
315    /* Realizing the SL Engine in synchronous mode. */
316    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
317    CheckErr(res);
318
319    TestPlayStream(sl, argv[1]);
320
321    /* Shutdown OpenSL ES */
322    (*sl)->Destroy(sl);
323
324    return EXIT_SUCCESS;
325}
326