1 /*
2 **
3 ** Copyright 2008, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 ** http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 // Proxy for media player implementations
19
20 //#define LOG_NDEBUG 0
21 #define LOG_TAG "MediaPlayerService"
22 #include <utils/Log.h>
23
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/time.h>
27 #include <dirent.h>
28 #include <unistd.h>
29
30 #include <string.h>
31
32 #include <cutils/atomic.h>
33 #include <cutils/properties.h> // for property_get
34
35 #include <utils/misc.h>
36
37 #include <android_runtime/ActivityManager.h>
38
39 #include <binder/IPCThreadState.h>
40 #include <binder/IServiceManager.h>
41 #include <binder/MemoryHeapBase.h>
42 #include <binder/MemoryBase.h>
43 #include <gui/SurfaceTextureClient.h>
44 #include <utils/Errors.h> // for status_t
45 #include <utils/String8.h>
46 #include <utils/SystemClock.h>
47 #include <utils/Vector.h>
48 #include <cutils/properties.h>
49
50 #include <media/MediaPlayerInterface.h>
51 #include <media/mediarecorder.h>
52 #include <media/MediaMetadataRetrieverInterface.h>
53 #include <media/Metadata.h>
54 #include <media/AudioTrack.h>
55 #include <media/MemoryLeakTrackUtil.h>
56 #include <media/stagefright/MediaErrors.h>
57
58 #include <system/audio.h>
59
60 #include <private/android_filesystem_config.h>
61
62 #include "MediaRecorderClient.h"
63 #include "MediaPlayerService.h"
64 #include "MetadataRetrieverClient.h"
65
66 #include "MidiFile.h"
67 #include "TestPlayerStub.h"
68 #include "StagefrightPlayer.h"
69 #include "nuplayer/NuPlayerDriver.h"
70
71 #include <OMX.h>
72
73 namespace {
74 using android::media::Metadata;
75 using android::status_t;
76 using android::OK;
77 using android::BAD_VALUE;
78 using android::NOT_ENOUGH_DATA;
79 using android::Parcel;
80
81 // Max number of entries in the filter.
82 const int kMaxFilterSize = 64; // I pulled that out of thin air.
83
84 // FIXME: Move all the metadata related function in the Metadata.cpp
85
86
87 // Unmarshall a filter from a Parcel.
88 // Filter format in a parcel:
89 //
90 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
91 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92 // | number of entries (n) |
93 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94 // | metadata type 1 |
95 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96 // | metadata type 2 |
97 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98 // ....
99 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100 // | metadata type n |
101 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102 //
103 // @param p Parcel that should start with a filter.
104 // @param[out] filter On exit contains the list of metadata type to be
105 // filtered.
106 // @param[out] status On exit contains the status code to be returned.
107 // @return true if the parcel starts with a valid filter.
unmarshallFilter(const Parcel & p,Metadata::Filter * filter,status_t * status)108 bool unmarshallFilter(const Parcel& p,
109 Metadata::Filter *filter,
110 status_t *status)
111 {
112 int32_t val;
113 if (p.readInt32(&val) != OK)
114 {
115 LOGE("Failed to read filter's length");
116 *status = NOT_ENOUGH_DATA;
117 return false;
118 }
119
120 if( val > kMaxFilterSize || val < 0)
121 {
122 LOGE("Invalid filter len %d", val);
123 *status = BAD_VALUE;
124 return false;
125 }
126
127 const size_t num = val;
128
129 filter->clear();
130 filter->setCapacity(num);
131
132 size_t size = num * sizeof(Metadata::Type);
133
134
135 if (p.dataAvail() < size)
136 {
137 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
138 *status = NOT_ENOUGH_DATA;
139 return false;
140 }
141
142 const Metadata::Type *data =
143 static_cast<const Metadata::Type*>(p.readInplace(size));
144
145 if (NULL == data)
146 {
147 LOGE("Filter had no data");
148 *status = BAD_VALUE;
149 return false;
150 }
151
152 // TODO: The stl impl of vector would be more efficient here
153 // because it degenerates into a memcpy on pod types. Try to
154 // replace later or use stl::set.
155 for (size_t i = 0; i < num; ++i)
156 {
157 filter->add(*data);
158 ++data;
159 }
160 *status = OK;
161 return true;
162 }
163
164 // @param filter Of metadata type.
165 // @param val To be searched.
166 // @return true if a match was found.
findMetadata(const Metadata::Filter & filter,const int32_t val)167 bool findMetadata(const Metadata::Filter& filter, const int32_t val)
168 {
169 // Deal with empty and ANY right away
170 if (filter.isEmpty()) return false;
171 if (filter[0] == Metadata::kAny) return true;
172
173 return filter.indexOf(val) >= 0;
174 }
175
176 } // anonymous namespace
177
178
179 namespace android {
180
checkPermission(const char * permissionString)181 static bool checkPermission(const char* permissionString) {
182 #ifndef HAVE_ANDROID_OS
183 return true;
184 #endif
185 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
186 bool ok = checkCallingPermission(String16(permissionString));
187 if (!ok) LOGE("Request requires %s", permissionString);
188 return ok;
189 }
190
191 // TODO: Temp hack until we can register players
192 typedef struct {
193 const char *extension;
194 const player_type playertype;
195 } extmap;
196 extmap FILE_EXTS [] = {
197 {".mid", SONIVOX_PLAYER},
198 {".midi", SONIVOX_PLAYER},
199 {".smf", SONIVOX_PLAYER},
200 {".xmf", SONIVOX_PLAYER},
201 {".imy", SONIVOX_PLAYER},
202 {".rtttl", SONIVOX_PLAYER},
203 {".rtx", SONIVOX_PLAYER},
204 {".ota", SONIVOX_PLAYER},
205 };
206
207 // TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
208 /* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
209 /* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
210
instantiate()211 void MediaPlayerService::instantiate() {
212 defaultServiceManager()->addService(
213 String16("media.player"), new MediaPlayerService());
214 }
215
MediaPlayerService()216 MediaPlayerService::MediaPlayerService()
217 {
218 LOGV("MediaPlayerService created");
219 mNextConnId = 1;
220
221 mBatteryAudio.refCount = 0;
222 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
223 mBatteryAudio.deviceOn[i] = 0;
224 mBatteryAudio.lastTime[i] = 0;
225 mBatteryAudio.totalTime[i] = 0;
226 }
227 // speaker is on by default
228 mBatteryAudio.deviceOn[SPEAKER] = 1;
229 }
230
~MediaPlayerService()231 MediaPlayerService::~MediaPlayerService()
232 {
233 LOGV("MediaPlayerService destroyed");
234 }
235
createMediaRecorder(pid_t pid)236 sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
237 {
238 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
239 wp<MediaRecorderClient> w = recorder;
240 Mutex::Autolock lock(mLock);
241 mMediaRecorderClients.add(w);
242 LOGV("Create new media recorder client from pid %d", pid);
243 return recorder;
244 }
245
removeMediaRecorderClient(wp<MediaRecorderClient> client)246 void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
247 {
248 Mutex::Autolock lock(mLock);
249 mMediaRecorderClients.remove(client);
250 LOGV("Delete media recorder client");
251 }
252
createMetadataRetriever(pid_t pid)253 sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
254 {
255 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
256 LOGV("Create new media retriever from pid %d", pid);
257 return retriever;
258 }
259
create(pid_t pid,const sp<IMediaPlayerClient> & client,int audioSessionId)260 sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
261 int audioSessionId)
262 {
263 int32_t connId = android_atomic_inc(&mNextConnId);
264
265 sp<Client> c = new Client(
266 this, pid, connId, client, audioSessionId,
267 IPCThreadState::self()->getCallingUid());
268
269 LOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
270 IPCThreadState::self()->getCallingUid());
271
272 wp<Client> w = c;
273 {
274 Mutex::Autolock lock(mLock);
275 mClients.add(w);
276 }
277 return c;
278 }
279
getOMX()280 sp<IOMX> MediaPlayerService::getOMX() {
281 Mutex::Autolock autoLock(mLock);
282
283 if (mOMX.get() == NULL) {
284 mOMX = new OMX;
285 }
286
287 return mOMX;
288 }
289
dump(int fd,const Vector<String16> & args) const290 status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
291 {
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
295
296 result.append(" AudioCache\n");
297 if (mHeap != 0) {
298 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
299 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
300 result.append(buffer);
301 }
302 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
303 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
304 result.append(buffer);
305 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
306 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
307 result.append(buffer);
308 ::write(fd, result.string(), result.size());
309 return NO_ERROR;
310 }
311
dump(int fd,const Vector<String16> & args) const312 status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
313 {
314 const size_t SIZE = 256;
315 char buffer[SIZE];
316 String8 result;
317
318 result.append(" AudioOutput\n");
319 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
320 mStreamType, mLeftVolume, mRightVolume);
321 result.append(buffer);
322 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
323 mMsecsPerFrame, mLatency);
324 result.append(buffer);
325 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
326 mAuxEffectId, mSendLevel);
327 result.append(buffer);
328
329 ::write(fd, result.string(), result.size());
330 if (mTrack != 0) {
331 mTrack->dump(fd, args);
332 }
333 return NO_ERROR;
334 }
335
dump(int fd,const Vector<String16> & args) const336 status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
337 {
338 const size_t SIZE = 256;
339 char buffer[SIZE];
340 String8 result;
341 result.append(" Client\n");
342 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
343 mPid, mConnId, mStatus, mLoop?"true": "false");
344 result.append(buffer);
345 write(fd, result.string(), result.size());
346 if (mPlayer != NULL) {
347 mPlayer->dump(fd, args);
348 }
349 if (mAudioOutput != 0) {
350 mAudioOutput->dump(fd, args);
351 }
352 write(fd, "\n", 1);
353 return NO_ERROR;
354 }
355
dump(int fd,const Vector<String16> & args)356 status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
357 {
358 const size_t SIZE = 256;
359 char buffer[SIZE];
360 String8 result;
361 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
362 snprintf(buffer, SIZE, "Permission Denial: "
363 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
364 IPCThreadState::self()->getCallingPid(),
365 IPCThreadState::self()->getCallingUid());
366 result.append(buffer);
367 } else {
368 Mutex::Autolock lock(mLock);
369 for (int i = 0, n = mClients.size(); i < n; ++i) {
370 sp<Client> c = mClients[i].promote();
371 if (c != 0) c->dump(fd, args);
372 }
373 if (mMediaRecorderClients.size() == 0) {
374 result.append(" No media recorder client\n\n");
375 } else {
376 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
377 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
378 if (c != 0) {
379 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
380 result.append(buffer);
381 write(fd, result.string(), result.size());
382 result = "\n";
383 c->dump(fd, args);
384 }
385 }
386 }
387
388 result.append(" Files opened and/or mapped:\n");
389 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
390 FILE *f = fopen(buffer, "r");
391 if (f) {
392 while (!feof(f)) {
393 fgets(buffer, SIZE, f);
394 if (strstr(buffer, " /mnt/sdcard/") ||
395 strstr(buffer, " /system/sounds/") ||
396 strstr(buffer, " /data/") ||
397 strstr(buffer, " /system/media/")) {
398 result.append(" ");
399 result.append(buffer);
400 }
401 }
402 fclose(f);
403 } else {
404 result.append("couldn't open ");
405 result.append(buffer);
406 result.append("\n");
407 }
408
409 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
410 DIR *d = opendir(buffer);
411 if (d) {
412 struct dirent *ent;
413 while((ent = readdir(d)) != NULL) {
414 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
415 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
416 struct stat s;
417 if (lstat(buffer, &s) == 0) {
418 if ((s.st_mode & S_IFMT) == S_IFLNK) {
419 char linkto[256];
420 int len = readlink(buffer, linkto, sizeof(linkto));
421 if(len > 0) {
422 if(len > 255) {
423 linkto[252] = '.';
424 linkto[253] = '.';
425 linkto[254] = '.';
426 linkto[255] = 0;
427 } else {
428 linkto[len] = 0;
429 }
430 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
431 strstr(linkto, "/system/sounds/") == linkto ||
432 strstr(linkto, "/data/") == linkto ||
433 strstr(linkto, "/system/media/") == linkto) {
434 result.append(" ");
435 result.append(buffer);
436 result.append(" -> ");
437 result.append(linkto);
438 result.append("\n");
439 }
440 }
441 } else {
442 result.append(" unexpected type for ");
443 result.append(buffer);
444 result.append("\n");
445 }
446 }
447 }
448 }
449 closedir(d);
450 } else {
451 result.append("couldn't open ");
452 result.append(buffer);
453 result.append("\n");
454 }
455
456 bool dumpMem = false;
457 for (size_t i = 0; i < args.size(); i++) {
458 if (args[i] == String16("-m")) {
459 dumpMem = true;
460 }
461 }
462 if (dumpMem) {
463 dumpMemoryAddresses(fd);
464 }
465 }
466 write(fd, result.string(), result.size());
467 return NO_ERROR;
468 }
469
removeClient(wp<Client> client)470 void MediaPlayerService::removeClient(wp<Client> client)
471 {
472 Mutex::Autolock lock(mLock);
473 mClients.remove(client);
474 }
475
Client(const sp<MediaPlayerService> & service,pid_t pid,int32_t connId,const sp<IMediaPlayerClient> & client,int audioSessionId,uid_t uid)476 MediaPlayerService::Client::Client(
477 const sp<MediaPlayerService>& service, pid_t pid,
478 int32_t connId, const sp<IMediaPlayerClient>& client,
479 int audioSessionId, uid_t uid)
480 {
481 LOGV("Client(%d) constructor", connId);
482 mPid = pid;
483 mConnId = connId;
484 mService = service;
485 mClient = client;
486 mLoop = false;
487 mStatus = NO_INIT;
488 mAudioSessionId = audioSessionId;
489 mUID = uid;
490
491 #if CALLBACK_ANTAGONIZER
492 LOGD("create Antagonizer");
493 mAntagonizer = new Antagonizer(notify, this);
494 #endif
495 }
496
~Client()497 MediaPlayerService::Client::~Client()
498 {
499 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
500 mAudioOutput.clear();
501 wp<Client> client(this);
502 disconnect();
503 mService->removeClient(client);
504 }
505
disconnect()506 void MediaPlayerService::Client::disconnect()
507 {
508 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
509 // grab local reference and clear main reference to prevent future
510 // access to object
511 sp<MediaPlayerBase> p;
512 {
513 Mutex::Autolock l(mLock);
514 p = mPlayer;
515 }
516 mClient.clear();
517
518 mPlayer.clear();
519
520 // clear the notification to prevent callbacks to dead client
521 // and reset the player. We assume the player will serialize
522 // access to itself if necessary.
523 if (p != 0) {
524 p->setNotifyCallback(0, 0);
525 #if CALLBACK_ANTAGONIZER
526 LOGD("kill Antagonizer");
527 mAntagonizer->kill();
528 #endif
529 p->reset();
530 }
531
532 disconnectNativeWindow();
533
534 IPCThreadState::self()->flushCommands();
535 }
536
getDefaultPlayerType()537 static player_type getDefaultPlayerType() {
538 return STAGEFRIGHT_PLAYER;
539 }
540
getPlayerType(int fd,int64_t offset,int64_t length)541 player_type getPlayerType(int fd, int64_t offset, int64_t length)
542 {
543 char buf[20];
544 lseek(fd, offset, SEEK_SET);
545 read(fd, buf, sizeof(buf));
546 lseek(fd, offset, SEEK_SET);
547
548 long ident = *((long*)buf);
549
550 // Ogg vorbis?
551 if (ident == 0x5367674f) // 'OggS'
552 return STAGEFRIGHT_PLAYER;
553
554 // Some kind of MIDI?
555 EAS_DATA_HANDLE easdata;
556 if (EAS_Init(&easdata) == EAS_SUCCESS) {
557 EAS_FILE locator;
558 locator.path = NULL;
559 locator.fd = fd;
560 locator.offset = offset;
561 locator.length = length;
562 EAS_HANDLE eashandle;
563 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
564 EAS_CloseFile(easdata, eashandle);
565 EAS_Shutdown(easdata);
566 return SONIVOX_PLAYER;
567 }
568 EAS_Shutdown(easdata);
569 }
570
571 return getDefaultPlayerType();
572 }
573
getPlayerType(const char * url)574 player_type getPlayerType(const char* url)
575 {
576 if (TestPlayerStub::canBeUsed(url)) {
577 return TEST_PLAYER;
578 }
579
580 if (!strncasecmp("http://", url, 7)
581 || !strncasecmp("https://", url, 8)) {
582 size_t len = strlen(url);
583 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
584 return NU_PLAYER;
585 }
586
587 if (strstr(url,"m3u8")) {
588 return NU_PLAYER;
589 }
590 }
591
592 // use MidiFile for MIDI extensions
593 int lenURL = strlen(url);
594 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
595 int len = strlen(FILE_EXTS[i].extension);
596 int start = lenURL - len;
597 if (start > 0) {
598 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
599 return FILE_EXTS[i].playertype;
600 }
601 }
602 }
603
604 return getDefaultPlayerType();
605 }
606
createPlayer(player_type playerType,void * cookie,notify_callback_f notifyFunc)607 static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
608 notify_callback_f notifyFunc)
609 {
610 sp<MediaPlayerBase> p;
611 switch (playerType) {
612 case SONIVOX_PLAYER:
613 LOGV(" create MidiFile");
614 p = new MidiFile();
615 break;
616 case STAGEFRIGHT_PLAYER:
617 LOGV(" create StagefrightPlayer");
618 p = new StagefrightPlayer;
619 break;
620 case NU_PLAYER:
621 LOGV(" create NuPlayer");
622 p = new NuPlayerDriver;
623 break;
624 case TEST_PLAYER:
625 LOGV("Create Test Player stub");
626 p = new TestPlayerStub();
627 break;
628 default:
629 LOGE("Unknown player type: %d", playerType);
630 return NULL;
631 }
632 if (p != NULL) {
633 if (p->initCheck() == NO_ERROR) {
634 p->setNotifyCallback(cookie, notifyFunc);
635 } else {
636 p.clear();
637 }
638 }
639 if (p == NULL) {
640 LOGE("Failed to create player object");
641 }
642 return p;
643 }
644
createPlayer(player_type playerType)645 sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
646 {
647 // determine if we have the right player type
648 sp<MediaPlayerBase> p = mPlayer;
649 if ((p != NULL) && (p->playerType() != playerType)) {
650 LOGV("delete player");
651 p.clear();
652 }
653 if (p == NULL) {
654 p = android::createPlayer(playerType, this, notify);
655 }
656
657 if (p != NULL) {
658 p->setUID(mUID);
659 }
660
661 return p;
662 }
663
setDataSource(const char * url,const KeyedVector<String8,String8> * headers)664 status_t MediaPlayerService::Client::setDataSource(
665 const char *url, const KeyedVector<String8, String8> *headers)
666 {
667 LOGV("setDataSource(%s)", url);
668 if (url == NULL)
669 return UNKNOWN_ERROR;
670
671 if ((strncmp(url, "http://", 7) == 0) ||
672 (strncmp(url, "https://", 8) == 0) ||
673 (strncmp(url, "rtsp://", 7) == 0)) {
674 if (!checkPermission("android.permission.INTERNET")) {
675 return PERMISSION_DENIED;
676 }
677 }
678
679 if (strncmp(url, "content://", 10) == 0) {
680 // get a filedescriptor for the content Uri and
681 // pass it to the setDataSource(fd) method
682
683 String16 url16(url);
684 int fd = android::openContentProviderFile(url16);
685 if (fd < 0)
686 {
687 LOGE("Couldn't open fd for %s", url);
688 return UNKNOWN_ERROR;
689 }
690 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
691 close(fd);
692 return mStatus;
693 } else {
694 player_type playerType = getPlayerType(url);
695 LOGV("player type = %d", playerType);
696
697 // create the right type of player
698 sp<MediaPlayerBase> p = createPlayer(playerType);
699 if (p == NULL) return NO_INIT;
700
701 if (!p->hardwareOutput()) {
702 mAudioOutput = new AudioOutput(mAudioSessionId);
703 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
704 }
705
706 // now set data source
707 LOGV(" setDataSource");
708 mStatus = p->setDataSource(url, headers);
709 if (mStatus == NO_ERROR) {
710 mPlayer = p;
711 } else {
712 LOGE(" error: %d", mStatus);
713 }
714 return mStatus;
715 }
716 }
717
setDataSource(int fd,int64_t offset,int64_t length)718 status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
719 {
720 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
721 struct stat sb;
722 int ret = fstat(fd, &sb);
723 if (ret != 0) {
724 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
725 return UNKNOWN_ERROR;
726 }
727
728 LOGV("st_dev = %llu", sb.st_dev);
729 LOGV("st_mode = %u", sb.st_mode);
730 LOGV("st_uid = %lu", sb.st_uid);
731 LOGV("st_gid = %lu", sb.st_gid);
732 LOGV("st_size = %llu", sb.st_size);
733
734 if (offset >= sb.st_size) {
735 LOGE("offset error");
736 ::close(fd);
737 return UNKNOWN_ERROR;
738 }
739 if (offset + length > sb.st_size) {
740 length = sb.st_size - offset;
741 LOGV("calculated length = %lld", length);
742 }
743
744 player_type playerType = getPlayerType(fd, offset, length);
745 LOGV("player type = %d", playerType);
746
747 // create the right type of player
748 sp<MediaPlayerBase> p = createPlayer(playerType);
749 if (p == NULL) return NO_INIT;
750
751 if (!p->hardwareOutput()) {
752 mAudioOutput = new AudioOutput(mAudioSessionId);
753 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
754 }
755
756 // now set data source
757 mStatus = p->setDataSource(fd, offset, length);
758 if (mStatus == NO_ERROR) mPlayer = p;
759
760 return mStatus;
761 }
762
setDataSource(const sp<IStreamSource> & source)763 status_t MediaPlayerService::Client::setDataSource(
764 const sp<IStreamSource> &source) {
765 // create the right type of player
766 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
767
768 if (p == NULL) {
769 return NO_INIT;
770 }
771
772 if (!p->hardwareOutput()) {
773 mAudioOutput = new AudioOutput(mAudioSessionId);
774 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
775 }
776
777 // now set data source
778 mStatus = p->setDataSource(source);
779
780 if (mStatus == OK) {
781 mPlayer = p;
782 }
783
784 return mStatus;
785 }
786
setVideoSurface(const sp<Surface> & surface)787 status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
788 {
789 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
790 sp<MediaPlayerBase> p = getPlayer();
791 if (p == 0) return UNKNOWN_ERROR;
792 return p->setVideoSurface(surface);
793 }
794
disconnectNativeWindow()795 void MediaPlayerService::Client::disconnectNativeWindow() {
796 if (mConnectedWindow != NULL) {
797 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
798 NATIVE_WINDOW_API_MEDIA);
799
800 if (err != OK) {
801 LOGW("native_window_api_disconnect returned an error: %s (%d)",
802 strerror(-err), err);
803 }
804 }
805 mConnectedWindow.clear();
806 }
807
setVideoSurfaceTexture(const sp<ISurfaceTexture> & surfaceTexture)808 status_t MediaPlayerService::Client::setVideoSurfaceTexture(
809 const sp<ISurfaceTexture>& surfaceTexture)
810 {
811 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
812 sp<MediaPlayerBase> p = getPlayer();
813 if (p == 0) return UNKNOWN_ERROR;
814
815 sp<IBinder> binder(surfaceTexture == NULL ? NULL :
816 surfaceTexture->asBinder());
817 if (mConnectedWindowBinder == binder) {
818 return OK;
819 }
820
821 sp<ANativeWindow> anw;
822 if (surfaceTexture != NULL) {
823 anw = new SurfaceTextureClient(surfaceTexture);
824 status_t err = native_window_api_connect(anw.get(),
825 NATIVE_WINDOW_API_MEDIA);
826
827 if (err != OK) {
828 LOGE("setVideoSurfaceTexture failed: %d", err);
829 // Note that we must do the reset before disconnecting from the ANW.
830 // Otherwise queue/dequeue calls could be made on the disconnected
831 // ANW, which may result in errors.
832 reset();
833
834 disconnectNativeWindow();
835
836 return err;
837 }
838 }
839
840 // Note that we must set the player's new SurfaceTexture before
841 // disconnecting the old one. Otherwise queue/dequeue calls could be made
842 // on the disconnected ANW, which may result in errors.
843 status_t err = p->setVideoSurfaceTexture(surfaceTexture);
844
845 disconnectNativeWindow();
846
847 mConnectedWindow = anw;
848
849 if (err == OK) {
850 mConnectedWindowBinder = binder;
851 } else {
852 disconnectNativeWindow();
853 }
854
855 return err;
856 }
857
invoke(const Parcel & request,Parcel * reply)858 status_t MediaPlayerService::Client::invoke(const Parcel& request,
859 Parcel *reply)
860 {
861 sp<MediaPlayerBase> p = getPlayer();
862 if (p == NULL) return UNKNOWN_ERROR;
863 return p->invoke(request, reply);
864 }
865
866 // This call doesn't need to access the native player.
setMetadataFilter(const Parcel & filter)867 status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
868 {
869 status_t status;
870 media::Metadata::Filter allow, drop;
871
872 if (unmarshallFilter(filter, &allow, &status) &&
873 unmarshallFilter(filter, &drop, &status)) {
874 Mutex::Autolock lock(mLock);
875
876 mMetadataAllow = allow;
877 mMetadataDrop = drop;
878 }
879 return status;
880 }
881
getMetadata(bool update_only,bool apply_filter,Parcel * reply)882 status_t MediaPlayerService::Client::getMetadata(
883 bool update_only, bool apply_filter, Parcel *reply)
884 {
885 sp<MediaPlayerBase> player = getPlayer();
886 if (player == 0) return UNKNOWN_ERROR;
887
888 status_t status;
889 // Placeholder for the return code, updated by the caller.
890 reply->writeInt32(-1);
891
892 media::Metadata::Filter ids;
893
894 // We don't block notifications while we fetch the data. We clear
895 // mMetadataUpdated first so we don't lose notifications happening
896 // during the rest of this call.
897 {
898 Mutex::Autolock lock(mLock);
899 if (update_only) {
900 ids = mMetadataUpdated;
901 }
902 mMetadataUpdated.clear();
903 }
904
905 media::Metadata metadata(reply);
906
907 metadata.appendHeader();
908 status = player->getMetadata(ids, reply);
909
910 if (status != OK) {
911 metadata.resetParcel();
912 LOGE("getMetadata failed %d", status);
913 return status;
914 }
915
916 // FIXME: Implement filtering on the result. Not critical since
917 // filtering takes place on the update notifications already. This
918 // would be when all the metadata are fetch and a filter is set.
919
920 // Everything is fine, update the metadata length.
921 metadata.updateLength();
922 return OK;
923 }
924
prepareAsync()925 status_t MediaPlayerService::Client::prepareAsync()
926 {
927 LOGV("[%d] prepareAsync", mConnId);
928 sp<MediaPlayerBase> p = getPlayer();
929 if (p == 0) return UNKNOWN_ERROR;
930 status_t ret = p->prepareAsync();
931 #if CALLBACK_ANTAGONIZER
932 LOGD("start Antagonizer");
933 if (ret == NO_ERROR) mAntagonizer->start();
934 #endif
935 return ret;
936 }
937
start()938 status_t MediaPlayerService::Client::start()
939 {
940 LOGV("[%d] start", mConnId);
941 sp<MediaPlayerBase> p = getPlayer();
942 if (p == 0) return UNKNOWN_ERROR;
943 p->setLooping(mLoop);
944 return p->start();
945 }
946
stop()947 status_t MediaPlayerService::Client::stop()
948 {
949 LOGV("[%d] stop", mConnId);
950 sp<MediaPlayerBase> p = getPlayer();
951 if (p == 0) return UNKNOWN_ERROR;
952 return p->stop();
953 }
954
pause()955 status_t MediaPlayerService::Client::pause()
956 {
957 LOGV("[%d] pause", mConnId);
958 sp<MediaPlayerBase> p = getPlayer();
959 if (p == 0) return UNKNOWN_ERROR;
960 return p->pause();
961 }
962
isPlaying(bool * state)963 status_t MediaPlayerService::Client::isPlaying(bool* state)
964 {
965 *state = false;
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 *state = p->isPlaying();
969 LOGV("[%d] isPlaying: %d", mConnId, *state);
970 return NO_ERROR;
971 }
972
getCurrentPosition(int * msec)973 status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
974 {
975 LOGV("getCurrentPosition");
976 sp<MediaPlayerBase> p = getPlayer();
977 if (p == 0) return UNKNOWN_ERROR;
978 status_t ret = p->getCurrentPosition(msec);
979 if (ret == NO_ERROR) {
980 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
981 } else {
982 LOGE("getCurrentPosition returned %d", ret);
983 }
984 return ret;
985 }
986
getDuration(int * msec)987 status_t MediaPlayerService::Client::getDuration(int *msec)
988 {
989 LOGV("getDuration");
990 sp<MediaPlayerBase> p = getPlayer();
991 if (p == 0) return UNKNOWN_ERROR;
992 status_t ret = p->getDuration(msec);
993 if (ret == NO_ERROR) {
994 LOGV("[%d] getDuration = %d", mConnId, *msec);
995 } else {
996 LOGE("getDuration returned %d", ret);
997 }
998 return ret;
999 }
1000
seekTo(int msec)1001 status_t MediaPlayerService::Client::seekTo(int msec)
1002 {
1003 LOGV("[%d] seekTo(%d)", mConnId, msec);
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 return p->seekTo(msec);
1007 }
1008
reset()1009 status_t MediaPlayerService::Client::reset()
1010 {
1011 LOGV("[%d] reset", mConnId);
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 return p->reset();
1015 }
1016
setAudioStreamType(int type)1017 status_t MediaPlayerService::Client::setAudioStreamType(int type)
1018 {
1019 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1020 // TODO: for hardware output, call player instead
1021 Mutex::Autolock l(mLock);
1022 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1023 return NO_ERROR;
1024 }
1025
setLooping(int loop)1026 status_t MediaPlayerService::Client::setLooping(int loop)
1027 {
1028 LOGV("[%d] setLooping(%d)", mConnId, loop);
1029 mLoop = loop;
1030 sp<MediaPlayerBase> p = getPlayer();
1031 if (p != 0) return p->setLooping(loop);
1032 return NO_ERROR;
1033 }
1034
setVolume(float leftVolume,float rightVolume)1035 status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1036 {
1037 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1038 // TODO: for hardware output, call player instead
1039 Mutex::Autolock l(mLock);
1040 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1041 return NO_ERROR;
1042 }
1043
setAuxEffectSendLevel(float level)1044 status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1045 {
1046 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1047 Mutex::Autolock l(mLock);
1048 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1049 return NO_ERROR;
1050 }
1051
attachAuxEffect(int effectId)1052 status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1053 {
1054 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1055 Mutex::Autolock l(mLock);
1056 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1057 return NO_ERROR;
1058 }
1059
setParameter(int key,const Parcel & request)1060 status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1061 LOGV("[%d] setParameter(%d)", mConnId, key);
1062 sp<MediaPlayerBase> p = getPlayer();
1063 if (p == 0) return UNKNOWN_ERROR;
1064 return p->setParameter(key, request);
1065 }
1066
getParameter(int key,Parcel * reply)1067 status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1068 LOGV("[%d] getParameter(%d)", mConnId, key);
1069 sp<MediaPlayerBase> p = getPlayer();
1070 if (p == 0) return UNKNOWN_ERROR;
1071 return p->getParameter(key, reply);
1072 }
1073
notify(void * cookie,int msg,int ext1,int ext2,const Parcel * obj)1074 void MediaPlayerService::Client::notify(
1075 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1076 {
1077 Client* client = static_cast<Client*>(cookie);
1078
1079 if (MEDIA_INFO == msg &&
1080 MEDIA_INFO_METADATA_UPDATE == ext1) {
1081 const media::Metadata::Type metadata_type = ext2;
1082
1083 if(client->shouldDropMetadata(metadata_type)) {
1084 return;
1085 }
1086
1087 // Update the list of metadata that have changed. getMetadata
1088 // also access mMetadataUpdated and clears it.
1089 client->addNewMetadataUpdate(metadata_type);
1090 }
1091 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1092 client->mClient->notify(msg, ext1, ext2, obj);
1093 }
1094
1095
shouldDropMetadata(media::Metadata::Type code) const1096 bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1097 {
1098 Mutex::Autolock lock(mLock);
1099
1100 if (findMetadata(mMetadataDrop, code)) {
1101 return true;
1102 }
1103
1104 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1105 return false;
1106 } else {
1107 return true;
1108 }
1109 }
1110
1111
addNewMetadataUpdate(media::Metadata::Type metadata_type)1112 void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1113 Mutex::Autolock lock(mLock);
1114 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1115 mMetadataUpdated.add(metadata_type);
1116 }
1117 }
1118
1119 #if CALLBACK_ANTAGONIZER
1120 const int Antagonizer::interval = 10000; // 10 msecs
1121
Antagonizer(notify_callback_f cb,void * client)1122 Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1123 mExit(false), mActive(false), mClient(client), mCb(cb)
1124 {
1125 createThread(callbackThread, this);
1126 }
1127
kill()1128 void Antagonizer::kill()
1129 {
1130 Mutex::Autolock _l(mLock);
1131 mActive = false;
1132 mExit = true;
1133 mCondition.wait(mLock);
1134 }
1135
callbackThread(void * user)1136 int Antagonizer::callbackThread(void* user)
1137 {
1138 LOGD("Antagonizer started");
1139 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1140 while (!p->mExit) {
1141 if (p->mActive) {
1142 LOGV("send event");
1143 p->mCb(p->mClient, 0, 0, 0);
1144 }
1145 usleep(interval);
1146 }
1147 Mutex::Autolock _l(p->mLock);
1148 p->mCondition.signal();
1149 LOGD("Antagonizer stopped");
1150 return 0;
1151 }
1152 #endif
1153
1154 static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1155
decode(const char * url,uint32_t * pSampleRate,int * pNumChannels,int * pFormat)1156 sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1157 {
1158 LOGV("decode(%s)", url);
1159 sp<MemoryBase> mem;
1160 sp<MediaPlayerBase> player;
1161
1162 // Protect our precious, precious DRMd ringtones by only allowing
1163 // decoding of http, but not filesystem paths or content Uris.
1164 // If the application wants to decode those, it should open a
1165 // filedescriptor for them and use that.
1166 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1167 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1168 return mem;
1169 }
1170
1171 player_type playerType = getPlayerType(url);
1172 LOGV("player type = %d", playerType);
1173
1174 // create the right type of player
1175 sp<AudioCache> cache = new AudioCache(url);
1176 player = android::createPlayer(playerType, cache.get(), cache->notify);
1177 if (player == NULL) goto Exit;
1178 if (player->hardwareOutput()) goto Exit;
1179
1180 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1181
1182 // set data source
1183 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1184
1185 LOGV("prepare");
1186 player->prepareAsync();
1187
1188 LOGV("wait for prepare");
1189 if (cache->wait() != NO_ERROR) goto Exit;
1190
1191 LOGV("start");
1192 player->start();
1193
1194 LOGV("wait for playback complete");
1195 cache->wait();
1196 // in case of error, return what was successfully decoded.
1197 if (cache->size() == 0) {
1198 goto Exit;
1199 }
1200
1201 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1202 *pSampleRate = cache->sampleRate();
1203 *pNumChannels = cache->channelCount();
1204 *pFormat = (int)cache->format();
1205 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1206
1207 Exit:
1208 if (player != 0) player->reset();
1209 return mem;
1210 }
1211
decode(int fd,int64_t offset,int64_t length,uint32_t * pSampleRate,int * pNumChannels,int * pFormat)1212 sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1213 {
1214 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1215 sp<MemoryBase> mem;
1216 sp<MediaPlayerBase> player;
1217
1218 player_type playerType = getPlayerType(fd, offset, length);
1219 LOGV("player type = %d", playerType);
1220
1221 // create the right type of player
1222 sp<AudioCache> cache = new AudioCache("decode_fd");
1223 player = android::createPlayer(playerType, cache.get(), cache->notify);
1224 if (player == NULL) goto Exit;
1225 if (player->hardwareOutput()) goto Exit;
1226
1227 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1228
1229 // set data source
1230 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1231
1232 LOGV("prepare");
1233 player->prepareAsync();
1234
1235 LOGV("wait for prepare");
1236 if (cache->wait() != NO_ERROR) goto Exit;
1237
1238 LOGV("start");
1239 player->start();
1240
1241 LOGV("wait for playback complete");
1242 cache->wait();
1243 // in case of error, return what was successfully decoded.
1244 if (cache->size() == 0) {
1245 goto Exit;
1246 }
1247
1248 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1249 *pSampleRate = cache->sampleRate();
1250 *pNumChannels = cache->channelCount();
1251 *pFormat = cache->format();
1252 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1253
1254 Exit:
1255 if (player != 0) player->reset();
1256 ::close(fd);
1257 return mem;
1258 }
1259
1260
1261 #undef LOG_TAG
1262 #define LOG_TAG "AudioSink"
AudioOutput(int sessionId)1263 MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
1264 : mCallback(NULL),
1265 mCallbackCookie(NULL),
1266 mSessionId(sessionId) {
1267 LOGV("AudioOutput(%d)", sessionId);
1268 mTrack = 0;
1269 mStreamType = AUDIO_STREAM_MUSIC;
1270 mLeftVolume = 1.0;
1271 mRightVolume = 1.0;
1272 mLatency = 0;
1273 mMsecsPerFrame = 0;
1274 mAuxEffectId = 0;
1275 mSendLevel = 0.0;
1276 setMinBufferCount();
1277 }
1278
~AudioOutput()1279 MediaPlayerService::AudioOutput::~AudioOutput()
1280 {
1281 close();
1282 }
1283
setMinBufferCount()1284 void MediaPlayerService::AudioOutput::setMinBufferCount()
1285 {
1286 char value[PROPERTY_VALUE_MAX];
1287 if (property_get("ro.kernel.qemu", value, 0)) {
1288 mIsOnEmulator = true;
1289 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1290 }
1291 }
1292
isOnEmulator()1293 bool MediaPlayerService::AudioOutput::isOnEmulator()
1294 {
1295 setMinBufferCount();
1296 return mIsOnEmulator;
1297 }
1298
getMinBufferCount()1299 int MediaPlayerService::AudioOutput::getMinBufferCount()
1300 {
1301 setMinBufferCount();
1302 return mMinBufferCount;
1303 }
1304
bufferSize() const1305 ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1306 {
1307 if (mTrack == 0) return NO_INIT;
1308 return mTrack->frameCount() * frameSize();
1309 }
1310
frameCount() const1311 ssize_t MediaPlayerService::AudioOutput::frameCount() const
1312 {
1313 if (mTrack == 0) return NO_INIT;
1314 return mTrack->frameCount();
1315 }
1316
channelCount() const1317 ssize_t MediaPlayerService::AudioOutput::channelCount() const
1318 {
1319 if (mTrack == 0) return NO_INIT;
1320 return mTrack->channelCount();
1321 }
1322
frameSize() const1323 ssize_t MediaPlayerService::AudioOutput::frameSize() const
1324 {
1325 if (mTrack == 0) return NO_INIT;
1326 return mTrack->frameSize();
1327 }
1328
latency() const1329 uint32_t MediaPlayerService::AudioOutput::latency () const
1330 {
1331 return mLatency;
1332 }
1333
msecsPerFrame() const1334 float MediaPlayerService::AudioOutput::msecsPerFrame() const
1335 {
1336 return mMsecsPerFrame;
1337 }
1338
getPosition(uint32_t * position)1339 status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1340 {
1341 if (mTrack == 0) return NO_INIT;
1342 return mTrack->getPosition(position);
1343 }
1344
open(uint32_t sampleRate,int channelCount,int format,int bufferCount,AudioCallback cb,void * cookie)1345 status_t MediaPlayerService::AudioOutput::open(
1346 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1347 AudioCallback cb, void *cookie)
1348 {
1349 mCallback = cb;
1350 mCallbackCookie = cookie;
1351
1352 // Check argument "bufferCount" against the mininum buffer count
1353 if (bufferCount < mMinBufferCount) {
1354 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1355 bufferCount = mMinBufferCount;
1356
1357 }
1358 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
1359 if (mTrack) close();
1360 int afSampleRate;
1361 int afFrameCount;
1362 int frameCount;
1363
1364 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1365 return NO_INIT;
1366 }
1367 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1368 return NO_INIT;
1369 }
1370
1371 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1372
1373 AudioTrack *t;
1374 if (mCallback != NULL) {
1375 t = new AudioTrack(
1376 mStreamType,
1377 sampleRate,
1378 format,
1379 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
1380 frameCount,
1381 0 /* flags */,
1382 CallbackWrapper,
1383 this,
1384 0,
1385 mSessionId);
1386 } else {
1387 t = new AudioTrack(
1388 mStreamType,
1389 sampleRate,
1390 format,
1391 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
1392 frameCount,
1393 0,
1394 NULL,
1395 NULL,
1396 0,
1397 mSessionId);
1398 }
1399
1400 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1401 LOGE("Unable to create audio track");
1402 delete t;
1403 return NO_INIT;
1404 }
1405
1406 LOGV("setVolume");
1407 t->setVolume(mLeftVolume, mRightVolume);
1408
1409 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1410 mLatency = t->latency();
1411 mTrack = t;
1412
1413 t->setAuxEffectSendLevel(mSendLevel);
1414 return t->attachAuxEffect(mAuxEffectId);;
1415 }
1416
start()1417 void MediaPlayerService::AudioOutput::start()
1418 {
1419 LOGV("start");
1420 if (mTrack) {
1421 mTrack->setVolume(mLeftVolume, mRightVolume);
1422 mTrack->setAuxEffectSendLevel(mSendLevel);
1423 mTrack->start();
1424 }
1425 }
1426
1427
1428
write(const void * buffer,size_t size)1429 ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1430 {
1431 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1432
1433 //LOGV("write(%p, %u)", buffer, size);
1434 if (mTrack) {
1435 ssize_t ret = mTrack->write(buffer, size);
1436 return ret;
1437 }
1438 return NO_INIT;
1439 }
1440
stop()1441 void MediaPlayerService::AudioOutput::stop()
1442 {
1443 LOGV("stop");
1444 if (mTrack) mTrack->stop();
1445 }
1446
flush()1447 void MediaPlayerService::AudioOutput::flush()
1448 {
1449 LOGV("flush");
1450 if (mTrack) mTrack->flush();
1451 }
1452
pause()1453 void MediaPlayerService::AudioOutput::pause()
1454 {
1455 LOGV("pause");
1456 if (mTrack) mTrack->pause();
1457 }
1458
close()1459 void MediaPlayerService::AudioOutput::close()
1460 {
1461 LOGV("close");
1462 delete mTrack;
1463 mTrack = 0;
1464 }
1465
setVolume(float left,float right)1466 void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1467 {
1468 LOGV("setVolume(%f, %f)", left, right);
1469 mLeftVolume = left;
1470 mRightVolume = right;
1471 if (mTrack) {
1472 mTrack->setVolume(left, right);
1473 }
1474 }
1475
setAuxEffectSendLevel(float level)1476 status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1477 {
1478 LOGV("setAuxEffectSendLevel(%f)", level);
1479 mSendLevel = level;
1480 if (mTrack) {
1481 return mTrack->setAuxEffectSendLevel(level);
1482 }
1483 return NO_ERROR;
1484 }
1485
attachAuxEffect(int effectId)1486 status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1487 {
1488 LOGV("attachAuxEffect(%d)", effectId);
1489 mAuxEffectId = effectId;
1490 if (mTrack) {
1491 return mTrack->attachAuxEffect(effectId);
1492 }
1493 return NO_ERROR;
1494 }
1495
1496 // static
CallbackWrapper(int event,void * cookie,void * info)1497 void MediaPlayerService::AudioOutput::CallbackWrapper(
1498 int event, void *cookie, void *info) {
1499 //LOGV("callbackwrapper");
1500 if (event != AudioTrack::EVENT_MORE_DATA) {
1501 return;
1502 }
1503
1504 AudioOutput *me = (AudioOutput *)cookie;
1505 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1506
1507 size_t actualSize = (*me->mCallback)(
1508 me, buffer->raw, buffer->size, me->mCallbackCookie);
1509
1510 if (actualSize == 0 && buffer->size > 0) {
1511 // We've reached EOS but the audio track is not stopped yet,
1512 // keep playing silence.
1513
1514 memset(buffer->raw, 0, buffer->size);
1515 actualSize = buffer->size;
1516 }
1517
1518 buffer->size = actualSize;
1519 }
1520
getSessionId()1521 int MediaPlayerService::AudioOutput::getSessionId()
1522 {
1523 return mSessionId;
1524 }
1525
1526 #undef LOG_TAG
1527 #define LOG_TAG "AudioCache"
AudioCache(const char * name)1528 MediaPlayerService::AudioCache::AudioCache(const char* name) :
1529 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1530 mError(NO_ERROR), mCommandComplete(false)
1531 {
1532 // create ashmem heap
1533 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1534 }
1535
latency() const1536 uint32_t MediaPlayerService::AudioCache::latency () const
1537 {
1538 return 0;
1539 }
1540
msecsPerFrame() const1541 float MediaPlayerService::AudioCache::msecsPerFrame() const
1542 {
1543 return mMsecsPerFrame;
1544 }
1545
getPosition(uint32_t * position)1546 status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1547 {
1548 if (position == 0) return BAD_VALUE;
1549 *position = mSize;
1550 return NO_ERROR;
1551 }
1552
1553 ////////////////////////////////////////////////////////////////////////////////
1554
1555 struct CallbackThread : public Thread {
1556 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1557 MediaPlayerBase::AudioSink::AudioCallback cb,
1558 void *cookie);
1559
1560 protected:
1561 virtual ~CallbackThread();
1562
1563 virtual bool threadLoop();
1564
1565 private:
1566 wp<MediaPlayerBase::AudioSink> mSink;
1567 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1568 void *mCookie;
1569 void *mBuffer;
1570 size_t mBufferSize;
1571
1572 CallbackThread(const CallbackThread &);
1573 CallbackThread &operator=(const CallbackThread &);
1574 };
1575
CallbackThread(const wp<MediaPlayerBase::AudioSink> & sink,MediaPlayerBase::AudioSink::AudioCallback cb,void * cookie)1576 CallbackThread::CallbackThread(
1577 const wp<MediaPlayerBase::AudioSink> &sink,
1578 MediaPlayerBase::AudioSink::AudioCallback cb,
1579 void *cookie)
1580 : mSink(sink),
1581 mCallback(cb),
1582 mCookie(cookie),
1583 mBuffer(NULL),
1584 mBufferSize(0) {
1585 }
1586
~CallbackThread()1587 CallbackThread::~CallbackThread() {
1588 if (mBuffer) {
1589 free(mBuffer);
1590 mBuffer = NULL;
1591 }
1592 }
1593
threadLoop()1594 bool CallbackThread::threadLoop() {
1595 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1596 if (sink == NULL) {
1597 return false;
1598 }
1599
1600 if (mBuffer == NULL) {
1601 mBufferSize = sink->bufferSize();
1602 mBuffer = malloc(mBufferSize);
1603 }
1604
1605 size_t actualSize =
1606 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1607
1608 if (actualSize > 0) {
1609 sink->write(mBuffer, actualSize);
1610 }
1611
1612 return true;
1613 }
1614
1615 ////////////////////////////////////////////////////////////////////////////////
1616
open(uint32_t sampleRate,int channelCount,int format,int bufferCount,AudioCallback cb,void * cookie)1617 status_t MediaPlayerService::AudioCache::open(
1618 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1619 AudioCallback cb, void *cookie)
1620 {
1621 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1622 if (mHeap->getHeapID() < 0) {
1623 return NO_INIT;
1624 }
1625
1626 mSampleRate = sampleRate;
1627 mChannelCount = (uint16_t)channelCount;
1628 mFormat = (uint16_t)format;
1629 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1630
1631 if (cb != NULL) {
1632 mCallbackThread = new CallbackThread(this, cb, cookie);
1633 }
1634 return NO_ERROR;
1635 }
1636
start()1637 void MediaPlayerService::AudioCache::start() {
1638 if (mCallbackThread != NULL) {
1639 mCallbackThread->run("AudioCache callback");
1640 }
1641 }
1642
stop()1643 void MediaPlayerService::AudioCache::stop() {
1644 if (mCallbackThread != NULL) {
1645 mCallbackThread->requestExitAndWait();
1646 }
1647 }
1648
write(const void * buffer,size_t size)1649 ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1650 {
1651 LOGV("write(%p, %u)", buffer, size);
1652 if ((buffer == 0) || (size == 0)) return size;
1653
1654 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1655 if (p == NULL) return NO_INIT;
1656 p += mSize;
1657 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1658 if (mSize + size > mHeap->getSize()) {
1659 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1660 size = mHeap->getSize() - mSize;
1661 }
1662 memcpy(p, buffer, size);
1663 mSize += size;
1664 return size;
1665 }
1666
1667 // call with lock held
wait()1668 status_t MediaPlayerService::AudioCache::wait()
1669 {
1670 Mutex::Autolock lock(mLock);
1671 while (!mCommandComplete) {
1672 mSignal.wait(mLock);
1673 }
1674 mCommandComplete = false;
1675
1676 if (mError == NO_ERROR) {
1677 LOGV("wait - success");
1678 } else {
1679 LOGV("wait - error");
1680 }
1681 return mError;
1682 }
1683
notify(void * cookie,int msg,int ext1,int ext2,const Parcel * obj)1684 void MediaPlayerService::AudioCache::notify(
1685 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1686 {
1687 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1688 AudioCache* p = static_cast<AudioCache*>(cookie);
1689
1690 // ignore buffering messages
1691 switch (msg)
1692 {
1693 case MEDIA_ERROR:
1694 LOGE("Error %d, %d occurred", ext1, ext2);
1695 p->mError = ext1;
1696 break;
1697 case MEDIA_PREPARED:
1698 LOGV("prepared");
1699 break;
1700 case MEDIA_PLAYBACK_COMPLETE:
1701 LOGV("playback complete");
1702 break;
1703 default:
1704 LOGV("ignored");
1705 return;
1706 }
1707
1708 // wake up thread
1709 Mutex::Autolock lock(p->mLock);
1710 p->mCommandComplete = true;
1711 p->mSignal.signal();
1712 }
1713
getSessionId()1714 int MediaPlayerService::AudioCache::getSessionId()
1715 {
1716 return 0;
1717 }
1718
addBatteryData(uint32_t params)1719 void MediaPlayerService::addBatteryData(uint32_t params)
1720 {
1721 Mutex::Autolock lock(mLock);
1722
1723 int32_t time = systemTime() / 1000000L;
1724
1725 // change audio output devices. This notification comes from AudioFlinger
1726 if ((params & kBatteryDataSpeakerOn)
1727 || (params & kBatteryDataOtherAudioDeviceOn)) {
1728
1729 int deviceOn[NUM_AUDIO_DEVICES];
1730 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1731 deviceOn[i] = 0;
1732 }
1733
1734 if ((params & kBatteryDataSpeakerOn)
1735 && (params & kBatteryDataOtherAudioDeviceOn)) {
1736 deviceOn[SPEAKER_AND_OTHER] = 1;
1737 } else if (params & kBatteryDataSpeakerOn) {
1738 deviceOn[SPEAKER] = 1;
1739 } else {
1740 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1741 }
1742
1743 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1744 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1745
1746 if (mBatteryAudio.refCount > 0) { // if playing audio
1747 if (!deviceOn[i]) {
1748 mBatteryAudio.lastTime[i] += time;
1749 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1750 mBatteryAudio.lastTime[i] = 0;
1751 } else {
1752 mBatteryAudio.lastTime[i] = 0 - time;
1753 }
1754 }
1755
1756 mBatteryAudio.deviceOn[i] = deviceOn[i];
1757 }
1758 }
1759 return;
1760 }
1761
1762 // an sudio stream is started
1763 if (params & kBatteryDataAudioFlingerStart) {
1764 // record the start time only if currently no other audio
1765 // is being played
1766 if (mBatteryAudio.refCount == 0) {
1767 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1768 if (mBatteryAudio.deviceOn[i]) {
1769 mBatteryAudio.lastTime[i] -= time;
1770 }
1771 }
1772 }
1773
1774 mBatteryAudio.refCount ++;
1775 return;
1776
1777 } else if (params & kBatteryDataAudioFlingerStop) {
1778 if (mBatteryAudio.refCount <= 0) {
1779 LOGW("Battery track warning: refCount is <= 0");
1780 return;
1781 }
1782
1783 // record the stop time only if currently this is the only
1784 // audio being played
1785 if (mBatteryAudio.refCount == 1) {
1786 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1787 if (mBatteryAudio.deviceOn[i]) {
1788 mBatteryAudio.lastTime[i] += time;
1789 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1790 mBatteryAudio.lastTime[i] = 0;
1791 }
1792 }
1793 }
1794
1795 mBatteryAudio.refCount --;
1796 return;
1797 }
1798
1799 int uid = IPCThreadState::self()->getCallingUid();
1800 if (uid == AID_MEDIA) {
1801 return;
1802 }
1803 int index = mBatteryData.indexOfKey(uid);
1804
1805 if (index < 0) { // create a new entry for this UID
1806 BatteryUsageInfo info;
1807 info.audioTotalTime = 0;
1808 info.videoTotalTime = 0;
1809 info.audioLastTime = 0;
1810 info.videoLastTime = 0;
1811 info.refCount = 0;
1812
1813 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1814 LOGE("Battery track error: no memory for new app");
1815 return;
1816 }
1817 }
1818
1819 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1820
1821 if (params & kBatteryDataCodecStarted) {
1822 if (params & kBatteryDataTrackAudio) {
1823 info.audioLastTime -= time;
1824 info.refCount ++;
1825 }
1826 if (params & kBatteryDataTrackVideo) {
1827 info.videoLastTime -= time;
1828 info.refCount ++;
1829 }
1830 } else {
1831 if (info.refCount == 0) {
1832 LOGW("Battery track warning: refCount is already 0");
1833 return;
1834 } else if (info.refCount < 0) {
1835 LOGE("Battery track error: refCount < 0");
1836 mBatteryData.removeItem(uid);
1837 return;
1838 }
1839
1840 if (params & kBatteryDataTrackAudio) {
1841 info.audioLastTime += time;
1842 info.refCount --;
1843 }
1844 if (params & kBatteryDataTrackVideo) {
1845 info.videoLastTime += time;
1846 info.refCount --;
1847 }
1848
1849 // no stream is being played by this UID
1850 if (info.refCount == 0) {
1851 info.audioTotalTime += info.audioLastTime;
1852 info.audioLastTime = 0;
1853 info.videoTotalTime += info.videoLastTime;
1854 info.videoLastTime = 0;
1855 }
1856 }
1857 }
1858
pullBatteryData(Parcel * reply)1859 status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1860 Mutex::Autolock lock(mLock);
1861
1862 // audio output devices usage
1863 int32_t time = systemTime() / 1000000L; //in ms
1864 int32_t totalTime;
1865
1866 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1867 totalTime = mBatteryAudio.totalTime[i];
1868
1869 if (mBatteryAudio.deviceOn[i]
1870 && (mBatteryAudio.lastTime[i] != 0)) {
1871 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1872 totalTime += tmpTime;
1873 }
1874
1875 reply->writeInt32(totalTime);
1876 // reset the total time
1877 mBatteryAudio.totalTime[i] = 0;
1878 }
1879
1880 // codec usage
1881 BatteryUsageInfo info;
1882 int size = mBatteryData.size();
1883
1884 reply->writeInt32(size);
1885 int i = 0;
1886
1887 while (i < size) {
1888 info = mBatteryData.valueAt(i);
1889
1890 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1891 reply->writeInt32(info.audioTotalTime);
1892 reply->writeInt32(info.videoTotalTime);
1893
1894 info.audioTotalTime = 0;
1895 info.videoTotalTime = 0;
1896
1897 // remove the UID entry where no stream is being played
1898 if (info.refCount <= 0) {
1899 mBatteryData.removeItemsAt(i);
1900 size --;
1901 i --;
1902 }
1903 i++;
1904 }
1905 return NO_ERROR;
1906 }
1907 } // namespace android
1908