slesTestSlowDownUri.cpp revision 85b1ba5dfb402b1acbfa516776d946769ccb8ffd
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#include <assert.h>
18#include <pthread.h>
19#include <stdlib.h>
20#include <stdio.h>
21#include <string.h>
22#include <unistd.h>
23#include <sys/time.h>
24
25#include <SLES/OpenSLES.h>
26
27
28#define MAX_NUMBER_INTERFACES 3
29
30#define REPETITIONS 4  // 4 repetitions, but will stop the looping before the end
31
32#define INITIAL_RATE 2000 // 2x normal playback speed
33
34// These are extensions to OpenSL ES 1.0.1 values
35
36#define SL_PREFETCHSTATUS_UNKNOWN 0
37#define SL_PREFETCHSTATUS_ERROR   (-1)
38
39// Mutex and condition shared with main program to protect prefetch_status
40
41static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
42static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
43SLuint32 prefetch_status = SL_PREFETCHSTATUS_UNKNOWN;
44
45/* used to detect errors likely to have occured when the OpenSL ES framework fails to open
46 * a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond.
47 */
48#define PREFETCHEVENT_ERROR_CANDIDATE \
49        (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
50
51//-----------------------------------------------------------------
52//* Exits the application if an error is encountered */
53#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
54
55void ExitOnErrorFunc( SLresult result , int line)
56{
57    if (SL_RESULT_SUCCESS != result) {
58        fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
59        exit(EXIT_FAILURE);
60    }
61}
62
63//-----------------------------------------------------------------
64/* PlayItf callback for an audio player */
65void PlayEventCallback( SLPlayItf caller,  void *pContext, SLuint32 event)
66{
67    fprintf(stdout, "PlayEventCallback event = ");
68    if (event & SL_PLAYEVENT_HEADATEND) {
69        fprintf(stdout, "SL_PLAYEVENT_HEADATEND \n");
70        /* slow playback down by 2x for next loop,  if possible */
71        SLpermille minRate, maxRate, stepSize, rate = 1000;
72        SLuint32 capa;
73        assert(NULL != pContext);
74        SLPlaybackRateItf pRateItf = (SLPlaybackRateItf)pContext;
75        SLresult res = (*pRateItf)->GetRate(pRateItf, &rate); CheckErr(res);
76        res = (*pRateItf)->GetRateRange(pRateItf, 0, &minRate, &maxRate, &stepSize, &capa);
77        CheckErr(res);
78        fprintf(stdout, "old rate = %d, minRate=%d, maxRate=%d\n", rate, minRate, maxRate);
79        rate /= 2;
80        if (rate < minRate) {
81            rate = minRate;
82        }
83        fprintf(stdout, "new rate = %d\n", rate);
84        res = (*pRateItf)->SetRate(pRateItf, rate); CheckErr(res);
85        if (res == SL_RESULT_FEATURE_UNSUPPORTED) {
86            fprintf(stderr, "new playback rate %d per mille is unsupported\n", rate);
87        } else {
88            CheckErr(res);
89        }
90    }
91    if (event & SL_PLAYEVENT_HEADATMARKER) {
92        fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER ");
93    }
94    if (event & SL_PLAYEVENT_HEADATNEWPOS) {
95        fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS ");
96    }
97    if (event & SL_PLAYEVENT_HEADMOVING) {
98        fprintf(stdout, "SL_PLAYEVENT_HEADMOVING ");
99    }
100    if (event & SL_PLAYEVENT_HEADSTALLED) {
101        fprintf(stdout, "SL_PLAYEVENT_HEADSTALLED");
102    }
103    fprintf(stdout, "\n");
104}
105
106//-----------------------------------------------------------------
107/* PrefetchStatusItf callback for an audio player */
108void PrefetchEventCallback( SLPrefetchStatusItf caller,  void *pContext, SLuint32 event)
109{
110    //fprintf(stdout, "\t\tPrefetchEventCallback: received event %u\n", event);
111    SLresult result;
112    assert(pContext == NULL);
113    SLpermille level = 0;
114    result = (*caller)->GetFillLevel(caller, &level);
115    CheckErr(result);
116    SLuint32 status;
117    result = (*caller)->GetPrefetchStatus(caller, &status);
118    CheckErr(result);
119    if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
120        fprintf(stdout, "\t\tPrefetchEventCallback: Buffer fill level is = %d\n", level);
121    }
122    if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
123        fprintf(stdout, "\t\tPrefetchEventCallback: Prefetch Status is = %u\n", status);
124    }
125    SLuint32 new_prefetch_status;
126    if ((event & PREFETCHEVENT_ERROR_CANDIDATE) == PREFETCHEVENT_ERROR_CANDIDATE
127            && level == 0 && status == SL_PREFETCHSTATUS_UNDERFLOW) {
128        fprintf(stdout, "\t\tPrefetchEventCallback: Error while prefetching data, exiting\n");
129        new_prefetch_status = SL_PREFETCHSTATUS_ERROR;
130    } else if (event == SL_PREFETCHEVENT_STATUSCHANGE &&
131            status == SL_PREFETCHSTATUS_SUFFICIENTDATA) {
132        new_prefetch_status = status;
133    } else {
134        return;
135    }
136    int ok;
137    ok = pthread_mutex_lock(&mutex);
138    assert(ok == 0);
139    prefetch_status = new_prefetch_status;
140    ok = pthread_cond_signal(&cond);
141    assert(ok == 0);
142    ok = pthread_mutex_unlock(&mutex);
143    assert(ok == 0);
144}
145
146// Display rate capabilities in a nicely formatted way
147
148void printCapabilities(SLuint32 capabilities)
149{
150    bool needBar = false;
151    printf("0x%x (", capabilities);
152#define _(x)                             \
153    if (capabilities & SL_RATEPROP_##x) { \
154        if (needBar)                     \
155            printf("|");                 \
156        printf("SL_RATEPROP_" #x);        \
157        needBar = true;                  \
158        capabilities &= ~SL_RATEPROP_##x; \
159    }
160    _(SILENTAUDIO)
161    _(STAGGEREDAUDIO)
162    _(NOPITCHCORAUDIO)
163    _(PITCHCORAUDIO)
164    if (capabilities != 0) {
165        if (needBar)
166            printf("|");
167        printf("0x%x", capabilities);
168        needBar = true;
169    }
170    if (!needBar)
171        printf("N/A");
172    printf(")");
173}
174
175//-----------------------------------------------------------------
176
177/* Play some music from a URI  */
178void TestSlowDownUri( SLObjectItf sl, const char* path)
179{
180    SLEngineItf                EngineItf;
181
182    SLint32                    numOutputs = 0;
183    SLuint32                   deviceID = 0;
184
185    SLresult                   res;
186
187    SLDataSource               audioSource;
188    SLDataLocator_URI          uri;
189    SLDataFormat_MIME          mime;
190
191    SLDataSink                 audioSink;
192    SLDataLocator_OutputMix    locator_outputmix;
193
194    SLObjectItf                player;
195    SLPlayItf                  playItf;
196    SLSeekItf                  seekItf;
197    SLPrefetchStatusItf        prefetchItf;
198    SLPlaybackRateItf          rateItf;
199
200    SLObjectItf                OutputMix;
201
202    SLboolean required[MAX_NUMBER_INTERFACES];
203    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
204
205    /* Get the SL Engine Interface which is implicit */
206    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);   CheckErr(res);
207
208    /* Initialize arrays required[] and iidArray[] */
209    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
210        required[i] = SL_BOOLEAN_FALSE;
211        iidArray[i] = SL_IID_NULL;
212    }
213
214    required[0] = SL_BOOLEAN_TRUE;
215    iidArray[0] = SL_IID_VOLUME;
216    // Create Output Mix object to be used by player
217    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
218            iidArray, required);  CheckErr(res);
219
220    // Realizing the Output Mix object in synchronous mode.
221    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);  CheckErr(res);
222
223    /* Setup the data source structure for the URI */
224    uri.locatorType = SL_DATALOCATOR_URI;
225    uri.URI         =  (SLchar*) path;
226    mime.formatType    = SL_DATAFORMAT_MIME;
227    mime.mimeType      = (SLchar*)NULL;
228    mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
229
230    audioSource.pFormat  = (void *)&mime;
231    audioSource.pLocator = (void *)&uri;
232
233    /* Setup the data sink structure */
234    locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
235    locator_outputmix.outputMix   = OutputMix;
236    audioSink.pLocator            = (void *)&locator_outputmix;
237    audioSink.pFormat             = NULL;
238
239    /******************************************************/
240    /* Create the audio player */
241    required[0] = SL_BOOLEAN_TRUE;
242    iidArray[0] = SL_IID_SEEK;
243    required[1] = SL_BOOLEAN_TRUE;
244    iidArray[1] = SL_IID_PREFETCHSTATUS;
245    required[2] = SL_BOOLEAN_TRUE;
246    iidArray[2] = SL_IID_PLAYBACKRATE;
247    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
248            MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
249
250    /* Realizing the player in synchronous mode. */
251    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
252    fprintf(stdout, "URI example: after Realize\n");
253
254    /* Get interfaces */
255    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);  CheckErr(res);
256
257    res = (*player)->GetInterface(player, SL_IID_SEEK,  (void*)&seekItf);  CheckErr(res);
258
259    res = (*player)->GetInterface(player, SL_IID_PLAYBACKRATE, (void*)&rateItf);  CheckErr(res);
260
261    res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
262    CheckErr(res);
263    res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, NULL);
264    CheckErr(res);
265    res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
266            SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);  CheckErr(res);
267
268    /* Configure fill level updates every 5 percent */
269    (*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50);  CheckErr(res);
270
271    /* Display duration */
272    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
273    res = (*playItf)->GetDuration(playItf, &durationInMsec);  CheckErr(res);
274    if (durationInMsec == SL_TIME_UNKNOWN) {
275        fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
276    } else {
277        fprintf(stdout, "Content duration is %u ms (before starting to prefetch)\n",
278                durationInMsec);
279    }
280
281    /* Loop on the whole of the content */
282    res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_TRUE, 0, SL_TIME_UNKNOWN);  CheckErr(res);
283
284    /* Set up marker and position callbacks */
285    res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, (void *) rateItf);
286            CheckErr(res);
287    res = (*playItf)->SetCallbackEventsMask(playItf,
288            SL_PLAYEVENT_HEADATEND | SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS);
289    res = (*playItf)->SetMarkerPosition(playItf, 1500); CheckErr(res);
290    res = (*playItf)->SetPositionUpdatePeriod(playItf, 500); CheckErr(res);
291
292    /* Get the default rate */
293    SLpermille rate = 1234;
294    res = (*rateItf)->GetRate(rateItf, &rate); CheckErr(res);
295    printf("default rate = %d per mille\n", rate);
296    assert(1000 == rate);
297
298    /* Get the default rate properties */
299    SLuint32 properties = 0;
300    res = (*rateItf)->GetProperties(rateItf, &properties); CheckErr(res);
301    printf("default rate properties: ");
302    printCapabilities(properties);
303    printf("\n");
304    assert(SL_RATEPROP_NOPITCHCORAUDIO == properties);
305
306    /* Get all supported playback rate ranges */
307    SLuint8 index;
308    for (index = 0; ; ++index) {
309        SLpermille minRate, maxRate, stepSize;
310        SLuint32 capabilities;
311        res = (*rateItf)->GetRateRange(rateItf, index, &minRate, &maxRate, &stepSize,
312                &capabilities);
313        if (res == SL_RESULT_PARAMETER_INVALID) {
314            if (index == 0) {
315                fprintf(stderr, "implementation supports no rate ranges\n");
316            }
317            break;
318        }
319        CheckErr(res);
320        if (index == 255) {
321            fprintf(stderr, "implementation supports way too many rate ranges, I'm giving up\n");
322            break;
323        }
324        printf("range[%u]: min=%d, max=%d, capabilities=", index, minRate, maxRate);
325        printCapabilities(capabilities);
326        printf("\n");
327    }
328
329    /* Change the playback rate before playback */
330    res = (*rateItf)->SetRate(rateItf, INITIAL_RATE);
331    if (res == SL_RESULT_FEATURE_UNSUPPORTED || res == SL_RESULT_PARAMETER_INVALID) {
332        fprintf(stderr, "initial playback rate %d per mille is unsupported\n", INITIAL_RATE);
333    } else {
334        CheckErr(res);
335    }
336
337    /******************************************************/
338    /* Play the URI */
339    /*     first cause the player to prefetch the data */
340    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED ); CheckErr(res);
341
342    // wait for prefetch status callback to indicate either sufficient data or error
343    pthread_mutex_lock(&mutex);
344    while (prefetch_status == SL_PREFETCHSTATUS_UNKNOWN) {
345        pthread_cond_wait(&cond, &mutex);
346    }
347    pthread_mutex_unlock(&mutex);
348    if (prefetch_status == SL_PREFETCHSTATUS_ERROR) {
349        fprintf(stderr, "Error during prefetch, exiting\n");
350        goto destroyRes;
351    }
352
353    /* Display duration again, */
354    res = (*playItf)->GetDuration(playItf, &durationInMsec); CheckErr(res);
355    if (durationInMsec == SL_TIME_UNKNOWN) {
356        fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
357    } else {
358        fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
359    }
360
361    /* Start playing */
362    fprintf(stdout, "starting to play\n");
363    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING ); CheckErr(res);
364
365    /* Wait as long as the duration of the content, times the repetitions,
366     * before stopping the loop */
367#if 1
368    usleep( (REPETITIONS-1) * durationInMsec * 1100);
369#else
370    int ii;
371    for (ii = 0; ii < REPETITIONS; ++ii) {
372        usleep(durationInMsec * 1100);
373        PlayEventCallback(playItf, (void *) rateItf, SL_PLAYEVENT_HEADATEND);
374    }
375#endif
376
377    res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_FALSE, 0, SL_TIME_UNKNOWN); CheckErr(res);
378    fprintf(stdout, "As of now, stopped looping (sound shouldn't repeat from now on)\n");
379    /* wait some more to make sure it doesn't repeat */
380    usleep(durationInMsec * 1000);
381
382    /* Stop playback */
383    fprintf(stdout, "stopping playback\n");
384    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); CheckErr(res);
385
386destroyRes:
387
388    /* Destroy the player */
389    (*player)->Destroy(player);
390
391    /* Destroy Output Mix object */
392    (*OutputMix)->Destroy(OutputMix);
393}
394
395//-----------------------------------------------------------------
396int main(int argc, char* const argv[])
397{
398    SLresult    res;
399    SLObjectItf sl;
400
401    fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLSeekItf, SLPlaybackRateItf\n",
402            argv[0]);
403    fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
404    fprintf(stdout, "Plays a sound and loops it %d times while changing the \n", REPETITIONS);
405    fprintf(stdout, "playback rate each time.\n\n");
406
407    if (argc == 1) {
408        fprintf(stdout, "Usage: \n\t%s path \n\t%s url\n", argv[0], argv[0]);
409        fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"  or \"%s file:///sdcard/my.mp3\"\n",
410                argv[0], argv[0]);
411        return EXIT_FAILURE;
412    }
413
414    SLEngineOption EngineOption[] = {
415            {(SLuint32) SL_ENGINEOPTION_THREADSAFE,
416            (SLuint32) SL_BOOLEAN_TRUE}};
417
418    res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
419    CheckErr(res);
420    /* Realizing the SL Engine in synchronous mode. */
421    res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
422    CheckErr(res);
423
424    TestSlowDownUri(sl, argv[1]);
425
426    /* Shutdown OpenSL ES */
427    (*sl)->Destroy(sl);
428
429    return EXIT_SUCCESS;
430}
431