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