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 <system/window.h>
18#include <utils/StrongPointer.h>
19#include <gui/Surface.h>
20
21#include "sles_allinclusive.h"
22#include "android_prompts.h"
23// LocAVPlayer and StreamPlayer derive from GenericMediaPlayer,
24//    so no need to #include "android_GenericMediaPlayer.h"
25#include "android_LocAVPlayer.h"
26#include "android_StreamPlayer.h"
27
28//-----------------------------------------------------------------------------
29static void player_handleMediaPlayerEventNotifications(int event, int data1, int data2, void* user)
30{
31
32    // FIXME This code is derived from similar code in sfplayer_handlePrefetchEvent.  The two
33    // versions are quite similar, but still different enough that they need to be separate.
34    // At some point they should be re-factored and merged if feasible.
35    // As with other OpenMAX AL implementation code, this copy mostly uses SL_ symbols
36    // rather than XA_ unless the difference is significant.
37
38    if (NULL == user) {
39        return;
40    }
41
42    CMediaPlayer* mp = (CMediaPlayer*) user;
43    if (!android::CallbackProtector::enterCbIfOk(mp->mCallbackProtector)) {
44        // it is not safe to enter the callback (the media player is about to go away)
45        return;
46    }
47    union {
48        char c[sizeof(int)];
49        int i;
50    } u;
51    u.i = event;
52    SL_LOGV("player_handleMediaPlayerEventNotifications(event='%c%c%c%c' (%d), data1=%d, data2=%d, "
53            "user=%p) from AVPlayer", u.c[3], u.c[2], u.c[1], u.c[0], event, data1, data2, user);
54    switch(event) {
55
56      case android::GenericPlayer::kEventPrepared: {
57        SL_LOGV("Received GenericPlayer::kEventPrepared for CMediaPlayer %p", mp);
58
59        // assume no callback
60        slPrefetchCallback callback = NULL;
61        void* callbackPContext;
62        XAuint32 events;
63
64        object_lock_exclusive(&mp->mObject);
65
66        // mark object as prepared; same state is used for successful or unsuccessful prepare
67        assert(mp->mAndroidObjState == ANDROID_PREPARING);
68        mp->mAndroidObjState = ANDROID_READY;
69
70        if (PLAYER_SUCCESS == data1) {
71            // Most of successful prepare completion for mp->mAVPlayer
72            // is handled by GenericPlayer and its subclasses.
73        } else {
74            // AVPlayer prepare() failed prefetching, there is no event in XAPrefetchStatus to
75            //  indicate a prefetch error, so we signal it by sending simultaneously two events:
76            //  - SL_PREFETCHEVENT_FILLLEVELCHANGE with a level of 0
77            //  - SL_PREFETCHEVENT_STATUSCHANGE with a status of SL_PREFETCHSTATUS_UNDERFLOW
78            SL_LOGE(ERROR_PLAYER_PREFETCH_d, data1);
79            if (IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
80                mp->mPrefetchStatus.mLevel = 0;
81                mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
82                if (!(~mp->mPrefetchStatus.mCallbackEventsMask &
83                        (SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE))) {
84                    callback = mp->mPrefetchStatus.mCallback;
85                    callbackPContext = mp->mPrefetchStatus.mContext;
86                    events = SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE;
87                }
88            }
89        }
90
91        object_unlock_exclusive(&mp->mObject);
92
93        // callback with no lock held
94        if (NULL != callback) {
95            (*callback)(&mp->mPrefetchStatus.mItf, callbackPContext, events);
96        }
97
98        break;
99      }
100
101      case android::GenericPlayer::kEventHasVideoSize: {
102        SL_LOGV("Received AVPlayer::kEventHasVideoSize (%d,%d) for CMediaPlayer %p",
103                data1, data2, mp);
104
105        object_lock_exclusive(&mp->mObject);
106
107        // remove an existing video info entry (here we only have one video stream)
108        for(size_t i=0 ; i < mp->mStreamInfo.mStreamInfoTable.size() ; i++) {
109            if (XA_DOMAINTYPE_VIDEO == mp->mStreamInfo.mStreamInfoTable.itemAt(i).domain) {
110                mp->mStreamInfo.mStreamInfoTable.removeAt(i);
111                break;
112            }
113        }
114        // update the stream information with a new video info entry
115        StreamInfo streamInfo;
116        streamInfo.domain = XA_DOMAINTYPE_VIDEO;
117        streamInfo.videoInfo.codecId = 0;// unknown, we don't have that info FIXME
118        streamInfo.videoInfo.width = (XAuint32)data1;
119        streamInfo.videoInfo.height = (XAuint32)data2;
120        streamInfo.videoInfo.bitRate = 0;// unknown, we don't have that info FIXME
121        streamInfo.videoInfo.frameRate = 0;
122        streamInfo.videoInfo.duration = XA_TIME_UNKNOWN;
123        StreamInfo &contInfo = mp->mStreamInfo.mStreamInfoTable.editItemAt(0);
124        contInfo.containerInfo.numStreams = 1;
125        ssize_t index = mp->mStreamInfo.mStreamInfoTable.add(streamInfo);
126
127        // callback is unconditional; there is no bitmask of enabled events
128        xaStreamEventChangeCallback callback = mp->mStreamInfo.mCallback;
129        void* callbackPContext = mp->mStreamInfo.mContext;
130
131        object_unlock_exclusive(&mp->mObject);
132
133        // enqueue notification (outside of lock) that the stream information has been updated
134        if ((NULL != callback) && (index >= 0)) {
135#ifndef USE_ASYNCHRONOUS_STREAMCBEVENT_PROPERTYCHANGE_CALLBACK
136            (*callback)(&mp->mStreamInfo.mItf, XA_STREAMCBEVENT_PROPERTYCHANGE /*eventId*/,
137                    1 /*streamIndex, only one stream supported here, 0 is reserved*/,
138                    NULL /*pEventData, always NULL in OpenMAX AL 1.0.1*/,
139                    callbackPContext /*pContext*/);
140#else
141            SLresult res = EnqueueAsyncCallback_piipp(mp, callback,
142                    /*p1*/ &mp->mStreamInfo.mItf,
143                    /*i1*/ XA_STREAMCBEVENT_PROPERTYCHANGE /*eventId*/,
144                    /*i2*/ 1 /*streamIndex, only one stream supported here, 0 is reserved*/,
145                    /*p2*/ NULL /*pEventData, always NULL in OpenMAX AL 1.0.1*/,
146                    /*p3*/ callbackPContext /*pContext*/);
147            ALOGW_IF(SL_RESULT_SUCCESS != res,
148                        "Callback %p(%p, XA_STREAMCBEVENT_PROPERTYCHANGE, 1, NULL, %p) dropped",
149                        callback, &mp->mStreamInfo.mItf, callbackPContext);
150#endif
151        }
152        break;
153      }
154
155      case android::GenericPlayer::kEventEndOfStream: {
156        SL_LOGV("Received AVPlayer::kEventEndOfStream for CMediaPlayer %p", mp);
157
158        object_lock_exclusive(&mp->mObject);
159        // should be xaPlayCallback but we're sharing the itf between SL and AL
160        slPlayCallback playCallback = NULL;
161        void * playContext = NULL;
162        // XAPlayItf callback or no callback?
163        if (mp->mPlay.mEventFlags & XA_PLAYEVENT_HEADATEND) {
164            playCallback = mp->mPlay.mCallback;
165            playContext = mp->mPlay.mContext;
166        }
167        mp->mPlay.mState = XA_PLAYSTATE_PAUSED;
168        object_unlock_exclusive(&mp->mObject);
169
170        // enqueue callback with no lock held
171        if (NULL != playCallback) {
172#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK
173            (*playCallback)(&mp->mPlay.mItf, playContext, XA_PLAYEVENT_HEADATEND);
174#else
175            SLresult res = EnqueueAsyncCallback_ppi(mp, playCallback, &mp->mPlay.mItf, playContext,
176                    XA_PLAYEVENT_HEADATEND);
177            ALOGW_IF(SL_RESULT_SUCCESS != res,
178                    "Callback %p(%p, %p, SL_PLAYEVENT_HEADATEND) dropped", playCallback,
179                    &mp->mPlay.mItf, playContext);
180#endif
181        }
182        break;
183      }
184
185      case android::GenericPlayer::kEventChannelCount: {
186        SL_LOGV("kEventChannelCount channels = %d", data1);
187        object_lock_exclusive(&mp->mObject);
188        if (UNKNOWN_NUMCHANNELS == mp->mNumChannels && UNKNOWN_NUMCHANNELS != data1) {
189            mp->mNumChannels = data1;
190            android_Player_volumeUpdate(mp);
191        }
192        object_unlock_exclusive(&mp->mObject);
193      }
194      break;
195
196      case android::GenericPlayer::kEventPrefetchFillLevelUpdate: {
197        SL_LOGV("kEventPrefetchFillLevelUpdate");
198        if (!IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
199            break;
200        }
201        slPrefetchCallback callback = NULL;
202        void* callbackPContext = NULL;
203
204        // SLPrefetchStatusItf callback or no callback?
205        interface_lock_exclusive(&mp->mPrefetchStatus);
206        if (mp->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
207            callback = mp->mPrefetchStatus.mCallback;
208            callbackPContext = mp->mPrefetchStatus.mContext;
209        }
210        mp->mPrefetchStatus.mLevel = (SLpermille)data1;
211        interface_unlock_exclusive(&mp->mPrefetchStatus);
212
213        // callback with no lock held
214        if (NULL != callback) {
215            (*callback)(&mp->mPrefetchStatus.mItf, callbackPContext,
216                    SL_PREFETCHEVENT_FILLLEVELCHANGE);
217        }
218      }
219      break;
220
221      case android::GenericPlayer::kEventPrefetchStatusChange: {
222        SL_LOGV("kEventPrefetchStatusChange");
223        if (!IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
224            break;
225        }
226        slPrefetchCallback callback = NULL;
227        void* callbackPContext = NULL;
228
229        // SLPrefetchStatusItf callback or no callback?
230        object_lock_exclusive(&mp->mObject);
231        if (mp->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
232            callback = mp->mPrefetchStatus.mCallback;
233            callbackPContext = mp->mPrefetchStatus.mContext;
234        }
235        if (data1 >= android::kStatusIntermediate) {
236            mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
237        } else if (data1 < android::kStatusIntermediate) {
238            mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
239        }
240        object_unlock_exclusive(&mp->mObject);
241
242        // callback with no lock held
243        if (NULL != callback) {
244            (*callback)(&mp->mPrefetchStatus.mItf, callbackPContext, SL_PREFETCHEVENT_STATUSCHANGE);
245        }
246      }
247      break;
248
249      case android::GenericPlayer::kEventPlay: {
250        SL_LOGV("kEventPlay");
251
252        interface_lock_shared(&mp->mPlay);
253        slPlayCallback callback = mp->mPlay.mCallback;
254        void* callbackPContext = mp->mPlay.mContext;
255        interface_unlock_shared(&mp->mPlay);
256
257        if (NULL != callback) {
258            (*callback)(&mp->mPlay.mItf, callbackPContext, (SLuint32) data1); // SL_PLAYEVENT_HEAD*
259        }
260      }
261      break;
262
263      case android::GenericPlayer::kEventErrorAfterPrepare: {
264        SL_LOGV("kEventErrorAfterPrepare");
265
266        // assume no callback
267        slPrefetchCallback callback = NULL;
268        void* callbackPContext = NULL;
269
270        object_lock_exclusive(&mp->mObject);
271        if (IsInterfaceInitialized(&mp->mObject, MPH_XAPREFETCHSTATUS)) {
272            mp->mPrefetchStatus.mLevel = 0;
273            mp->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
274            if (!(~mp->mPrefetchStatus.mCallbackEventsMask &
275                    (SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE))) {
276                callback = mp->mPrefetchStatus.mCallback;
277                callbackPContext = mp->mPrefetchStatus.mContext;
278            }
279        }
280        object_unlock_exclusive(&mp->mObject);
281
282        // FIXME there's interesting information in data1, but no API to convey it to client
283        SL_LOGE("Error after prepare: %d", data1);
284
285        // callback with no lock held
286        if (NULL != callback) {
287            (*callback)(&mp->mPrefetchStatus.mItf, callbackPContext,
288                    SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
289        }
290
291      }
292      break;
293
294      default: {
295        SL_LOGE("Received unknown event %d, data %d from AVPlayer", event, data1);
296      }
297    }
298
299    mp->mCallbackProtector->exitCb();
300}
301
302
303//-----------------------------------------------------------------------------
304XAresult android_Player_checkSourceSink(CMediaPlayer *mp) {
305
306    XAresult result = XA_RESULT_SUCCESS;
307
308    const SLDataSource *pSrc    = &mp->mDataSource.u.mSource;
309    const SLDataSink *pAudioSnk = &mp->mAudioSink.u.mSink;
310
311    // format check:
312    const SLuint32 sourceLocatorType = *(SLuint32 *)pSrc->pLocator;
313    const SLuint32 sourceFormatType  = *(SLuint32 *)pSrc->pFormat;
314    const SLuint32 audioSinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
315    //const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
316
317    // Source check
318    switch(sourceLocatorType) {
319
320    case XA_DATALOCATOR_ANDROIDBUFFERQUEUE: {
321        switch (sourceFormatType) {
322        case XA_DATAFORMAT_MIME: {
323            SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pSrc->pFormat;
324            if (SL_CONTAINERTYPE_MPEG_TS != df_mime->containerType) {
325                SL_LOGE("Cannot create player with XA_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
326                        "that is not fed MPEG-2 TS data");
327                return SL_RESULT_CONTENT_UNSUPPORTED;
328            }
329        } break;
330        default:
331            SL_LOGE("Cannot create player with XA_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
332                    "without SL_DATAFORMAT_MIME format");
333            return XA_RESULT_CONTENT_UNSUPPORTED;
334        }
335    } break;
336
337    case XA_DATALOCATOR_URI: // intended fall-through
338    case XA_DATALOCATOR_ANDROIDFD:
339        break;
340
341    default:
342        SL_LOGE("Cannot create media player with data locator type 0x%x",
343                (unsigned) sourceLocatorType);
344        return SL_RESULT_PARAMETER_INVALID;
345    }// switch (locatorType)
346
347    // Audio sink check: only playback is supported here
348    switch(audioSinkLocatorType) {
349
350    case XA_DATALOCATOR_OUTPUTMIX:
351        break;
352
353    default:
354        SL_LOGE("Cannot create media player with audio sink data locator of type 0x%x",
355                (unsigned) audioSinkLocatorType);
356        return XA_RESULT_PARAMETER_INVALID;
357    }// switch (locaaudioSinkLocatorTypeorType)
358
359    return result;
360}
361
362
363//-----------------------------------------------------------------------------
364XAresult android_Player_create(CMediaPlayer *mp) {
365
366    XAresult result = XA_RESULT_SUCCESS;
367
368    // FIXME verify data source
369    const SLDataSource *pDataSrc = &mp->mDataSource.u.mSource;
370    // FIXME verify audio data sink
371    const SLDataSink *pAudioSnk = &mp->mAudioSink.u.mSink;
372    // FIXME verify image data sink
373    const SLDataSink *pVideoSnk = &mp->mImageVideoSink.u.mSink;
374
375    XAuint32 sourceLocator = *(XAuint32 *)pDataSrc->pLocator;
376    switch(sourceLocator) {
377    // FIXME support Android simple buffer queue as well
378    case XA_DATALOCATOR_ANDROIDBUFFERQUEUE:
379        mp->mAndroidObjType = AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE;
380        break;
381    case XA_DATALOCATOR_URI: // intended fall-through
382    case SL_DATALOCATOR_ANDROIDFD:
383        mp->mAndroidObjType = AUDIOVIDEOPLAYER_FROM_URIFD;
384        break;
385    case XA_DATALOCATOR_ADDRESS: // intended fall-through
386    default:
387        mp->mAndroidObjType = INVALID_TYPE;
388        SL_LOGE("Unable to create MediaPlayer for data source locator 0x%x", sourceLocator);
389        result = XA_RESULT_PARAMETER_INVALID;
390        break;
391    }
392
393    // FIXME duplicates an initialization also done by higher level
394    mp->mAndroidObjState = ANDROID_UNINITIALIZED;
395    mp->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
396    mp->mSessionId = android::AudioSystem::newAudioSessionId();
397
398    // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
399    // android::AudioSystem::acquireAudioSessionId(mp->mSessionId);
400
401    mp->mCallbackProtector = new android::CallbackProtector();
402
403    return result;
404}
405
406
407//-----------------------------------------------------------------------------
408// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
409XAresult android_Player_realize(CMediaPlayer *mp, SLboolean async) {
410    SL_LOGV("android_Player_realize_l(%p)", mp);
411    XAresult result = XA_RESULT_SUCCESS;
412
413    const SLDataSource *pDataSrc = &mp->mDataSource.u.mSource;
414    const SLuint32 sourceLocator = *(SLuint32 *)pDataSrc->pLocator;
415
416    AudioPlayback_Parameters ap_params;
417    ap_params.sessionId = mp->mSessionId;
418    ap_params.streamType = mp->mStreamType;
419
420    switch(mp->mAndroidObjType) {
421    case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
422        mp->mAVPlayer = new android::StreamPlayer(&ap_params, true /*hasVideo*/,
423                &mp->mAndroidBufferQueue, mp->mCallbackProtector);
424        mp->mAVPlayer->init(player_handleMediaPlayerEventNotifications, (void*)mp);
425        }
426        break;
427    case AUDIOVIDEOPLAYER_FROM_URIFD: {
428        mp->mAVPlayer = new android::LocAVPlayer(&ap_params, true /*hasVideo*/);
429        mp->mAVPlayer->init(player_handleMediaPlayerEventNotifications, (void*)mp);
430        switch (mp->mDataSource.mLocator.mLocatorType) {
431        case XA_DATALOCATOR_URI:
432            ((android::LocAVPlayer*)mp->mAVPlayer.get())->setDataSource(
433                    (const char*)mp->mDataSource.mLocator.mURI.URI);
434            break;
435        case XA_DATALOCATOR_ANDROIDFD: {
436            int64_t offset = (int64_t)mp->mDataSource.mLocator.mFD.offset;
437            ((android::LocAVPlayer*)mp->mAVPlayer.get())->setDataSource(
438                    (int)mp->mDataSource.mLocator.mFD.fd,
439                    offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
440                            (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
441                    (int64_t)mp->mDataSource.mLocator.mFD.length);
442            }
443            break;
444        default:
445            SL_LOGE("Invalid or unsupported data locator type %u for data source",
446                    mp->mDataSource.mLocator.mLocatorType);
447            result = XA_RESULT_PARAMETER_INVALID;
448        }
449        }
450        break;
451    case INVALID_TYPE: // intended fall-through
452    default:
453        SL_LOGE("Unable to realize MediaPlayer, invalid internal Android object type");
454        result = XA_RESULT_PARAMETER_INVALID;
455        break;
456    }
457
458    if (XA_RESULT_SUCCESS == result) {
459
460        // if there is a video sink
461        if (XA_DATALOCATOR_NATIVEDISPLAY ==
462                mp->mImageVideoSink.mLocator.mLocatorType) {
463            ANativeWindow *nativeWindow = (ANativeWindow *)
464                    mp->mImageVideoSink.mLocator.mNativeDisplay.hWindow;
465            // we already verified earlier that hWindow is non-NULL
466            assert(nativeWindow != NULL);
467            result = android_Player_setNativeWindow(mp, nativeWindow);
468        }
469
470    }
471
472    return result;
473}
474
475// Called with a lock on MediaPlayer, and blocks until safe to destroy
476XAresult android_Player_preDestroy(CMediaPlayer *mp) {
477    SL_LOGV("android_Player_preDestroy(%p)", mp);
478
479    // Not yet clear why this order is important, but it reduces detected deadlocks
480    object_unlock_exclusive(&mp->mObject);
481    if (mp->mCallbackProtector != 0) {
482        mp->mCallbackProtector->requestCbExitAndWait();
483    }
484    object_lock_exclusive(&mp->mObject);
485
486    if (mp->mAVPlayer != 0) {
487        mp->mAVPlayer->preDestroy();
488    }
489    SL_LOGV("android_Player_preDestroy(%p) after mAVPlayer->preDestroy()", mp);
490
491    return XA_RESULT_SUCCESS;
492}
493
494//-----------------------------------------------------------------------------
495XAresult android_Player_destroy(CMediaPlayer *mp) {
496    SL_LOGV("android_Player_destroy(%p)", mp);
497
498    mp->mAVPlayer.clear();
499
500    // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
501    // android::AudioSystem::releaseAudioSessionId(mp->mSessionId);
502
503    mp->mCallbackProtector.clear();
504
505    // explicit destructor
506    mp->mAVPlayer.~sp();
507    mp->mCallbackProtector.~sp();
508
509    return XA_RESULT_SUCCESS;
510}
511
512
513void android_Player_usePlayEventMask(CMediaPlayer *mp) {
514    if (mp->mAVPlayer != 0) {
515        IPlay *pPlayItf = &mp->mPlay;
516        mp->mAVPlayer->setPlayEvents((int32_t) pPlayItf->mEventFlags,
517                (int32_t) pPlayItf->mMarkerPosition, (int32_t) pPlayItf->mPositionUpdatePeriod);
518    }
519}
520
521
522XAresult android_Player_getDuration(IPlay *pPlayItf, XAmillisecond *pDurMsec) {
523    CMediaPlayer *avp = (CMediaPlayer *)pPlayItf->mThis;
524
525    switch (avp->mAndroidObjType) {
526
527    case AUDIOVIDEOPLAYER_FROM_URIFD: {
528        int dur = ANDROID_UNKNOWN_TIME;
529        if (avp->mAVPlayer != 0) {
530            avp->mAVPlayer->getDurationMsec(&dur);
531        }
532        if (dur == ANDROID_UNKNOWN_TIME) {
533            *pDurMsec = XA_TIME_UNKNOWN;
534        } else {
535            *pDurMsec = (XAmillisecond)dur;
536        }
537    } break;
538
539    case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
540    default:
541        *pDurMsec = XA_TIME_UNKNOWN;
542        break;
543    }
544
545    return XA_RESULT_SUCCESS;
546}
547
548
549XAresult android_Player_getPosition(IPlay *pPlayItf, XAmillisecond *pPosMsec) {
550    SL_LOGD("android_Player_getPosition()");
551    XAresult result = XA_RESULT_SUCCESS;
552    CMediaPlayer *avp = (CMediaPlayer *)pPlayItf->mThis;
553
554    switch (avp->mAndroidObjType) {
555
556    case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
557    case AUDIOVIDEOPLAYER_FROM_URIFD: {
558        int pos = ANDROID_UNKNOWN_TIME;
559        if (avp->mAVPlayer != 0) {
560            avp->mAVPlayer->getPositionMsec(&pos);
561        }
562        if (pos == ANDROID_UNKNOWN_TIME) {
563            *pPosMsec = 0;
564        } else {
565            *pPosMsec = (XAmillisecond)pos;
566        }
567    } break;
568
569    default:
570        // we shouldn't be here
571        assert(false);
572        break;
573    }
574
575    return result;
576}
577
578
579//-----------------------------------------------------------------------------
580/**
581 * pre-condition: mp != NULL
582 */
583void android_Player_volumeUpdate(CMediaPlayer* mp)
584{
585    android::GenericPlayer* avp = mp->mAVPlayer.get();
586    if (avp != NULL) {
587        float volumes[2];
588        // MediaPlayer does not currently support EffectSend or MuteSolo
589        android_player_volumeUpdate(volumes, &mp->mVolume, mp->mNumChannels, 1.0f, NULL);
590        float leftVol = volumes[0], rightVol = volumes[1];
591        avp->setVolume(leftVol, rightVol);
592    }
593}
594
595//-----------------------------------------------------------------------------
596/**
597 * pre-condition: gp != 0
598 */
599XAresult android_Player_setPlayState(const android::sp<android::GenericPlayer> &gp,
600        SLuint32 playState,
601        AndroidObjectState* pObjState)
602{
603    XAresult result = XA_RESULT_SUCCESS;
604    AndroidObjectState objState = *pObjState;
605
606    switch (playState) {
607     case SL_PLAYSTATE_STOPPED: {
608         SL_LOGV("setting AVPlayer to SL_PLAYSTATE_STOPPED");
609         gp->stop();
610         }
611         break;
612     case SL_PLAYSTATE_PAUSED: {
613         SL_LOGV("setting AVPlayer to SL_PLAYSTATE_PAUSED");
614         switch(objState) {
615         case ANDROID_UNINITIALIZED:
616             *pObjState = ANDROID_PREPARING;
617             gp->prepare();
618             break;
619         case ANDROID_PREPARING:
620             break;
621         case ANDROID_READY:
622             gp->pause();
623             break;
624         default:
625             SL_LOGE("Android object in invalid state");
626             break;
627         }
628         }
629         break;
630     case SL_PLAYSTATE_PLAYING: {
631         SL_LOGV("setting AVPlayer to SL_PLAYSTATE_PLAYING");
632         switch(objState) {
633         case ANDROID_UNINITIALIZED:
634             *pObjState = ANDROID_PREPARING;
635             gp->prepare();
636             // intended fall through
637         case ANDROID_PREPARING:
638             // intended fall through
639         case ANDROID_READY:
640             gp->play();
641             break;
642         default:
643             SL_LOGE("Android object in invalid state");
644             break;
645         }
646         }
647         break;
648     default:
649         // checked by caller, should not happen
650         break;
651     }
652
653    return result;
654}
655
656
657/**
658 * pre-condition: mp != NULL
659 */
660XAresult android_Player_seek(CMediaPlayer *mp, SLmillisecond posMsec) {
661    XAresult result = XA_RESULT_SUCCESS;
662    switch (mp->mAndroidObjType) {
663      case AUDIOVIDEOPLAYER_FROM_URIFD:
664        if (mp->mAVPlayer !=0) {
665            mp->mAVPlayer->seek(posMsec);
666        }
667        break;
668      case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
669      default: {
670          result = XA_RESULT_FEATURE_UNSUPPORTED;
671      }
672    }
673    return result;
674}
675
676
677/**
678 * pre-condition: mp != NULL
679 */
680XAresult android_Player_loop(CMediaPlayer *mp, SLboolean loopEnable) {
681    XAresult result = XA_RESULT_SUCCESS;
682    switch (mp->mAndroidObjType) {
683      case AUDIOVIDEOPLAYER_FROM_URIFD:
684        if (mp->mAVPlayer !=0) {
685            mp->mAVPlayer->loop(loopEnable);
686        }
687        break;
688      case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
689      default: {
690          result = XA_RESULT_FEATURE_UNSUPPORTED;
691      }
692    }
693    return result;
694}
695
696
697//-----------------------------------------------------------------------------
698void android_Player_androidBufferQueue_clear_l(CMediaPlayer *mp) {
699    if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
700            && (mp->mAVPlayer != 0)) {
701        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
702        splr->appClear_l();
703    }
704}
705
706
707void android_Player_androidBufferQueue_onRefilled_l(CMediaPlayer *mp) {
708    if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
709            && (mp->mAVPlayer != 0)) {
710        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
711        splr->queueRefilled();
712    }
713}
714
715
716/*
717 *  pre-conditions:
718 *      mp != NULL
719 *      mp->mAVPlayer != 0 (player is realized)
720 *      nativeWindow can be NULL, but if NULL it is treated as an error
721 */
722SLresult android_Player_setNativeWindow(CMediaPlayer *mp, ANativeWindow *nativeWindow)
723{
724    assert(mp != NULL);
725    assert(mp->mAVPlayer != 0);
726    if (nativeWindow == NULL) {
727        SL_LOGE("ANativeWindow is NULL");
728        return SL_RESULT_PARAMETER_INVALID;
729    }
730    SLresult result;
731    int err;
732    int value;
733    // this could crash if app passes in a bad parameter, but that's OK
734    err = (*nativeWindow->query)(nativeWindow, NATIVE_WINDOW_CONCRETE_TYPE, &value);
735    if (0 != err) {
736        SL_LOGE("Query NATIVE_WINDOW_CONCRETE_TYPE on ANativeWindow * %p failed; "
737                "errno %d", nativeWindow, err);
738        result = SL_RESULT_PARAMETER_INVALID;
739    } else {
740        switch (value) {
741        case NATIVE_WINDOW_SURFACE: { // Surface
742            SL_LOGV("Displaying on ANativeWindow of type NATIVE_WINDOW_SURFACE");
743            android::sp<android::Surface> surface(
744                    static_cast<android::Surface *>(nativeWindow));
745            android::sp<android::IGraphicBufferProducer> nativeSurfaceTexture(
746                    surface->getIGraphicBufferProducer());
747            mp->mAVPlayer->setVideoSurfaceTexture(nativeSurfaceTexture);
748            result = SL_RESULT_SUCCESS;
749            } break;
750        case NATIVE_WINDOW_FRAMEBUFFER:              // FramebufferNativeWindow
751            // fall through
752        default:
753            SL_LOGE("ANativeWindow * %p has unknown or unsupported concrete type %d",
754                    nativeWindow, value);
755            result = SL_RESULT_PARAMETER_INVALID;
756            break;
757        }
758    }
759    return result;
760}
761