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