blob: 5eecbde955c42143b3296ad9bd4c5280de25881a [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
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>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
37#include <android_runtime/ActivityManager.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070038
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070043#include <utils/Errors.h> // for status_t
44#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070045#include <utils/SystemClock.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047#include <cutils/properties.h>
48
49#include <media/MediaPlayerInterface.h>
50#include <media/mediarecorder.h>
51#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070052#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080053#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070054#include <media/MemoryLeakTrackUtil.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055
Gloria Wang7cf180c2011-02-19 18:37:57 -080056#include <private/android_filesystem_config.h>
57
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080058#include "MediaRecorderClient.h"
59#include "MediaPlayerService.h"
60#include "MetadataRetrieverClient.h"
61
62#include "MidiFile.h"
Nicolas Catania14d27472009-07-13 14:37:49 -070063#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070064#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080065#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070066
Andreas Huber20111aa2009-07-14 16:56:47 -070067#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070068
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080069/* desktop Linux needs a little help with gettid() */
70#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
71#define __KERNEL__
72# include <linux/unistd.h>
73#ifdef _syscall0
74_syscall0(pid_t,gettid)
75#else
76pid_t gettid() { return syscall(__NR_gettid);}
77#endif
78#undef __KERNEL__
79#endif
80
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070081namespace {
nikoa64c8c72009-07-20 15:07:26 -070082using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070083using android::status_t;
84using android::OK;
85using android::BAD_VALUE;
86using android::NOT_ENOUGH_DATA;
87using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088
89// Max number of entries in the filter.
90const int kMaxFilterSize = 64; // I pulled that out of thin air.
91
nikoa64c8c72009-07-20 15:07:26 -070092// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070093
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070094
95// Unmarshall a filter from a Parcel.
96// Filter format in a parcel:
97//
98// 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
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | number of entries (n) |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// | metadata type 1 |
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | metadata type 2 |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// ....
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | metadata type n |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110//
111// @param p Parcel that should start with a filter.
112// @param[out] filter On exit contains the list of metadata type to be
113// filtered.
114// @param[out] status On exit contains the status code to be returned.
115// @return true if the parcel starts with a valid filter.
116bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700117 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700118 status_t *status)
119{
Nicolas Catania48290382009-07-10 13:53:06 -0700120 int32_t val;
121 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700122 {
123 LOGE("Failed to read filter's length");
124 *status = NOT_ENOUGH_DATA;
125 return false;
126 }
127
Nicolas Catania48290382009-07-10 13:53:06 -0700128 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 {
Nicolas Catania48290382009-07-10 13:53:06 -0700130 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 *status = BAD_VALUE;
132 return false;
133 }
134
Nicolas Catania48290382009-07-10 13:53:06 -0700135 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136
137 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700138 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139
nikoa64c8c72009-07-20 15:07:26 -0700140 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141
Nicolas Catania48290382009-07-10 13:53:06 -0700142
143 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144 {
Nicolas Catania48290382009-07-10 13:53:06 -0700145 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146 *status = NOT_ENOUGH_DATA;
147 return false;
148 }
149
nikoa64c8c72009-07-20 15:07:26 -0700150 const Metadata::Type *data =
151 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152
Nicolas Catania48290382009-07-10 13:53:06 -0700153 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 {
155 LOGE("Filter had no data");
156 *status = BAD_VALUE;
157 return false;
158 }
159
160 // TODO: The stl impl of vector would be more efficient here
161 // because it degenerates into a memcpy on pod types. Try to
162 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700163 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 {
Nicolas Catania48290382009-07-10 13:53:06 -0700165 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166 ++data;
167 }
168 *status = OK;
169 return true;
170}
171
Nicolas Catania48290382009-07-10 13:53:06 -0700172// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173// @param val To be searched.
174// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700175bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700176{
177 // Deal with empty and ANY right away
178 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700179 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180
Nicolas Catania48290382009-07-10 13:53:06 -0700181 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182}
183
184} // anonymous namespace
185
186
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800187namespace android {
188
189// TODO: Temp hack until we can register players
190typedef struct {
191 const char *extension;
192 const player_type playertype;
193} extmap;
194extmap FILE_EXTS [] = {
195 {".mid", SONIVOX_PLAYER},
196 {".midi", SONIVOX_PLAYER},
197 {".smf", SONIVOX_PLAYER},
198 {".xmf", SONIVOX_PLAYER},
199 {".imy", SONIVOX_PLAYER},
200 {".rtttl", SONIVOX_PLAYER},
201 {".rtx", SONIVOX_PLAYER},
202 {".ota", SONIVOX_PLAYER},
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800203};
204
205// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800206/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
207/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
208
209void MediaPlayerService::instantiate() {
210 defaultServiceManager()->addService(
211 String16("media.player"), new MediaPlayerService());
212}
213
214MediaPlayerService::MediaPlayerService()
215{
216 LOGV("MediaPlayerService created");
217 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800218
219 mBatteryAudio.refCount = 0;
220 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
221 mBatteryAudio.deviceOn[i] = 0;
222 mBatteryAudio.lastTime[i] = 0;
223 mBatteryAudio.totalTime[i] = 0;
224 }
225 // speaker is on by default
226 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800227}
228
229MediaPlayerService::~MediaPlayerService()
230{
231 LOGV("MediaPlayerService destroyed");
232}
233
234sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
235{
Gloria Wangdac6a312009-10-29 15:46:37 -0700236 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
237 wp<MediaRecorderClient> w = recorder;
238 Mutex::Autolock lock(mLock);
239 mMediaRecorderClients.add(w);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800240 LOGV("Create new media recorder client from pid %d", pid);
241 return recorder;
242}
243
Gloria Wangdac6a312009-10-29 15:46:37 -0700244void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
245{
246 Mutex::Autolock lock(mLock);
247 mMediaRecorderClients.remove(client);
248 LOGV("Delete media recorder client");
249}
250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
252{
253 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
254 LOGV("Create new media retriever from pid %d", pid);
255 return retriever;
256}
257
Andreas Huber2db84552010-01-28 11:19:57 -0800258sp<IMediaPlayer> MediaPlayerService::create(
259 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700260 const KeyedVector<String8, String8> *headers, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800261{
262 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700263 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
264 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
265 connId, pid, url, connId, audioSessionId);
Andreas Huber2db84552010-01-28 11:19:57 -0800266 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267 {
268 c.clear();
269 return c;
270 }
271 wp<Client> w = c;
272 Mutex::Autolock lock(mLock);
273 mClients.add(w);
274 return c;
275}
276
277sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700278 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279{
280 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700281 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
282 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
283 connId, pid, fd, offset, length, audioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
285 c.clear();
286 } else {
287 wp<Client> w = c;
288 Mutex::Autolock lock(mLock);
289 mClients.add(w);
290 }
291 ::close(fd);
292 return c;
293}
294
Andreas Hubere2b10282010-11-23 11:41:34 -0800295sp<IMediaPlayer> MediaPlayerService::create(
296 pid_t pid, const sp<IMediaPlayerClient> &client,
297 const sp<IStreamSource> &source, int audioSessionId) {
298 int32_t connId = android_atomic_inc(&mNextConnId);
299 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
300
301 LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
302 connId, pid, audioSessionId);
303
304 if (OK != c->setDataSource(source)) {
305 c.clear();
306 } else {
307 wp<Client> w = c;
308 Mutex::Autolock lock(mLock);
309 mClients.add(w);
310 }
311
312 return c;
313}
314
Andreas Huber318ad9c2009-10-15 13:46:54 -0700315sp<IOMX> MediaPlayerService::getOMX() {
316 Mutex::Autolock autoLock(mLock);
317
318 if (mOMX.get() == NULL) {
319 mOMX = new OMX;
320 }
321
322 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700323}
324
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800325status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
326{
327 const size_t SIZE = 256;
328 char buffer[SIZE];
329 String8 result;
330
331 result.append(" AudioCache\n");
332 if (mHeap != 0) {
333 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
334 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
335 result.append(buffer);
336 }
337 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
338 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
339 result.append(buffer);
340 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
341 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
342 result.append(buffer);
343 ::write(fd, result.string(), result.size());
344 return NO_ERROR;
345}
346
347status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
348{
349 const size_t SIZE = 256;
350 char buffer[SIZE];
351 String8 result;
352
353 result.append(" AudioOutput\n");
354 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
355 mStreamType, mLeftVolume, mRightVolume);
356 result.append(buffer);
357 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
358 mMsecsPerFrame, mLatency);
359 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700360 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
361 mAuxEffectId, mSendLevel);
362 result.append(buffer);
363
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800364 ::write(fd, result.string(), result.size());
365 if (mTrack != 0) {
366 mTrack->dump(fd, args);
367 }
368 return NO_ERROR;
369}
370
371status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
372{
373 const size_t SIZE = 256;
374 char buffer[SIZE];
375 String8 result;
376 result.append(" Client\n");
377 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
378 mPid, mConnId, mStatus, mLoop?"true": "false");
379 result.append(buffer);
380 write(fd, result.string(), result.size());
381 if (mAudioOutput != 0) {
382 mAudioOutput->dump(fd, args);
383 }
384 write(fd, "\n", 1);
385 return NO_ERROR;
386}
387
388static int myTid() {
389#ifdef HAVE_GETTID
390 return gettid();
391#else
392 return getpid();
393#endif
394}
395
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
397{
398 const size_t SIZE = 256;
399 char buffer[SIZE];
400 String8 result;
401 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
402 snprintf(buffer, SIZE, "Permission Denial: "
403 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
404 IPCThreadState::self()->getCallingPid(),
405 IPCThreadState::self()->getCallingUid());
406 result.append(buffer);
407 } else {
408 Mutex::Autolock lock(mLock);
409 for (int i = 0, n = mClients.size(); i < n; ++i) {
410 sp<Client> c = mClients[i].promote();
411 if (c != 0) c->dump(fd, args);
412 }
James Dongb9141222010-07-08 11:16:11 -0700413 if (mMediaRecorderClients.size() == 0) {
414 result.append(" No media recorder client\n\n");
415 } else {
416 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
417 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
418 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
419 result.append(buffer);
420 write(fd, result.string(), result.size());
421 result = "\n";
422 c->dump(fd, args);
423 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700424 }
425
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800426 result.append(" Files opened and/or mapped:\n");
427 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
428 FILE *f = fopen(buffer, "r");
429 if (f) {
430 while (!feof(f)) {
431 fgets(buffer, SIZE, f);
Dave Sparks02fa8342010-09-27 16:55:18 -0700432 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800433 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700434 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800435 strstr(buffer, " /system/media/")) {
436 result.append(" ");
437 result.append(buffer);
438 }
439 }
440 fclose(f);
441 } else {
442 result.append("couldn't open ");
443 result.append(buffer);
444 result.append("\n");
445 }
446
447 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
448 DIR *d = opendir(buffer);
449 if (d) {
450 struct dirent *ent;
451 while((ent = readdir(d)) != NULL) {
452 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
453 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
454 struct stat s;
455 if (lstat(buffer, &s) == 0) {
456 if ((s.st_mode & S_IFMT) == S_IFLNK) {
457 char linkto[256];
458 int len = readlink(buffer, linkto, sizeof(linkto));
459 if(len > 0) {
460 if(len > 255) {
461 linkto[252] = '.';
462 linkto[253] = '.';
463 linkto[254] = '.';
464 linkto[255] = 0;
465 } else {
466 linkto[len] = 0;
467 }
Dave Sparks02fa8342010-09-27 16:55:18 -0700468 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700470 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 strstr(linkto, "/system/media/") == linkto) {
472 result.append(" ");
473 result.append(buffer);
474 result.append(" -> ");
475 result.append(linkto);
476 result.append("\n");
477 }
478 }
479 } else {
480 result.append(" unexpected type for ");
481 result.append(buffer);
482 result.append("\n");
483 }
484 }
485 }
486 }
487 closedir(d);
488 } else {
489 result.append("couldn't open ");
490 result.append(buffer);
491 result.append("\n");
492 }
493
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 bool dumpMem = false;
495 for (size_t i = 0; i < args.size(); i++) {
496 if (args[i] == String16("-m")) {
497 dumpMem = true;
498 }
499 }
500 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700501 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800503 }
504 write(fd, result.string(), result.size());
505 return NO_ERROR;
506}
507
508void MediaPlayerService::removeClient(wp<Client> client)
509{
510 Mutex::Autolock lock(mLock);
511 mClients.remove(client);
512}
513
514MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700515 int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516{
517 LOGV("Client(%d) constructor", connId);
518 mPid = pid;
519 mConnId = connId;
520 mService = service;
521 mClient = client;
522 mLoop = false;
523 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700524 mAudioSessionId = audioSessionId;
525
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800526#if CALLBACK_ANTAGONIZER
527 LOGD("create Antagonizer");
528 mAntagonizer = new Antagonizer(notify, this);
529#endif
530}
531
532MediaPlayerService::Client::~Client()
533{
534 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
535 mAudioOutput.clear();
536 wp<Client> client(this);
537 disconnect();
538 mService->removeClient(client);
539}
540
541void MediaPlayerService::Client::disconnect()
542{
543 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
544 // grab local reference and clear main reference to prevent future
545 // access to object
546 sp<MediaPlayerBase> p;
547 {
548 Mutex::Autolock l(mLock);
549 p = mPlayer;
550 }
Dave Sparks795fa582009-03-24 17:57:12 -0700551 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700552
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 mPlayer.clear();
554
555 // clear the notification to prevent callbacks to dead client
556 // and reset the player. We assume the player will serialize
557 // access to itself if necessary.
558 if (p != 0) {
559 p->setNotifyCallback(0, 0);
560#if CALLBACK_ANTAGONIZER
561 LOGD("kill Antagonizer");
562 mAntagonizer->kill();
563#endif
564 p->reset();
565 }
566
567 IPCThreadState::self()->flushCommands();
568}
569
Andreas Huber47f59cf2009-08-07 09:30:32 -0700570static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700571 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700572}
573
James Dong148c1a22009-09-06 14:29:45 -0700574player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575{
576 char buf[20];
577 lseek(fd, offset, SEEK_SET);
578 read(fd, buf, sizeof(buf));
579 lseek(fd, offset, SEEK_SET);
580
581 long ident = *((long*)buf);
582
583 // Ogg vorbis?
584 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700585 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586
587 // Some kind of MIDI?
588 EAS_DATA_HANDLE easdata;
589 if (EAS_Init(&easdata) == EAS_SUCCESS) {
590 EAS_FILE locator;
591 locator.path = NULL;
592 locator.fd = fd;
593 locator.offset = offset;
594 locator.length = length;
595 EAS_HANDLE eashandle;
596 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
597 EAS_CloseFile(easdata, eashandle);
598 EAS_Shutdown(easdata);
599 return SONIVOX_PLAYER;
600 }
601 EAS_Shutdown(easdata);
602 }
603
Andreas Huber47f59cf2009-08-07 09:30:32 -0700604 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605}
606
James Dong148c1a22009-09-06 14:29:45 -0700607player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608{
Nicolas Catania14d27472009-07-13 14:37:49 -0700609 if (TestPlayerStub::canBeUsed(url)) {
610 return TEST_PLAYER;
611 }
612
Andreas Huber0a73d812011-03-21 16:28:04 -0700613 if (!strncasecmp("http://", url, 7)
614 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-02-16 09:05:38 -0800615 size_t len = strlen(url);
616 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
617 return NU_PLAYER;
618 }
Andreas Huber5bc087c2010-12-23 10:27:40 -0800619
Andreas Hubered8d14f2011-02-16 09:05:38 -0800620 if (strstr(url,"m3u8")) {
621 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800622 }
623 }
624
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625 // use MidiFile for MIDI extensions
626 int lenURL = strlen(url);
627 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
628 int len = strlen(FILE_EXTS[i].extension);
629 int start = lenURL - len;
630 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900631 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700632 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 }
634 }
635 }
636
Andreas Huber47f59cf2009-08-07 09:30:32 -0700637 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638}
639
640static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
641 notify_callback_f notifyFunc)
642{
643 sp<MediaPlayerBase> p;
644 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 case SONIVOX_PLAYER:
646 LOGV(" create MidiFile");
647 p = new MidiFile();
648 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700649 case STAGEFRIGHT_PLAYER:
650 LOGV(" create StagefrightPlayer");
651 p = new StagefrightPlayer;
652 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800653 case NU_PLAYER:
654 LOGV(" create NuPlayer");
655 p = new NuPlayerDriver;
656 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700657 case TEST_PLAYER:
658 LOGV("Create Test Player stub");
659 p = new TestPlayerStub();
660 break;
James Dong30d713a2010-11-10 18:42:40 -0800661 default:
662 LOGE("Unknown player type: %d", playerType);
663 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664 }
665 if (p != NULL) {
666 if (p->initCheck() == NO_ERROR) {
667 p->setNotifyCallback(cookie, notifyFunc);
668 } else {
669 p.clear();
670 }
671 }
672 if (p == NULL) {
673 LOGE("Failed to create player object");
674 }
675 return p;
676}
677
678sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
679{
680 // determine if we have the right player type
681 sp<MediaPlayerBase> p = mPlayer;
682 if ((p != NULL) && (p->playerType() != playerType)) {
683 LOGV("delete player");
684 p.clear();
685 }
686 if (p == NULL) {
687 p = android::createPlayer(playerType, this, notify);
688 }
689 return p;
690}
691
Andreas Huber2db84552010-01-28 11:19:57 -0800692status_t MediaPlayerService::Client::setDataSource(
693 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694{
695 LOGV("setDataSource(%s)", url);
696 if (url == NULL)
697 return UNKNOWN_ERROR;
698
699 if (strncmp(url, "content://", 10) == 0) {
700 // get a filedescriptor for the content Uri and
701 // pass it to the setDataSource(fd) method
702
703 String16 url16(url);
704 int fd = android::openContentProviderFile(url16);
705 if (fd < 0)
706 {
707 LOGE("Couldn't open fd for %s", url);
708 return UNKNOWN_ERROR;
709 }
710 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
711 close(fd);
712 return mStatus;
713 } else {
714 player_type playerType = getPlayerType(url);
715 LOGV("player type = %d", playerType);
716
717 // create the right type of player
718 sp<MediaPlayerBase> p = createPlayer(playerType);
719 if (p == NULL) return NO_INIT;
720
721 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700722 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
724 }
725
726 // now set data source
727 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800728 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700729 if (mStatus == NO_ERROR) {
730 mPlayer = p;
731 } else {
732 LOGE(" error: %d", mStatus);
733 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 return mStatus;
735 }
736}
737
738status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
739{
740 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
741 struct stat sb;
742 int ret = fstat(fd, &sb);
743 if (ret != 0) {
744 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
745 return UNKNOWN_ERROR;
746 }
747
748 LOGV("st_dev = %llu", sb.st_dev);
749 LOGV("st_mode = %u", sb.st_mode);
750 LOGV("st_uid = %lu", sb.st_uid);
751 LOGV("st_gid = %lu", sb.st_gid);
752 LOGV("st_size = %llu", sb.st_size);
753
754 if (offset >= sb.st_size) {
755 LOGE("offset error");
756 ::close(fd);
757 return UNKNOWN_ERROR;
758 }
759 if (offset + length > sb.st_size) {
760 length = sb.st_size - offset;
761 LOGV("calculated length = %lld", length);
762 }
763
764 player_type playerType = getPlayerType(fd, offset, length);
765 LOGV("player type = %d", playerType);
766
767 // create the right type of player
768 sp<MediaPlayerBase> p = createPlayer(playerType);
769 if (p == NULL) return NO_INIT;
770
771 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700772 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
774 }
775
776 // now set data source
777 mStatus = p->setDataSource(fd, offset, length);
778 if (mStatus == NO_ERROR) mPlayer = p;
779 return mStatus;
780}
781
Andreas Hubere2b10282010-11-23 11:41:34 -0800782status_t MediaPlayerService::Client::setDataSource(
783 const sp<IStreamSource> &source) {
784 // create the right type of player
Andreas Huberf9334412010-12-15 15:17:42 -0800785 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Hubere2b10282010-11-23 11:41:34 -0800786
787 if (p == NULL) {
788 return NO_INIT;
789 }
790
791 if (!p->hardwareOutput()) {
792 mAudioOutput = new AudioOutput(mAudioSessionId);
793 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
794 }
795
796 // now set data source
797 mStatus = p->setDataSource(source);
798
799 if (mStatus == OK) {
800 mPlayer = p;
801 }
802
803 return mStatus;
804}
805
Andreas Huber5daeb122010-08-16 08:49:37 -0700806status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800807{
808 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
809 sp<MediaPlayerBase> p = getPlayer();
810 if (p == 0) return UNKNOWN_ERROR;
811 return p->setVideoSurface(surface);
812}
813
Glenn Kasten11731182011-02-08 17:26:17 -0800814status_t MediaPlayerService::Client::setVideoSurfaceTexture(
815 const sp<ISurfaceTexture>& surfaceTexture)
816{
817 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
818 sp<MediaPlayerBase> p = getPlayer();
819 if (p == 0) return UNKNOWN_ERROR;
820 return p->setVideoSurfaceTexture(surfaceTexture);
821}
822
Nicolas Catania1d187f12009-05-12 23:25:55 -0700823status_t MediaPlayerService::Client::invoke(const Parcel& request,
824 Parcel *reply)
825{
826 sp<MediaPlayerBase> p = getPlayer();
827 if (p == NULL) return UNKNOWN_ERROR;
828 return p->invoke(request, reply);
829}
830
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700831// This call doesn't need to access the native player.
832status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
833{
834 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700835 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700836
Nicolas Catania48290382009-07-10 13:53:06 -0700837 if (unmarshallFilter(filter, &allow, &status) &&
838 unmarshallFilter(filter, &drop, &status)) {
839 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700840
841 mMetadataAllow = allow;
842 mMetadataDrop = drop;
843 }
844 return status;
845}
846
Nicolas Catania48290382009-07-10 13:53:06 -0700847status_t MediaPlayerService::Client::getMetadata(
848 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700849{
nikoa64c8c72009-07-20 15:07:26 -0700850 sp<MediaPlayerBase> player = getPlayer();
851 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700852
nikod608a812009-07-16 16:39:53 -0700853 status_t status;
854 // Placeholder for the return code, updated by the caller.
855 reply->writeInt32(-1);
856
nikoa64c8c72009-07-20 15:07:26 -0700857 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700858
859 // We don't block notifications while we fetch the data. We clear
860 // mMetadataUpdated first so we don't lose notifications happening
861 // during the rest of this call.
862 {
863 Mutex::Autolock lock(mLock);
864 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700865 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700866 }
867 mMetadataUpdated.clear();
868 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700869
nikoa64c8c72009-07-20 15:07:26 -0700870 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700871
nikoa64c8c72009-07-20 15:07:26 -0700872 metadata.appendHeader();
873 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700874
875 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700876 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700877 LOGE("getMetadata failed %d", status);
878 return status;
879 }
880
881 // FIXME: Implement filtering on the result. Not critical since
882 // filtering takes place on the update notifications already. This
883 // would be when all the metadata are fetch and a filter is set.
884
nikod608a812009-07-16 16:39:53 -0700885 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700886 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700887 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700888}
889
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800890status_t MediaPlayerService::Client::prepareAsync()
891{
892 LOGV("[%d] prepareAsync", mConnId);
893 sp<MediaPlayerBase> p = getPlayer();
894 if (p == 0) return UNKNOWN_ERROR;
895 status_t ret = p->prepareAsync();
896#if CALLBACK_ANTAGONIZER
897 LOGD("start Antagonizer");
898 if (ret == NO_ERROR) mAntagonizer->start();
899#endif
900 return ret;
901}
902
903status_t MediaPlayerService::Client::start()
904{
905 LOGV("[%d] start", mConnId);
906 sp<MediaPlayerBase> p = getPlayer();
907 if (p == 0) return UNKNOWN_ERROR;
908 p->setLooping(mLoop);
909 return p->start();
910}
911
912status_t MediaPlayerService::Client::stop()
913{
914 LOGV("[%d] stop", mConnId);
915 sp<MediaPlayerBase> p = getPlayer();
916 if (p == 0) return UNKNOWN_ERROR;
917 return p->stop();
918}
919
920status_t MediaPlayerService::Client::pause()
921{
922 LOGV("[%d] pause", mConnId);
923 sp<MediaPlayerBase> p = getPlayer();
924 if (p == 0) return UNKNOWN_ERROR;
925 return p->pause();
926}
927
928status_t MediaPlayerService::Client::isPlaying(bool* state)
929{
930 *state = false;
931 sp<MediaPlayerBase> p = getPlayer();
932 if (p == 0) return UNKNOWN_ERROR;
933 *state = p->isPlaying();
934 LOGV("[%d] isPlaying: %d", mConnId, *state);
935 return NO_ERROR;
936}
937
938status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
939{
940 LOGV("getCurrentPosition");
941 sp<MediaPlayerBase> p = getPlayer();
942 if (p == 0) return UNKNOWN_ERROR;
943 status_t ret = p->getCurrentPosition(msec);
944 if (ret == NO_ERROR) {
945 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
946 } else {
947 LOGE("getCurrentPosition returned %d", ret);
948 }
949 return ret;
950}
951
952status_t MediaPlayerService::Client::getDuration(int *msec)
953{
954 LOGV("getDuration");
955 sp<MediaPlayerBase> p = getPlayer();
956 if (p == 0) return UNKNOWN_ERROR;
957 status_t ret = p->getDuration(msec);
958 if (ret == NO_ERROR) {
959 LOGV("[%d] getDuration = %d", mConnId, *msec);
960 } else {
961 LOGE("getDuration returned %d", ret);
962 }
963 return ret;
964}
965
966status_t MediaPlayerService::Client::seekTo(int msec)
967{
968 LOGV("[%d] seekTo(%d)", mConnId, msec);
969 sp<MediaPlayerBase> p = getPlayer();
970 if (p == 0) return UNKNOWN_ERROR;
971 return p->seekTo(msec);
972}
973
974status_t MediaPlayerService::Client::reset()
975{
976 LOGV("[%d] reset", mConnId);
977 sp<MediaPlayerBase> p = getPlayer();
978 if (p == 0) return UNKNOWN_ERROR;
979 return p->reset();
980}
981
982status_t MediaPlayerService::Client::setAudioStreamType(int type)
983{
984 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
985 // TODO: for hardware output, call player instead
986 Mutex::Autolock l(mLock);
987 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
988 return NO_ERROR;
989}
990
991status_t MediaPlayerService::Client::setLooping(int loop)
992{
993 LOGV("[%d] setLooping(%d)", mConnId, loop);
994 mLoop = loop;
995 sp<MediaPlayerBase> p = getPlayer();
996 if (p != 0) return p->setLooping(loop);
997 return NO_ERROR;
998}
999
1000status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1001{
1002 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1003 // TODO: for hardware output, call player instead
1004 Mutex::Autolock l(mLock);
1005 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1006 return NO_ERROR;
1007}
1008
Eric Laurent2beeb502010-07-16 07:43:46 -07001009status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1010{
1011 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1012 Mutex::Autolock l(mLock);
1013 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1014 return NO_ERROR;
1015}
1016
1017status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1018{
1019 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1020 Mutex::Autolock l(mLock);
1021 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1022 return NO_ERROR;
1023}
Nicolas Catania48290382009-07-10 13:53:06 -07001024
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001025void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1026{
1027 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001028
1029 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001030 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001031 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001032
1033 if(client->shouldDropMetadata(metadata_type)) {
1034 return;
1035 }
1036
1037 // Update the list of metadata that have changed. getMetadata
1038 // also access mMetadataUpdated and clears it.
1039 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001040 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001041 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1042 client->mClient->notify(msg, ext1, ext2);
1043}
1044
Nicolas Catania48290382009-07-10 13:53:06 -07001045
nikoa64c8c72009-07-20 15:07:26 -07001046bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001047{
Nicolas Catania48290382009-07-10 13:53:06 -07001048 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001049
Nicolas Catania48290382009-07-10 13:53:06 -07001050 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001051 return true;
1052 }
1053
Nicolas Catania48290382009-07-10 13:53:06 -07001054 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001055 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001056 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001057 return true;
1058 }
1059}
1060
Nicolas Catania48290382009-07-10 13:53:06 -07001061
nikoa64c8c72009-07-20 15:07:26 -07001062void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001063 Mutex::Autolock lock(mLock);
1064 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1065 mMetadataUpdated.add(metadata_type);
1066 }
1067}
1068
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069#if CALLBACK_ANTAGONIZER
1070const int Antagonizer::interval = 10000; // 10 msecs
1071
1072Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1073 mExit(false), mActive(false), mClient(client), mCb(cb)
1074{
1075 createThread(callbackThread, this);
1076}
1077
1078void Antagonizer::kill()
1079{
1080 Mutex::Autolock _l(mLock);
1081 mActive = false;
1082 mExit = true;
1083 mCondition.wait(mLock);
1084}
1085
1086int Antagonizer::callbackThread(void* user)
1087{
1088 LOGD("Antagonizer started");
1089 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1090 while (!p->mExit) {
1091 if (p->mActive) {
1092 LOGV("send event");
1093 p->mCb(p->mClient, 0, 0, 0);
1094 }
1095 usleep(interval);
1096 }
1097 Mutex::Autolock _l(p->mLock);
1098 p->mCondition.signal();
1099 LOGD("Antagonizer stopped");
1100 return 0;
1101}
1102#endif
1103
1104static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1105
1106sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1107{
1108 LOGV("decode(%s)", url);
1109 sp<MemoryBase> mem;
1110 sp<MediaPlayerBase> player;
1111
1112 // Protect our precious, precious DRMd ringtones by only allowing
1113 // decoding of http, but not filesystem paths or content Uris.
1114 // If the application wants to decode those, it should open a
1115 // filedescriptor for them and use that.
1116 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1117 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1118 return mem;
1119 }
1120
1121 player_type playerType = getPlayerType(url);
1122 LOGV("player type = %d", playerType);
1123
1124 // create the right type of player
1125 sp<AudioCache> cache = new AudioCache(url);
1126 player = android::createPlayer(playerType, cache.get(), cache->notify);
1127 if (player == NULL) goto Exit;
1128 if (player->hardwareOutput()) goto Exit;
1129
1130 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1131
1132 // set data source
1133 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1134
1135 LOGV("prepare");
1136 player->prepareAsync();
1137
1138 LOGV("wait for prepare");
1139 if (cache->wait() != NO_ERROR) goto Exit;
1140
1141 LOGV("start");
1142 player->start();
1143
1144 LOGV("wait for playback complete");
1145 if (cache->wait() != NO_ERROR) goto Exit;
1146
1147 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1148 *pSampleRate = cache->sampleRate();
1149 *pNumChannels = cache->channelCount();
1150 *pFormat = cache->format();
1151 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1152
1153Exit:
1154 if (player != 0) player->reset();
1155 return mem;
1156}
1157
1158sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1159{
1160 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1161 sp<MemoryBase> mem;
1162 sp<MediaPlayerBase> player;
1163
1164 player_type playerType = getPlayerType(fd, offset, length);
1165 LOGV("player type = %d", playerType);
1166
1167 // create the right type of player
1168 sp<AudioCache> cache = new AudioCache("decode_fd");
1169 player = android::createPlayer(playerType, cache.get(), cache->notify);
1170 if (player == NULL) goto Exit;
1171 if (player->hardwareOutput()) goto Exit;
1172
1173 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1174
1175 // set data source
1176 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1177
1178 LOGV("prepare");
1179 player->prepareAsync();
1180
1181 LOGV("wait for prepare");
1182 if (cache->wait() != NO_ERROR) goto Exit;
1183
1184 LOGV("start");
1185 player->start();
1186
1187 LOGV("wait for playback complete");
1188 if (cache->wait() != NO_ERROR) goto Exit;
1189
1190 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1191 *pSampleRate = cache->sampleRate();
1192 *pNumChannels = cache->channelCount();
1193 *pFormat = cache->format();
1194 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1195
1196Exit:
1197 if (player != 0) player->reset();
1198 ::close(fd);
1199 return mem;
1200}
1201
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001202
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001203#undef LOG_TAG
1204#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001205MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001206 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001207 mCallbackCookie(NULL),
1208 mSessionId(sessionId) {
1209 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001210 mTrack = 0;
1211 mStreamType = AudioSystem::MUSIC;
1212 mLeftVolume = 1.0;
1213 mRightVolume = 1.0;
1214 mLatency = 0;
1215 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001216 mAuxEffectId = 0;
1217 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001218 setMinBufferCount();
1219}
1220
1221MediaPlayerService::AudioOutput::~AudioOutput()
1222{
1223 close();
1224}
1225
1226void MediaPlayerService::AudioOutput::setMinBufferCount()
1227{
1228 char value[PROPERTY_VALUE_MAX];
1229 if (property_get("ro.kernel.qemu", value, 0)) {
1230 mIsOnEmulator = true;
1231 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1232 }
1233}
1234
1235bool MediaPlayerService::AudioOutput::isOnEmulator()
1236{
1237 setMinBufferCount();
1238 return mIsOnEmulator;
1239}
1240
1241int MediaPlayerService::AudioOutput::getMinBufferCount()
1242{
1243 setMinBufferCount();
1244 return mMinBufferCount;
1245}
1246
1247ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1248{
1249 if (mTrack == 0) return NO_INIT;
1250 return mTrack->frameCount() * frameSize();
1251}
1252
1253ssize_t MediaPlayerService::AudioOutput::frameCount() const
1254{
1255 if (mTrack == 0) return NO_INIT;
1256 return mTrack->frameCount();
1257}
1258
1259ssize_t MediaPlayerService::AudioOutput::channelCount() const
1260{
1261 if (mTrack == 0) return NO_INIT;
1262 return mTrack->channelCount();
1263}
1264
1265ssize_t MediaPlayerService::AudioOutput::frameSize() const
1266{
1267 if (mTrack == 0) return NO_INIT;
1268 return mTrack->frameSize();
1269}
1270
1271uint32_t MediaPlayerService::AudioOutput::latency () const
1272{
1273 return mLatency;
1274}
1275
1276float MediaPlayerService::AudioOutput::msecsPerFrame() const
1277{
1278 return mMsecsPerFrame;
1279}
1280
Eric Laurent342e9cf2010-01-19 17:37:09 -08001281status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1282{
1283 if (mTrack == 0) return NO_INIT;
1284 return mTrack->getPosition(position);
1285}
1286
Andreas Huber20111aa2009-07-14 16:56:47 -07001287status_t MediaPlayerService::AudioOutput::open(
1288 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1289 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001290{
Andreas Huber20111aa2009-07-14 16:56:47 -07001291 mCallback = cb;
1292 mCallbackCookie = cookie;
1293
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001294 // Check argument "bufferCount" against the mininum buffer count
1295 if (bufferCount < mMinBufferCount) {
1296 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1297 bufferCount = mMinBufferCount;
1298
1299 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001300 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001301 if (mTrack) close();
1302 int afSampleRate;
1303 int afFrameCount;
1304 int frameCount;
1305
1306 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1307 return NO_INIT;
1308 }
1309 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1310 return NO_INIT;
1311 }
1312
1313 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001314
1315 AudioTrack *t;
1316 if (mCallback != NULL) {
1317 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001318 mStreamType,
1319 sampleRate,
1320 format,
1321 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1322 frameCount,
1323 0 /* flags */,
1324 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001325 this,
1326 0,
1327 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001328 } else {
1329 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001330 mStreamType,
1331 sampleRate,
1332 format,
1333 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001334 frameCount,
1335 0,
1336 NULL,
1337 NULL,
1338 0,
1339 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001340 }
1341
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001342 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1343 LOGE("Unable to create audio track");
1344 delete t;
1345 return NO_INIT;
1346 }
1347
1348 LOGV("setVolume");
1349 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001350
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001351 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001352 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001353 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001354
1355 t->setAuxEffectSendLevel(mSendLevel);
1356 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001357}
1358
1359void MediaPlayerService::AudioOutput::start()
1360{
1361 LOGV("start");
1362 if (mTrack) {
1363 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001364 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001365 mTrack->start();
1366 }
1367}
1368
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001369
1370
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001371ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1372{
Andreas Huber20111aa2009-07-14 16:56:47 -07001373 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1374
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001376 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001377 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001378 return ret;
1379 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380 return NO_INIT;
1381}
1382
1383void MediaPlayerService::AudioOutput::stop()
1384{
1385 LOGV("stop");
1386 if (mTrack) mTrack->stop();
1387}
1388
1389void MediaPlayerService::AudioOutput::flush()
1390{
1391 LOGV("flush");
1392 if (mTrack) mTrack->flush();
1393}
1394
1395void MediaPlayerService::AudioOutput::pause()
1396{
1397 LOGV("pause");
1398 if (mTrack) mTrack->pause();
1399}
1400
1401void MediaPlayerService::AudioOutput::close()
1402{
1403 LOGV("close");
1404 delete mTrack;
1405 mTrack = 0;
1406}
1407
1408void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1409{
1410 LOGV("setVolume(%f, %f)", left, right);
1411 mLeftVolume = left;
1412 mRightVolume = right;
1413 if (mTrack) {
1414 mTrack->setVolume(left, right);
1415 }
1416}
1417
Eric Laurent2beeb502010-07-16 07:43:46 -07001418status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1419{
1420 LOGV("setAuxEffectSendLevel(%f)", level);
1421 mSendLevel = level;
1422 if (mTrack) {
1423 return mTrack->setAuxEffectSendLevel(level);
1424 }
1425 return NO_ERROR;
1426}
1427
1428status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1429{
1430 LOGV("attachAuxEffect(%d)", effectId);
1431 mAuxEffectId = effectId;
1432 if (mTrack) {
1433 return mTrack->attachAuxEffect(effectId);
1434 }
1435 return NO_ERROR;
1436}
1437
Andreas Huber20111aa2009-07-14 16:56:47 -07001438// static
1439void MediaPlayerService::AudioOutput::CallbackWrapper(
1440 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001441 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001442 if (event != AudioTrack::EVENT_MORE_DATA) {
1443 return;
1444 }
1445
1446 AudioOutput *me = (AudioOutput *)cookie;
1447 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1448
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001449 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001450 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001451
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001452 buffer->size = actualSize;
1453
Andreas Huber20111aa2009-07-14 16:56:47 -07001454}
1455
Eric Laurent8c563ed2010-10-07 18:23:03 -07001456int MediaPlayerService::AudioOutput::getSessionId()
1457{
1458 return mSessionId;
1459}
1460
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001461#undef LOG_TAG
1462#define LOG_TAG "AudioCache"
1463MediaPlayerService::AudioCache::AudioCache(const char* name) :
1464 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1465 mError(NO_ERROR), mCommandComplete(false)
1466{
1467 // create ashmem heap
1468 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1469}
1470
1471uint32_t MediaPlayerService::AudioCache::latency () const
1472{
1473 return 0;
1474}
1475
1476float MediaPlayerService::AudioCache::msecsPerFrame() const
1477{
1478 return mMsecsPerFrame;
1479}
1480
Eric Laurent342e9cf2010-01-19 17:37:09 -08001481status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1482{
1483 if (position == 0) return BAD_VALUE;
1484 *position = mSize;
1485 return NO_ERROR;
1486}
1487
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001488////////////////////////////////////////////////////////////////////////////////
1489
1490struct CallbackThread : public Thread {
1491 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1492 MediaPlayerBase::AudioSink::AudioCallback cb,
1493 void *cookie);
1494
1495protected:
1496 virtual ~CallbackThread();
1497
1498 virtual bool threadLoop();
1499
1500private:
1501 wp<MediaPlayerBase::AudioSink> mSink;
1502 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1503 void *mCookie;
1504 void *mBuffer;
1505 size_t mBufferSize;
1506
1507 CallbackThread(const CallbackThread &);
1508 CallbackThread &operator=(const CallbackThread &);
1509};
1510
1511CallbackThread::CallbackThread(
1512 const wp<MediaPlayerBase::AudioSink> &sink,
1513 MediaPlayerBase::AudioSink::AudioCallback cb,
1514 void *cookie)
1515 : mSink(sink),
1516 mCallback(cb),
1517 mCookie(cookie),
1518 mBuffer(NULL),
1519 mBufferSize(0) {
1520}
1521
1522CallbackThread::~CallbackThread() {
1523 if (mBuffer) {
1524 free(mBuffer);
1525 mBuffer = NULL;
1526 }
1527}
1528
1529bool CallbackThread::threadLoop() {
1530 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1531 if (sink == NULL) {
1532 return false;
1533 }
1534
1535 if (mBuffer == NULL) {
1536 mBufferSize = sink->bufferSize();
1537 mBuffer = malloc(mBufferSize);
1538 }
1539
1540 size_t actualSize =
1541 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1542
1543 if (actualSize > 0) {
1544 sink->write(mBuffer, actualSize);
1545 }
1546
1547 return true;
1548}
1549
1550////////////////////////////////////////////////////////////////////////////////
1551
Andreas Huber20111aa2009-07-14 16:56:47 -07001552status_t MediaPlayerService::AudioCache::open(
1553 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1554 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001555{
Dave Sparks8eb80112009-12-09 20:20:26 -08001556 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001557 if (mHeap->getHeapID() < 0) {
1558 return NO_INIT;
1559 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001560
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001561 mSampleRate = sampleRate;
1562 mChannelCount = (uint16_t)channelCount;
1563 mFormat = (uint16_t)format;
1564 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001565
1566 if (cb != NULL) {
1567 mCallbackThread = new CallbackThread(this, cb, cookie);
1568 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001569 return NO_ERROR;
1570}
1571
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001572void MediaPlayerService::AudioCache::start() {
1573 if (mCallbackThread != NULL) {
1574 mCallbackThread->run("AudioCache callback");
1575 }
1576}
1577
1578void MediaPlayerService::AudioCache::stop() {
1579 if (mCallbackThread != NULL) {
1580 mCallbackThread->requestExitAndWait();
1581 }
1582}
1583
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001584ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1585{
1586 LOGV("write(%p, %u)", buffer, size);
1587 if ((buffer == 0) || (size == 0)) return size;
1588
1589 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1590 if (p == NULL) return NO_INIT;
1591 p += mSize;
1592 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1593 if (mSize + size > mHeap->getSize()) {
1594 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1595 size = mHeap->getSize() - mSize;
1596 }
1597 memcpy(p, buffer, size);
1598 mSize += size;
1599 return size;
1600}
1601
1602// call with lock held
1603status_t MediaPlayerService::AudioCache::wait()
1604{
1605 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001606 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607 mSignal.wait(mLock);
1608 }
1609 mCommandComplete = false;
1610
1611 if (mError == NO_ERROR) {
1612 LOGV("wait - success");
1613 } else {
1614 LOGV("wait - error");
1615 }
1616 return mError;
1617}
1618
1619void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1620{
1621 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1622 AudioCache* p = static_cast<AudioCache*>(cookie);
1623
1624 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001625 switch (msg)
1626 {
1627 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001628 LOGE("Error %d, %d occurred", ext1, ext2);
1629 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001630 break;
1631 case MEDIA_PREPARED:
1632 LOGV("prepared");
1633 break;
1634 case MEDIA_PLAYBACK_COMPLETE:
1635 LOGV("playback complete");
1636 break;
1637 default:
1638 LOGV("ignored");
1639 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001640 }
1641
1642 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001643 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001644 p->mCommandComplete = true;
1645 p->mSignal.signal();
1646}
1647
Eric Laurent8c563ed2010-10-07 18:23:03 -07001648int MediaPlayerService::AudioCache::getSessionId()
1649{
1650 return 0;
1651}
1652
Gloria Wang7cf180c2011-02-19 18:37:57 -08001653void MediaPlayerService::addBatteryData(uint32_t params)
1654{
1655 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001656
1657 int32_t time = systemTime() / 1000000L;
1658
1659 // change audio output devices. This notification comes from AudioFlinger
1660 if ((params & kBatteryDataSpeakerOn)
1661 || (params & kBatteryDataOtherAudioDeviceOn)) {
1662
1663 int deviceOn[NUM_AUDIO_DEVICES];
1664 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1665 deviceOn[i] = 0;
1666 }
1667
1668 if ((params & kBatteryDataSpeakerOn)
1669 && (params & kBatteryDataOtherAudioDeviceOn)) {
1670 deviceOn[SPEAKER_AND_OTHER] = 1;
1671 } else if (params & kBatteryDataSpeakerOn) {
1672 deviceOn[SPEAKER] = 1;
1673 } else {
1674 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1675 }
1676
1677 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1678 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1679
1680 if (mBatteryAudio.refCount > 0) { // if playing audio
1681 if (!deviceOn[i]) {
1682 mBatteryAudio.lastTime[i] += time;
1683 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1684 mBatteryAudio.lastTime[i] = 0;
1685 } else {
1686 mBatteryAudio.lastTime[i] = 0 - time;
1687 }
1688 }
1689
1690 mBatteryAudio.deviceOn[i] = deviceOn[i];
1691 }
1692 }
1693 return;
1694 }
1695
1696 // an sudio stream is started
1697 if (params & kBatteryDataAudioFlingerStart) {
1698 // record the start time only if currently no other audio
1699 // is being played
1700 if (mBatteryAudio.refCount == 0) {
1701 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1702 if (mBatteryAudio.deviceOn[i]) {
1703 mBatteryAudio.lastTime[i] -= time;
1704 }
1705 }
1706 }
1707
1708 mBatteryAudio.refCount ++;
1709 return;
1710
1711 } else if (params & kBatteryDataAudioFlingerStop) {
1712 if (mBatteryAudio.refCount <= 0) {
1713 LOGW("Battery track warning: refCount is <= 0");
1714 return;
1715 }
1716
1717 // record the stop time only if currently this is the only
1718 // audio being played
1719 if (mBatteryAudio.refCount == 1) {
1720 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1721 if (mBatteryAudio.deviceOn[i]) {
1722 mBatteryAudio.lastTime[i] += time;
1723 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1724 mBatteryAudio.lastTime[i] = 0;
1725 }
1726 }
1727 }
1728
1729 mBatteryAudio.refCount --;
1730 return;
1731 }
1732
Gloria Wang7cf180c2011-02-19 18:37:57 -08001733 int uid = IPCThreadState::self()->getCallingUid();
1734 if (uid == AID_MEDIA) {
1735 return;
1736 }
1737 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001738
1739 if (index < 0) { // create a new entry for this UID
1740 BatteryUsageInfo info;
1741 info.audioTotalTime = 0;
1742 info.videoTotalTime = 0;
1743 info.audioLastTime = 0;
1744 info.videoLastTime = 0;
1745 info.refCount = 0;
1746
Gloria Wang9ee159b2011-02-24 14:51:45 -08001747 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1748 LOGE("Battery track error: no memory for new app");
1749 return;
1750 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001751 }
1752
1753 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1754
1755 if (params & kBatteryDataCodecStarted) {
1756 if (params & kBatteryDataTrackAudio) {
1757 info.audioLastTime -= time;
1758 info.refCount ++;
1759 }
1760 if (params & kBatteryDataTrackVideo) {
1761 info.videoLastTime -= time;
1762 info.refCount ++;
1763 }
1764 } else {
1765 if (info.refCount == 0) {
1766 LOGW("Battery track warning: refCount is already 0");
1767 return;
1768 } else if (info.refCount < 0) {
1769 LOGE("Battery track error: refCount < 0");
1770 mBatteryData.removeItem(uid);
1771 return;
1772 }
1773
1774 if (params & kBatteryDataTrackAudio) {
1775 info.audioLastTime += time;
1776 info.refCount --;
1777 }
1778 if (params & kBatteryDataTrackVideo) {
1779 info.videoLastTime += time;
1780 info.refCount --;
1781 }
1782
1783 // no stream is being played by this UID
1784 if (info.refCount == 0) {
1785 info.audioTotalTime += info.audioLastTime;
1786 info.audioLastTime = 0;
1787 info.videoTotalTime += info.videoLastTime;
1788 info.videoLastTime = 0;
1789 }
1790 }
1791}
1792
1793status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1794 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001795
1796 // audio output devices usage
1797 int32_t time = systemTime() / 1000000L; //in ms
1798 int32_t totalTime;
1799
1800 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1801 totalTime = mBatteryAudio.totalTime[i];
1802
1803 if (mBatteryAudio.deviceOn[i]
1804 && (mBatteryAudio.lastTime[i] != 0)) {
1805 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1806 totalTime += tmpTime;
1807 }
1808
1809 reply->writeInt32(totalTime);
1810 // reset the total time
1811 mBatteryAudio.totalTime[i] = 0;
1812 }
1813
1814 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001815 BatteryUsageInfo info;
1816 int size = mBatteryData.size();
1817
1818 reply->writeInt32(size);
1819 int i = 0;
1820
1821 while (i < size) {
1822 info = mBatteryData.valueAt(i);
1823
1824 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1825 reply->writeInt32(info.audioTotalTime);
1826 reply->writeInt32(info.videoTotalTime);
1827
1828 info.audioTotalTime = 0;
1829 info.videoTotalTime = 0;
1830
1831 // remove the UID entry where no stream is being played
1832 if (info.refCount <= 0) {
1833 mBatteryData.removeItemsAt(i);
1834 size --;
1835 i --;
1836 }
1837 i++;
1838 }
1839 return NO_ERROR;
1840}
nikoa64c8c72009-07-20 15:07:26 -07001841} // namespace android