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