1 /*
2 * Copyright (C) 2011 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 //#define USE_LOG SLAndroidLogLevel_Verbose
18
19 #include "sles_allinclusive.h"
20 #include "android/android_AudioSfDecoder.h"
21 #include "android/channels.h"
22
23 #include <binder/IServiceManager.h>
24 #include <datasource/DataSourceFactory.h>
25 #include <datasource/FileSource.h>
26 #include <datasource/NuCachedSource2.h>
27 #include <media/IMediaHTTPService.h>
28 #include <media/stagefright/foundation/ADebug.h>
29 #include <media/stagefright/InterfaceUtils.h>
30 #include <media/stagefright/MediaBuffer.h>
31 #include <media/stagefright/MediaExtractorFactory.h>
32 #include <media/stagefright/MetaData.h>
33 #include <media/stagefright/SimpleDecodingSource.h>
34 #include <media/stagefright/foundation/MediaDefs.h>
35
36
37 #define SIZE_CACHED_HIGH_BYTES 1000000
38 #define SIZE_CACHED_MED_BYTES 700000
39 #define SIZE_CACHED_LOW_BYTES 400000
40
41 namespace android {
42
43 //--------------------------------------------------------------------------------------------------
AudioSfDecoder(const AudioPlayback_Parameters * params)44 AudioSfDecoder::AudioSfDecoder(const AudioPlayback_Parameters* params) : GenericPlayer(params),
45 mDataSource(0),
46 mAudioSource(0),
47 mAudioSourceStarted(false),
48 mBitrate(-1),
49 mDurationUsec(ANDROID_UNKNOWN_TIME),
50 mDecodeBuffer(NULL),
51 mSeekTimeMsec(0),
52 // play event logic depends on the initial time being zero not ANDROID_UNKNOWN_TIME
53 mLastDecodedPositionUs(0)
54 {
55 SL_LOGD("AudioSfDecoder::AudioSfDecoder()");
56 }
57
58
~AudioSfDecoder()59 AudioSfDecoder::~AudioSfDecoder() {
60 SL_LOGD("AudioSfDecoder::~AudioSfDecoder()");
61 }
62
63
preDestroy()64 void AudioSfDecoder::preDestroy() {
65 GenericPlayer::preDestroy();
66 SL_LOGD("AudioSfDecoder::preDestroy()");
67 {
68 Mutex::Autolock _l(mBufferSourceLock);
69
70 if (NULL != mDecodeBuffer) {
71 mDecodeBuffer->release();
72 mDecodeBuffer = NULL;
73 }
74
75 if ((mAudioSource != 0) && mAudioSourceStarted) {
76 mAudioSource->stop();
77 mAudioSourceStarted = false;
78 }
79 }
80 }
81
82
83 //--------------------------------------------------
play()84 void AudioSfDecoder::play() {
85 SL_LOGD("AudioSfDecoder::play");
86
87 GenericPlayer::play();
88 (new AMessage(kWhatDecode, this))->post();
89 }
90
91
getPositionMsec(int * msec)92 void AudioSfDecoder::getPositionMsec(int* msec) {
93 int64_t timeUsec = getPositionUsec();
94 if (timeUsec == ANDROID_UNKNOWN_TIME) {
95 *msec = ANDROID_UNKNOWN_TIME;
96 } else {
97 *msec = timeUsec / 1000;
98 }
99 }
100
101
102 //--------------------------------------------------
getPcmFormatKeyCount() const103 uint32_t AudioSfDecoder::getPcmFormatKeyCount() const {
104 return NB_PCMMETADATA_KEYS;
105 }
106
107
108 //--------------------------------------------------
getPcmFormatKeySize(uint32_t index,uint32_t * pKeySize)109 bool AudioSfDecoder::getPcmFormatKeySize(uint32_t index, uint32_t* pKeySize) {
110 if (index >= NB_PCMMETADATA_KEYS) {
111 return false;
112 } else {
113 *pKeySize = strlen(kPcmDecodeMetadataKeys[index]) +1;
114 return true;
115 }
116 }
117
118
119 //--------------------------------------------------
getPcmFormatKeyName(uint32_t index,uint32_t keySize,char * keyName)120 bool AudioSfDecoder::getPcmFormatKeyName(uint32_t index, uint32_t keySize, char* keyName) {
121 uint32_t actualKeySize;
122 if (!getPcmFormatKeySize(index, &actualKeySize)) {
123 return false;
124 }
125 if (keySize < actualKeySize) {
126 return false;
127 }
128 strncpy(keyName, kPcmDecodeMetadataKeys[index], actualKeySize);
129 return true;
130 }
131
132
133 //--------------------------------------------------
getPcmFormatValueSize(uint32_t index,uint32_t * pValueSize)134 bool AudioSfDecoder::getPcmFormatValueSize(uint32_t index, uint32_t* pValueSize) {
135 if (index >= NB_PCMMETADATA_KEYS) {
136 *pValueSize = 0;
137 return false;
138 } else {
139 *pValueSize = sizeof(uint32_t);
140 return true;
141 }
142 }
143
144
145 //--------------------------------------------------
getPcmFormatKeyValue(uint32_t index,uint32_t size,uint32_t * pValue)146 bool AudioSfDecoder::getPcmFormatKeyValue(uint32_t index, uint32_t size, uint32_t* pValue) {
147 uint32_t valueSize = 0;
148 if (!getPcmFormatValueSize(index, &valueSize)) {
149 return false;
150 } else if (size != valueSize) {
151 // this ensures we are accessing mPcmFormatValues with a valid size for that index
152 SL_LOGE("Error retrieving metadata value at index %d: using size of %d, should be %d",
153 index, size, valueSize);
154 return false;
155 } else {
156 android::Mutex::Autolock autoLock(mPcmFormatLock);
157 *pValue = mPcmFormatValues[index];
158 return true;
159 }
160 }
161
162
163 //--------------------------------------------------
164 // Event handlers
165 // it is strictly verboten to call those methods outside of the event loop
166
167 // Initializes the data and audio sources, and update the PCM format info
168 // post-condition: upon successful initialization based on the player data locator
169 // GenericPlayer::onPrepare() was called
170 // mDataSource != 0
171 // mAudioSource != 0
172 // mAudioSourceStarted == true
173 // All error returns from this method are via notifyPrepared(status) followed by "return".
onPrepare()174 void AudioSfDecoder::onPrepare() {
175 SL_LOGD("AudioSfDecoder::onPrepare()");
176 Mutex::Autolock _l(mBufferSourceLock);
177
178 {
179 android::Mutex::Autolock autoLock(mPcmFormatLock);
180 // Initialize the PCM format info with the known parameters before the start of the decode
181 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_BITSPERSAMPLE] = SL_PCMSAMPLEFORMAT_FIXED_16;
182 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CONTAINERSIZE] = 16;
183 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_ENDIANNESS] = SL_BYTEORDER_LITTLEENDIAN;
184 // initialization with the default values: they will be replaced by the actual values
185 // once the decoder has figured them out
186 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = UNKNOWN_NUMCHANNELS;
187 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = UNKNOWN_SAMPLERATE;
188 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] = SL_ANDROID_UNKNOWN_CHANNELMASK;
189 }
190
191 //---------------------------------
192 // Instantiate and initialize the data source for the decoder
193 sp<DataSource> dataSource;
194
195 switch (mDataLocatorType) {
196
197 case kDataLocatorNone:
198 SL_LOGE("AudioSfDecoder::onPrepare: no data locator set");
199 notifyPrepared(MEDIA_ERROR_BASE);
200 return;
201
202 case kDataLocatorUri:
203 dataSource = DataSourceFactory::getInstance()->CreateFromURI(
204 NULL /* XXX httpService */, mDataLocator.uriRef);
205 if (dataSource == NULL) {
206 SL_LOGE("AudioSfDecoder::onPrepare(): Error opening %s", mDataLocator.uriRef);
207 notifyPrepared(MEDIA_ERROR_BASE);
208 return;
209 }
210 break;
211
212 case kDataLocatorFd:
213 {
214 // As FileSource unconditionally takes ownership of the fd and closes it, then
215 // we have to make a dup for FileSource if the app wants to keep ownership itself
216 int fd = mDataLocator.fdi.fd;
217 if (mDataLocator.fdi.mCloseAfterUse) {
218 mDataLocator.fdi.mCloseAfterUse = false;
219 } else {
220 fd = ::dup(fd);
221 }
222 dataSource = new FileSource(fd, mDataLocator.fdi.offset, mDataLocator.fdi.length);
223 status_t err = dataSource->initCheck();
224 if (err != OK) {
225 notifyPrepared(err);
226 return;
227 }
228 break;
229 }
230
231 // AndroidBufferQueue data source is handled by a subclass,
232 // which does not call up to this method. Hence, the missing case.
233 default:
234 TRESPASS();
235 }
236
237 //---------------------------------
238 // Instantiate and initialize the decoder attached to the data source
239 sp<IMediaExtractor> extractor = MediaExtractorFactory::Create(dataSource);
240 if (extractor == NULL) {
241 SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate extractor.");
242 notifyPrepared(ERROR_UNSUPPORTED);
243 return;
244 }
245
246 ssize_t audioTrackIndex = -1;
247 bool isRawAudio = false;
248 for (size_t i = 0; i < extractor->countTracks(); ++i) {
249 sp<MetaData> meta = extractor->getTrackMetaData(i);
250
251 const char *mime;
252 CHECK(meta->findCString(kKeyMIMEType, &mime));
253
254 if (!strncasecmp("audio/", mime, 6)) {
255 if (isSupportedCodec(mime)) {
256 audioTrackIndex = i;
257
258 if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) {
259 isRawAudio = true;
260 }
261 break;
262 }
263 }
264 }
265
266 if (audioTrackIndex < 0) {
267 SL_LOGE("AudioSfDecoder::onPrepare: Could not find a supported audio track.");
268 notifyPrepared(ERROR_UNSUPPORTED);
269 return;
270 }
271
272 sp<MediaSource> source = CreateMediaSourceFromIMediaSource(
273 extractor->getTrack(audioTrackIndex));
274 sp<MetaData> meta = source->getFormat();
275
276 // we can't trust the OMXCodec (if there is one) to issue a INFO_FORMAT_CHANGED so we want
277 // to have some meaningful values as soon as possible.
278 int32_t channelCount;
279 bool hasChannelCount = meta->findInt32(kKeyChannelCount, &channelCount);
280 int32_t sr;
281 bool hasSampleRate = meta->findInt32(kKeySampleRate, &sr);
282
283 // first compute the duration
284 off64_t size;
285 int64_t durationUs;
286 int32_t durationMsec;
287 if (dataSource->getSize(&size) == OK
288 && meta->findInt64(kKeyDuration, &durationUs)) {
289 if (durationUs != 0) {
290 mBitrate = size * 8000000LL / durationUs; // in bits/sec
291 } else {
292 mBitrate = -1;
293 }
294 mDurationUsec = durationUs;
295 durationMsec = durationUs / 1000;
296 } else {
297 mBitrate = -1;
298 mDurationUsec = ANDROID_UNKNOWN_TIME;
299 durationMsec = ANDROID_UNKNOWN_TIME;
300 }
301
302 // then assign the duration under the settings lock
303 {
304 Mutex::Autolock _l(mSettingsLock);
305 mDurationMsec = durationMsec;
306 }
307
308 // the audio content is not raw PCM, so we need a decoder
309 if (!isRawAudio) {
310 source = SimpleDecodingSource::Create(source);
311 if (source == NULL) {
312 SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate decoder.");
313 notifyPrepared(ERROR_UNSUPPORTED);
314 return;
315 }
316
317 meta = source->getFormat();
318 }
319
320
321 if (source->start() != OK) {
322 SL_LOGE("AudioSfDecoder::onPrepare: Failed to start source/decoder.");
323 notifyPrepared(MEDIA_ERROR_BASE);
324 return;
325 }
326
327 //---------------------------------
328 // The data source, and audio source (a decoder if required) are ready to be used
329 mDataSource = dataSource;
330 mAudioSource = source;
331 mAudioSourceStarted = true;
332
333 if (!hasChannelCount) {
334 CHECK(meta->findInt32(kKeyChannelCount, &channelCount));
335 }
336
337 if (!hasSampleRate) {
338 CHECK(meta->findInt32(kKeySampleRate, &sr));
339 }
340 // FIXME add code below once channel mask support is in, currently initialized to default
341 // value computed from the channel count
342 // if (!hasChannelMask) {
343 // CHECK(meta->findInt32(kKeyChannelMask, &channelMask));
344 // }
345
346 if (!wantPrefetch()) {
347 SL_LOGV("AudioSfDecoder::onPrepare: no need to prefetch");
348 // doesn't need prefetching, notify good to go
349 mCacheStatus = kStatusHigh;
350 mCacheFill = 1000;
351 notifyStatus();
352 notifyCacheFill();
353 }
354
355 {
356 android::Mutex::Autolock autoLock(mPcmFormatLock);
357 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr;
358 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount;
359 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] =
360 sles_channel_out_mask_from_count(channelCount);
361 }
362
363 // at this point we have enough information about the source to create the sink that
364 // will consume the data
365 createAudioSink();
366
367 // signal successful completion of prepare
368 mStateFlags |= kFlagPrepared;
369
370 GenericPlayer::onPrepare();
371 SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags);
372 }
373
374
onPause()375 void AudioSfDecoder::onPause() {
376 SL_LOGV("AudioSfDecoder::onPause()");
377 GenericPlayer::onPause();
378 pauseAudioSink();
379 }
380
381
onPlay()382 void AudioSfDecoder::onPlay() {
383 SL_LOGV("AudioSfDecoder::onPlay()");
384 GenericPlayer::onPlay();
385 startAudioSink();
386 }
387
388
onSeek(const sp<AMessage> & msg)389 void AudioSfDecoder::onSeek(const sp<AMessage> &msg) {
390 SL_LOGV("AudioSfDecoder::onSeek");
391 int64_t timeMsec;
392 CHECK(msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec));
393
394 Mutex::Autolock _l(mTimeLock);
395 mStateFlags |= kFlagSeeking;
396 mSeekTimeMsec = timeMsec;
397 // don't set mLastDecodedPositionUs to ANDROID_UNKNOWN_TIME; getPositionUsec
398 // ignores mLastDecodedPositionUs while seeking, and substitutes the seek goal instead
399
400 // nop for now
401 GenericPlayer::onSeek(msg);
402 }
403
404
onLoop(const sp<AMessage> & msg)405 void AudioSfDecoder::onLoop(const sp<AMessage> &msg) {
406 SL_LOGV("AudioSfDecoder::onLoop");
407 int32_t loop;
408 CHECK(msg->findInt32(WHATPARAM_LOOP_LOOPING, &loop));
409
410 if (loop) {
411 //SL_LOGV("AudioSfDecoder::onLoop start looping");
412 mStateFlags |= kFlagLooping;
413 } else {
414 //SL_LOGV("AudioSfDecoder::onLoop stop looping");
415 mStateFlags &= ~kFlagLooping;
416 }
417
418 // nop for now
419 GenericPlayer::onLoop(msg);
420 }
421
422
onCheckCache(const sp<AMessage> & msg)423 void AudioSfDecoder::onCheckCache(const sp<AMessage> &msg) {
424 //SL_LOGV("AudioSfDecoder::onCheckCache");
425 bool eos;
426 CacheStatus_t status = getCacheRemaining(&eos);
427
428 if (eos || status == kStatusHigh
429 || ((mStateFlags & kFlagPreparing) && (status >= kStatusEnough))) {
430 if (mStateFlags & kFlagPlaying) {
431 startAudioSink();
432 }
433 mStateFlags &= ~kFlagBuffering;
434
435 SL_LOGV("AudioSfDecoder::onCheckCache: buffering done.");
436
437 if (mStateFlags & kFlagPreparing) {
438 //SL_LOGV("AudioSfDecoder::onCheckCache: preparation done.");
439 mStateFlags &= ~kFlagPreparing;
440 }
441
442 if (mStateFlags & kFlagPlaying) {
443 (new AMessage(kWhatDecode, this))->post();
444 }
445 return;
446 }
447
448 msg->post(100000);
449 }
450
451
onDecode()452 void AudioSfDecoder::onDecode() {
453 SL_LOGV("AudioSfDecoder::onDecode");
454
455 //-------------------------------- Need to buffer some more before decoding?
456 bool eos;
457 if (mDataSource == 0) {
458 // application set play state to paused which failed, then set play state to playing
459 return;
460 }
461
462 if (wantPrefetch()
463 && (getCacheRemaining(&eos) == kStatusLow)
464 && !eos) {
465 SL_LOGV("buffering more.");
466
467 if (mStateFlags & kFlagPlaying) {
468 pauseAudioSink();
469 }
470 mStateFlags |= kFlagBuffering;
471 (new AMessage(kWhatCheckCache, this))->post(100000);
472 return;
473 }
474
475 if (!(mStateFlags & (kFlagPlaying | kFlagBuffering | kFlagPreparing))) {
476 // don't decode if we're not buffering, prefetching or playing
477 //SL_LOGV("don't decode: not buffering, prefetching or playing");
478 return;
479 }
480
481 //-------------------------------- Decode
482 status_t err;
483 MediaSource::ReadOptions readOptions;
484 if (mStateFlags & kFlagSeeking) {
485 assert(mSeekTimeMsec != ANDROID_UNKNOWN_TIME);
486 readOptions.setSeekTo(mSeekTimeMsec * 1000);
487 }
488
489 int64_t timeUsec = ANDROID_UNKNOWN_TIME;
490 {
491 Mutex::Autolock _l(mBufferSourceLock);
492
493 if (NULL != mDecodeBuffer) {
494 // the current decoded buffer hasn't been rendered, drop it
495 mDecodeBuffer->release();
496 mDecodeBuffer = NULL;
497 }
498 if (!mAudioSourceStarted) {
499 return;
500 }
501 err = mAudioSource->read(&mDecodeBuffer, &readOptions);
502 if (err == OK) {
503 // FIXME workaround apparent bug in AAC decoder: kKeyTime is 3 frames old if length is 0
504 if (mDecodeBuffer->range_length() == 0) {
505 timeUsec = ANDROID_UNKNOWN_TIME;
506 } else {
507 CHECK(mDecodeBuffer->meta_data().findInt64(kKeyTime, &timeUsec));
508 }
509 } else {
510 // errors are handled below
511 }
512 }
513
514 {
515 Mutex::Autolock _l(mTimeLock);
516 if (mStateFlags & kFlagSeeking) {
517 mStateFlags &= ~kFlagSeeking;
518 mSeekTimeMsec = ANDROID_UNKNOWN_TIME;
519 }
520 if (timeUsec != ANDROID_UNKNOWN_TIME) {
521 // Note that though we've decoded this position, we haven't rendered it yet.
522 // So a GetPosition called after this point will observe the advanced position,
523 // even though the PCM may not have been supplied to the sink. That's OK as
524 // we don't claim to provide AAC frame-accurate (let alone sample-accurate) GetPosition.
525 mLastDecodedPositionUs = timeUsec;
526 }
527 }
528
529 //-------------------------------- Handle return of decode
530 if (err != OK) {
531 bool continueDecoding = false;
532 switch (err) {
533 case ERROR_END_OF_STREAM:
534 if (0 < mDurationUsec) {
535 Mutex::Autolock _l(mTimeLock);
536 mLastDecodedPositionUs = mDurationUsec;
537 }
538 // handle notification and looping at end of stream
539 if (mStateFlags & kFlagPlaying) {
540 notify(PLAYEREVENT_ENDOFSTREAM, 1, true /*async*/);
541 }
542 if (mStateFlags & kFlagLooping) {
543 seek(0);
544 // kick-off decoding again
545 continueDecoding = true;
546 }
547 break;
548 case INFO_FORMAT_CHANGED:
549 SL_LOGD("MediaSource::read encountered INFO_FORMAT_CHANGED");
550 // reconfigure output
551 {
552 Mutex::Autolock _l(mBufferSourceLock);
553 hasNewDecodeParams();
554 }
555 continueDecoding = true;
556 break;
557 case INFO_DISCONTINUITY:
558 SL_LOGD("MediaSource::read encountered INFO_DISCONTINUITY");
559 continueDecoding = true;
560 break;
561 default:
562 SL_LOGE("MediaSource::read returned error %d", err);
563 break;
564 }
565 if (continueDecoding) {
566 if (NULL == mDecodeBuffer) {
567 (new AMessage(kWhatDecode, this))->post();
568 return;
569 }
570 } else {
571 return;
572 }
573 }
574
575 //-------------------------------- Render
576 sp<AMessage> msg = new AMessage(kWhatRender, this);
577 msg->post();
578
579 }
580
581
onMessageReceived(const sp<AMessage> & msg)582 void AudioSfDecoder::onMessageReceived(const sp<AMessage> &msg) {
583 switch (msg->what()) {
584 case kWhatDecode:
585 onDecode();
586 break;
587
588 case kWhatRender:
589 onRender();
590 break;
591
592 case kWhatCheckCache:
593 onCheckCache(msg);
594 break;
595
596 default:
597 GenericPlayer::onMessageReceived(msg);
598 break;
599 }
600 }
601
602 //--------------------------------------------------
603 // Prepared state, prefetch status notifications
notifyPrepared(status_t prepareRes)604 void AudioSfDecoder::notifyPrepared(status_t prepareRes) {
605 assert(!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully)));
606 if (NO_ERROR == prepareRes) {
607 // The "then" fork is not currently used, but is kept here to make it easier
608 // to replace by a new signalPrepareCompletion(status) if we re-visit this later.
609 mStateFlags |= kFlagPrepared;
610 } else {
611 mStateFlags |= kFlagPreparedUnsuccessfully;
612 }
613 // Do not call the superclass onPrepare to notify, because it uses a default error
614 // status code but we can provide a more specific one.
615 // GenericPlayer::onPrepare();
616 notify(PLAYEREVENT_PREPARED, (int32_t)prepareRes, true /*async*/);
617 SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags);
618 }
619
620
onNotify(const sp<AMessage> & msg)621 void AudioSfDecoder::onNotify(const sp<AMessage> &msg) {
622 notif_cbf_t notifyClient;
623 void* notifyUser;
624 {
625 android::Mutex::Autolock autoLock(mNotifyClientLock);
626 if (NULL == mNotifyClient) {
627 return;
628 } else {
629 notifyClient = mNotifyClient;
630 notifyUser = mNotifyUser;
631 }
632 }
633 int32_t val;
634 if (msg->findInt32(PLAYEREVENT_PREFETCHSTATUSCHANGE, &val)) {
635 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHSTATUSCHANGE, val);
636 notifyClient(kEventPrefetchStatusChange, val, 0, notifyUser);
637 }
638 else if (msg->findInt32(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, &val)) {
639 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHFILLLEVELUPDATE, val);
640 notifyClient(kEventPrefetchFillLevelUpdate, val, 0, notifyUser);
641 }
642 else if (msg->findInt32(PLAYEREVENT_ENDOFSTREAM, &val)) {
643 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_ENDOFSTREAM, val);
644 notifyClient(kEventEndOfStream, val, 0, notifyUser);
645 }
646 else {
647 GenericPlayer::onNotify(msg);
648 }
649 }
650
651
652 //--------------------------------------------------
653 // Private utility functions
654
wantPrefetch()655 bool AudioSfDecoder::wantPrefetch() {
656 if (mDataSource != 0) {
657 return (mDataSource->flags() & DataSource::kWantsPrefetching);
658 } else {
659 // happens if an improper data locator was passed, if the media extractor couldn't be
660 // initialized, if there is no audio track in the media, if the OMX decoder couldn't be
661 // instantiated, if the source couldn't be opened, or if the MediaSource
662 // couldn't be started
663 SL_LOGV("AudioSfDecoder::wantPrefetch() tries to access NULL mDataSource");
664 return false;
665 }
666 }
667
668
getPositionUsec()669 int64_t AudioSfDecoder::getPositionUsec() {
670 Mutex::Autolock _l(mTimeLock);
671 if (mStateFlags & kFlagSeeking) {
672 return mSeekTimeMsec * 1000;
673 } else {
674 return mLastDecodedPositionUs;
675 }
676 }
677
678
getCacheRemaining(bool * eos)679 CacheStatus_t AudioSfDecoder::getCacheRemaining(bool *eos) {
680 sp<NuCachedSource2> cachedSource =
681 static_cast<NuCachedSource2 *>(mDataSource.get());
682
683 CacheStatus_t oldStatus = mCacheStatus;
684
685 status_t finalStatus;
686 size_t dataRemaining = cachedSource->approxDataRemaining(&finalStatus);
687 *eos = (finalStatus != OK);
688
689 CHECK_GE(mBitrate, 0);
690
691 int64_t dataRemainingUs = dataRemaining * 8000000LL / mBitrate;
692 //SL_LOGV("AudioSfDecoder::getCacheRemaining: approx %.2f secs remaining (eos=%d)",
693 // dataRemainingUs / 1E6, *eos);
694
695 if (*eos) {
696 // data is buffered up to the end of the stream, it can't get any better than this
697 mCacheStatus = kStatusHigh;
698 mCacheFill = 1000;
699
700 } else {
701 if (mDurationUsec > 0) {
702 // known duration:
703
704 // fill level is ratio of how much has been played + how much is
705 // cached, divided by total duration
706 int64_t currentPositionUsec = getPositionUsec();
707 if (currentPositionUsec == ANDROID_UNKNOWN_TIME) {
708 // if we don't know where we are, assume the worst for the fill ratio
709 currentPositionUsec = 0;
710 }
711 if (mDurationUsec > 0) {
712 mCacheFill = (int16_t) ((1000.0
713 * (double)(currentPositionUsec + dataRemainingUs) / mDurationUsec));
714 } else {
715 mCacheFill = 0;
716 }
717 //SL_LOGV("cacheFill = %d", mCacheFill);
718
719 // cache status is evaluated against duration thresholds
720 if (dataRemainingUs > DURATION_CACHED_HIGH_MS*1000) {
721 mCacheStatus = kStatusHigh;
722 //ALOGV("high");
723 } else if (dataRemainingUs > DURATION_CACHED_MED_MS*1000) {
724 //ALOGV("enough");
725 mCacheStatus = kStatusEnough;
726 } else if (dataRemainingUs < DURATION_CACHED_LOW_MS*1000) {
727 //ALOGV("low");
728 mCacheStatus = kStatusLow;
729 } else {
730 mCacheStatus = kStatusIntermediate;
731 }
732
733 } else {
734 // unknown duration:
735
736 // cache status is evaluated against cache amount thresholds
737 // (no duration so we don't have the bitrate either, could be derived from format?)
738 if (dataRemaining > SIZE_CACHED_HIGH_BYTES) {
739 mCacheStatus = kStatusHigh;
740 } else if (dataRemaining > SIZE_CACHED_MED_BYTES) {
741 mCacheStatus = kStatusEnough;
742 } else if (dataRemaining < SIZE_CACHED_LOW_BYTES) {
743 mCacheStatus = kStatusLow;
744 } else {
745 mCacheStatus = kStatusIntermediate;
746 }
747 }
748
749 }
750
751 if (oldStatus != mCacheStatus) {
752 notifyStatus();
753 }
754
755 if (abs(mCacheFill - mLastNotifiedCacheFill) > mCacheFillNotifThreshold) {
756 notifyCacheFill();
757 }
758
759 return mCacheStatus;
760 }
761
762
hasNewDecodeParams()763 void AudioSfDecoder::hasNewDecodeParams() {
764
765 if ((mAudioSource != 0) && mAudioSourceStarted) {
766 sp<MetaData> meta = mAudioSource->getFormat();
767
768 int32_t channelCount;
769 CHECK(meta->findInt32(kKeyChannelCount, &channelCount));
770 int32_t sr;
771 CHECK(meta->findInt32(kKeySampleRate, &sr));
772
773 // FIXME similar to onPrepare()
774 {
775 android::Mutex::Autolock autoLock(mPcmFormatLock);
776 SL_LOGV("format changed: old sr=%d, channels=%d; new sr=%d, channels=%d",
777 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE],
778 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS],
779 sr, channelCount);
780 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount;
781 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr;
782 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] =
783 sles_channel_out_mask_from_count(channelCount);
784 }
785 // there's no need to do a notify of PLAYEREVENT_CHANNEL_COUNT,
786 // because the only listener is for volume updates, and decoders don't support that
787 }
788
789 // alert users of those params
790 updateAudioSink();
791 }
792
793 static const char* const kPlaybackOnlyCodecs[] = { MEDIA_MIMETYPE_AUDIO_AMR_NB,
794 MEDIA_MIMETYPE_AUDIO_AMR_WB };
795 #define NB_PLAYBACK_ONLY_CODECS (sizeof(kPlaybackOnlyCodecs)/sizeof(kPlaybackOnlyCodecs[0]))
796
isSupportedCodec(const char * mime)797 bool AudioSfDecoder::isSupportedCodec(const char* mime) {
798 bool codecRequiresPermission = false;
799 for (unsigned int i = 0 ; i < NB_PLAYBACK_ONLY_CODECS ; i++) {
800 if (!strcasecmp(mime, kPlaybackOnlyCodecs[i])) {
801 codecRequiresPermission = true;
802 break;
803 }
804 }
805 if (codecRequiresPermission) {
806 // verify only the system can decode, for playback only
807 return checkCallingPermission(
808 String16("android.permission.ALLOW_ANY_CODEC_FOR_PLAYBACK"));
809 } else {
810 return true;
811 }
812 }
813
814 } // namespace android
815