MediaPlayer_to_android.cpp revision f66b430471d691de4bf7b6bbc1a6527897f61cbd
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      default: {
248        SL_LOGE("Received unknown event %d, data %d from AVPlayer", event, data1);
249      }
250    }
251}
252
253
254//-----------------------------------------------------------------------------
255XAresult android_Player_checkSourceSink(CMediaPlayer *mp) {
256
257    XAresult result = XA_RESULT_SUCCESS;
258
259    const SLDataSource *pSrc    = &mp->mDataSource.u.mSource;
260    const SLDataSink *pAudioSnk = &mp->mAudioSink.u.mSink;
261
262    // format check:
263    const SLuint32 sourceLocatorType = *(SLuint32 *)pSrc->pLocator;
264    const SLuint32 sourceFormatType  = *(SLuint32 *)pSrc->pFormat;
265    const SLuint32 audioSinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
266    //const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
267
268    // Source check
269    switch(sourceLocatorType) {
270
271    case XA_DATALOCATOR_ANDROIDBUFFERQUEUE: {
272        switch (sourceFormatType) {
273        case XA_DATAFORMAT_MIME: {
274            SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pSrc->pFormat;
275            if (SL_CONTAINERTYPE_MPEG_TS != df_mime->containerType) {
276                SL_LOGE("Cannot create player with XA_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
277                        "that is not fed MPEG-2 TS data");
278                return SL_RESULT_CONTENT_UNSUPPORTED;
279            }
280        } break;
281        default:
282            SL_LOGE("Cannot create player with XA_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
283                    "without SL_DATAFORMAT_MIME format");
284            return XA_RESULT_CONTENT_UNSUPPORTED;
285        }
286    } break;
287
288    case XA_DATALOCATOR_URI: // intended fall-through
289    case XA_DATALOCATOR_ANDROIDFD:
290        break;
291
292    default:
293        SL_LOGE("Cannot create media player with data locator type 0x%x",
294                (unsigned) sourceLocatorType);
295        return SL_RESULT_PARAMETER_INVALID;
296    }// switch (locatorType)
297
298    // Audio sink check: only playback is supported here
299    switch(audioSinkLocatorType) {
300
301    case XA_DATALOCATOR_OUTPUTMIX:
302        break;
303
304    default:
305        SL_LOGE("Cannot create media player with audio sink data locator of type 0x%x",
306                (unsigned) audioSinkLocatorType);
307        return XA_RESULT_PARAMETER_INVALID;
308    }// switch (locaaudioSinkLocatorTypeorType)
309
310    return result;
311}
312
313
314//-----------------------------------------------------------------------------
315XAresult android_Player_create(CMediaPlayer *mp) {
316
317    XAresult result = XA_RESULT_SUCCESS;
318
319    // FIXME verify data source
320    const SLDataSource *pDataSrc = &mp->mDataSource.u.mSource;
321    // FIXME verify audio data sink
322    const SLDataSink *pAudioSnk = &mp->mAudioSink.u.mSink;
323    // FIXME verify image data sink
324    const SLDataSink *pVideoSnk = &mp->mImageVideoSink.u.mSink;
325
326    XAuint32 sourceLocator = *(XAuint32 *)pDataSrc->pLocator;
327    switch(sourceLocator) {
328    // FIXME support Android simple buffer queue as well
329    case XA_DATALOCATOR_ANDROIDBUFFERQUEUE:
330        mp->mAndroidObjType = AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE;
331        break;
332    case XA_DATALOCATOR_URI: // intended fall-through
333    case SL_DATALOCATOR_ANDROIDFD:
334        mp->mAndroidObjType = AUDIOVIDEOPLAYER_FROM_URIFD;
335        break;
336    case XA_DATALOCATOR_ADDRESS: // intended fall-through
337    default:
338        SL_LOGE("Unable to create MediaPlayer for data source locator 0x%x", sourceLocator);
339        result = XA_RESULT_PARAMETER_INVALID;
340        break;
341    }
342
343    // FIXME duplicates an initialization also done by higher level
344    mp->mAndroidObjState = ANDROID_UNINITIALIZED;
345    mp->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
346    mp->mSessionId = android::AudioSystem::newAudioSessionId();
347
348    mp->mCallbackProtector = new android::CallbackProtector();
349
350    return result;
351}
352
353
354//-----------------------------------------------------------------------------
355// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
356XAresult android_Player_realize(CMediaPlayer *mp, SLboolean async) {
357    SL_LOGV("android_Player_realize_l(%p)", mp);
358    XAresult result = XA_RESULT_SUCCESS;
359
360    const SLDataSource *pDataSrc = &mp->mDataSource.u.mSource;
361    const SLuint32 sourceLocator = *(SLuint32 *)pDataSrc->pLocator;
362
363    AudioPlayback_Parameters ap_params;
364    ap_params.sessionId = mp->mSessionId;
365    ap_params.streamType = mp->mStreamType;
366    ap_params.trackcb = NULL;
367    ap_params.trackcbUser = NULL;
368
369    switch(mp->mAndroidObjType) {
370    case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
371        mp->mAVPlayer = new android::StreamPlayer(&ap_params, true /*hasVideo*/,
372                &mp->mAndroidBufferQueue, mp->mCallbackProtector);
373        mp->mAVPlayer->init(player_handleMediaPlayerEventNotifications, (void*)mp);
374        }
375        break;
376    case AUDIOVIDEOPLAYER_FROM_URIFD: {
377        mp->mAVPlayer = new android::LocAVPlayer(&ap_params, true /*hasVideo*/);
378        mp->mAVPlayer->init(player_handleMediaPlayerEventNotifications, (void*)mp);
379        switch (mp->mDataSource.mLocator.mLocatorType) {
380        case XA_DATALOCATOR_URI:
381            ((android::LocAVPlayer*)mp->mAVPlayer.get())->setDataSource(
382                    (const char*)mp->mDataSource.mLocator.mURI.URI);
383            break;
384        case XA_DATALOCATOR_ANDROIDFD: {
385            int64_t offset = (int64_t)mp->mDataSource.mLocator.mFD.offset;
386            ((android::LocAVPlayer*)mp->mAVPlayer.get())->setDataSource(
387                    (int)mp->mDataSource.mLocator.mFD.fd,
388                    offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
389                            (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
390                    (int64_t)mp->mDataSource.mLocator.mFD.length);
391            }
392            break;
393        default:
394            SL_LOGE("Invalid or unsupported data locator type %u for data source",
395                    mp->mDataSource.mLocator.mLocatorType);
396            result = XA_RESULT_PARAMETER_INVALID;
397        }
398        }
399        break;
400    case INVALID_TYPE: // intended fall-through
401    default:
402        SL_LOGE("Unable to realize MediaPlayer, invalid internal Android object type");
403        result = XA_RESULT_PARAMETER_INVALID;
404        break;
405    }
406
407    if (XA_RESULT_SUCCESS == result) {
408
409        // if there is a video sink
410        if (XA_DATALOCATOR_NATIVEDISPLAY ==
411                mp->mImageVideoSink.mLocator.mLocatorType) {
412            ANativeWindow *nativeWindow = (ANativeWindow *)
413                    mp->mImageVideoSink.mLocator.mNativeDisplay.hWindow;
414            // we already verified earlier that hWindow is non-NULL
415            assert(nativeWindow != NULL);
416            result = android_Player_setNativeWindow(mp, nativeWindow);
417        }
418
419    }
420
421    return result;
422}
423
424// Called with a lock on MediaPlayer, and blocks until safe to destroy
425XAresult android_Player_preDestroy(CMediaPlayer *mp) {
426    SL_LOGV("android_Player_preDestroy(%p)", mp);
427    if (mp->mAVPlayer != 0) {
428        mp->mAVPlayer->preDestroy();
429    }
430    SL_LOGV("android_Player_preDestroy(%p) after mAVPlayer->preDestroy()", mp);
431
432    object_unlock_exclusive(&mp->mObject);
433    if (mp->mCallbackProtector != 0) {
434        mp->mCallbackProtector->requestCbExitAndWait();
435    }
436    object_lock_exclusive(&mp->mObject);
437
438    return XA_RESULT_SUCCESS;
439}
440
441//-----------------------------------------------------------------------------
442XAresult android_Player_destroy(CMediaPlayer *mp) {
443    SL_LOGV("android_Player_destroy(%p)", mp);
444
445    mp->mAVPlayer.clear();
446    mp->mCallbackProtector.clear();
447
448    // explicit destructor
449    mp->mAVPlayer.~sp();
450    mp->mCallbackProtector.~sp();
451
452    return XA_RESULT_SUCCESS;
453}
454
455
456void android_Player_usePlayEventMask(CMediaPlayer *mp) {
457    if (mp->mAVPlayer != 0) {
458        IPlay *pPlayItf = &mp->mPlay;
459        mp->mAVPlayer->setPlayEvents((int32_t) pPlayItf->mEventFlags,
460                (int32_t) pPlayItf->mMarkerPosition, (int32_t) pPlayItf->mPositionUpdatePeriod);
461    }
462}
463
464
465XAresult android_Player_getDuration(IPlay *pPlayItf, XAmillisecond *pDurMsec) {
466    CMediaPlayer *avp = (CMediaPlayer *)pPlayItf->mThis;
467
468    switch (avp->mAndroidObjType) {
469
470    case AUDIOVIDEOPLAYER_FROM_URIFD: {
471        int dur = ANDROID_UNKNOWN_TIME;
472        if (avp->mAVPlayer != 0) {
473            avp->mAVPlayer->getDurationMsec(&dur);
474        }
475        if (dur == ANDROID_UNKNOWN_TIME) {
476            *pDurMsec = XA_TIME_UNKNOWN;
477        } else {
478            *pDurMsec = (XAmillisecond)dur;
479        }
480    } break;
481
482    case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
483    default:
484        *pDurMsec = XA_TIME_UNKNOWN;
485        break;
486    }
487
488    return XA_RESULT_SUCCESS;
489}
490
491
492XAresult android_Player_getPosition(IPlay *pPlayItf, XAmillisecond *pPosMsec) {
493    SL_LOGD("android_Player_getPosition()");
494    XAresult result = XA_RESULT_SUCCESS;
495    CMediaPlayer *avp = (CMediaPlayer *)pPlayItf->mThis;
496
497    switch (avp->mAndroidObjType) {
498
499    case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
500    case AUDIOVIDEOPLAYER_FROM_URIFD: {
501        int pos = ANDROID_UNKNOWN_TIME;
502        if (avp->mAVPlayer != 0) {
503            avp->mAVPlayer->getPositionMsec(&pos);
504        }
505        if (pos == ANDROID_UNKNOWN_TIME) {
506            *pPosMsec = 0;
507        } else {
508            *pPosMsec = (XAmillisecond)pos;
509        }
510    } break;
511
512    default:
513        // we shouldn't be here
514        assert(false);
515        break;
516    }
517
518    return result;
519}
520
521
522//-----------------------------------------------------------------------------
523/**
524 * pre-condition: mp != NULL
525 */
526void android_Player_volumeUpdate(CMediaPlayer* mp)
527{
528    android::GenericPlayer* avp = mp->mAVPlayer.get();
529    if (avp != NULL) {
530        float volumes[2];
531        // MediaPlayer does not currently support EffectSend or MuteSolo
532        android_player_volumeUpdate(volumes, &mp->mVolume, mp->mNumChannels, 1.0f, NULL);
533        float leftVol = volumes[0], rightVol = volumes[1];
534        avp->setVolume(leftVol, rightVol);
535    }
536}
537
538//-----------------------------------------------------------------------------
539/**
540 * pre-condition: gp != 0
541 */
542XAresult android_Player_setPlayState(const android::sp<android::GenericPlayer> &gp,
543        SLuint32 playState,
544        AndroidObjectState* pObjState)
545{
546    XAresult result = XA_RESULT_SUCCESS;
547    AndroidObjectState objState = *pObjState;
548
549    switch (playState) {
550     case SL_PLAYSTATE_STOPPED: {
551         SL_LOGV("setting AVPlayer to SL_PLAYSTATE_STOPPED");
552         gp->stop();
553         }
554         break;
555     case SL_PLAYSTATE_PAUSED: {
556         SL_LOGV("setting AVPlayer to SL_PLAYSTATE_PAUSED");
557         switch(objState) {
558         case ANDROID_UNINITIALIZED:
559             *pObjState = ANDROID_PREPARING;
560             gp->prepare();
561             break;
562         case ANDROID_PREPARING:
563             break;
564         case ANDROID_READY:
565             gp->pause();
566             break;
567         default:
568             SL_LOGE("Android object in invalid state");
569             break;
570         }
571         }
572         break;
573     case SL_PLAYSTATE_PLAYING: {
574         SL_LOGV("setting AVPlayer to SL_PLAYSTATE_PLAYING");
575         switch(objState) {
576         case ANDROID_UNINITIALIZED:
577             *pObjState = ANDROID_PREPARING;
578             gp->prepare();
579             // intended fall through
580         case ANDROID_PREPARING:
581             // intended fall through
582         case ANDROID_READY:
583             gp->play();
584             break;
585         default:
586             SL_LOGE("Android object in invalid state");
587             break;
588         }
589         }
590         break;
591     default:
592         // checked by caller, should not happen
593         break;
594     }
595
596    return result;
597}
598
599
600/**
601 * pre-condition: mp != NULL
602 */
603XAresult android_Player_seek(CMediaPlayer *mp, SLmillisecond posMsec) {
604    XAresult result = XA_RESULT_SUCCESS;
605    switch (mp->mAndroidObjType) {
606      case AUDIOVIDEOPLAYER_FROM_URIFD:
607        if (mp->mAVPlayer !=0) {
608            mp->mAVPlayer->seek(posMsec);
609        }
610        break;
611      case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
612      default: {
613          result = XA_RESULT_FEATURE_UNSUPPORTED;
614      }
615    }
616    return result;
617}
618
619
620/**
621 * pre-condition: mp != NULL
622 */
623XAresult android_Player_loop(CMediaPlayer *mp, SLboolean loopEnable) {
624    XAresult result = XA_RESULT_SUCCESS;
625    switch (mp->mAndroidObjType) {
626      case AUDIOVIDEOPLAYER_FROM_URIFD:
627        if (mp->mAVPlayer !=0) {
628            mp->mAVPlayer->loop(loopEnable);
629        }
630        break;
631      case AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
632      default: {
633          result = XA_RESULT_FEATURE_UNSUPPORTED;
634      }
635    }
636    return result;
637}
638
639
640//-----------------------------------------------------------------------------
641void android_Player_androidBufferQueue_registerCallback_l(CMediaPlayer *mp) {
642    if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
643            && (mp->mAVPlayer != 0)) {
644        SL_LOGD("android_Player_androidBufferQueue_registerCallback_l");
645        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
646        splr->registerQueueCallback(&mp->mAndroidBufferQueue);
647    }
648}
649
650
651void android_Player_androidBufferQueue_clear_l(CMediaPlayer *mp) {
652    if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
653            && (mp->mAVPlayer != 0)) {
654        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
655        splr->appClear_l();
656    }
657}
658
659
660void android_Player_androidBufferQueue_onRefilled_l(CMediaPlayer *mp) {
661    if ((mp->mAndroidObjType == AUDIOVIDEOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE)
662            && (mp->mAVPlayer != 0)) {
663        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(mp->mAVPlayer.get());
664        splr->queueRefilled();
665    }
666}
667
668
669/*
670 *  pre-conditions:
671 *      mp != NULL
672 *      mp->mAVPlayer != 0 (player is realized)
673 *      nativeWindow can be NULL, but if NULL it is treated as an error
674 */
675SLresult android_Player_setNativeWindow(CMediaPlayer *mp, ANativeWindow *nativeWindow)
676{
677    assert(mp != NULL);
678    assert(mp->mAVPlayer != 0);
679    if (nativeWindow == NULL) {
680        SL_LOGE("ANativeWindow is NULL");
681        return SL_RESULT_PARAMETER_INVALID;
682    }
683    SLresult result;
684    int err;
685    int value;
686    // this could crash if app passes in a bad parameter, but that's OK
687    err = (*nativeWindow->query)(nativeWindow, NATIVE_WINDOW_CONCRETE_TYPE, &value);
688    if (0 != err) {
689        SL_LOGE("Query NATIVE_WINDOW_CONCRETE_TYPE on ANativeWindow * %p failed; "
690                "errno %d", nativeWindow, err);
691        result = SL_RESULT_PARAMETER_INVALID;
692    } else {
693        switch (value) {
694        case NATIVE_WINDOW_SURFACE: {                // Surface
695            SL_LOGV("Displaying on ANativeWindow of type NATIVE_WINDOW_SURFACE");
696            android::sp<android::Surface> nativeSurface(
697                    static_cast<android::Surface *>(nativeWindow));
698            mp->mAVPlayer->setVideoSurface(nativeSurface);
699            result = SL_RESULT_SUCCESS;
700            } break;
701        case NATIVE_WINDOW_SURFACE_TEXTURE_CLIENT: { // SurfaceTextureClient
702            SL_LOGV("Displaying on ANativeWindow of type NATIVE_WINDOW_SURFACE_TEXTURE_CLIENT");
703            android::sp<android::SurfaceTextureClient> surfaceTextureClient(
704                    static_cast<android::SurfaceTextureClient *>(nativeWindow));
705            android::sp<android::ISurfaceTexture> nativeSurfaceTexture(
706                    surfaceTextureClient->getISurfaceTexture());
707            mp->mAVPlayer->setVideoSurfaceTexture(nativeSurfaceTexture);
708            result = SL_RESULT_SUCCESS;
709            } break;
710        case NATIVE_WINDOW_FRAMEBUFFER:              // FramebufferNativeWindow
711            // fall through
712        default:
713            SL_LOGE("ANativeWindow * %p has unknown or unsupported concrete type %d",
714                    nativeWindow, value);
715            result = SL_RESULT_PARAMETER_INVALID;
716            break;
717        }
718    }
719    return result;
720}
721