blob: 6b977085d83e491274e72559943bb3d8066150bb [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
Gloria Wangb483c472011-04-11 17:23:27 -07001025void MediaPlayerService::Client::notify(
1026 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001027{
1028 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001029
1030 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001031 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001032 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001033
1034 if(client->shouldDropMetadata(metadata_type)) {
1035 return;
1036 }
1037
1038 // Update the list of metadata that have changed. getMetadata
1039 // also access mMetadataUpdated and clears it.
1040 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001041 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001043 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001044}
1045
Nicolas Catania48290382009-07-10 13:53:06 -07001046
nikoa64c8c72009-07-20 15:07:26 -07001047bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001048{
Nicolas Catania48290382009-07-10 13:53:06 -07001049 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001050
Nicolas Catania48290382009-07-10 13:53:06 -07001051 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001052 return true;
1053 }
1054
Nicolas Catania48290382009-07-10 13:53:06 -07001055 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001056 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001057 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001058 return true;
1059 }
1060}
1061
Nicolas Catania48290382009-07-10 13:53:06 -07001062
nikoa64c8c72009-07-20 15:07:26 -07001063void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001064 Mutex::Autolock lock(mLock);
1065 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1066 mMetadataUpdated.add(metadata_type);
1067 }
1068}
1069
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001070#if CALLBACK_ANTAGONIZER
1071const int Antagonizer::interval = 10000; // 10 msecs
1072
1073Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1074 mExit(false), mActive(false), mClient(client), mCb(cb)
1075{
1076 createThread(callbackThread, this);
1077}
1078
1079void Antagonizer::kill()
1080{
1081 Mutex::Autolock _l(mLock);
1082 mActive = false;
1083 mExit = true;
1084 mCondition.wait(mLock);
1085}
1086
1087int Antagonizer::callbackThread(void* user)
1088{
1089 LOGD("Antagonizer started");
1090 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1091 while (!p->mExit) {
1092 if (p->mActive) {
1093 LOGV("send event");
1094 p->mCb(p->mClient, 0, 0, 0);
1095 }
1096 usleep(interval);
1097 }
1098 Mutex::Autolock _l(p->mLock);
1099 p->mCondition.signal();
1100 LOGD("Antagonizer stopped");
1101 return 0;
1102}
1103#endif
1104
1105static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1106
1107sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1108{
1109 LOGV("decode(%s)", url);
1110 sp<MemoryBase> mem;
1111 sp<MediaPlayerBase> player;
1112
1113 // Protect our precious, precious DRMd ringtones by only allowing
1114 // decoding of http, but not filesystem paths or content Uris.
1115 // If the application wants to decode those, it should open a
1116 // filedescriptor for them and use that.
1117 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1118 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1119 return mem;
1120 }
1121
1122 player_type playerType = getPlayerType(url);
1123 LOGV("player type = %d", playerType);
1124
1125 // create the right type of player
1126 sp<AudioCache> cache = new AudioCache(url);
1127 player = android::createPlayer(playerType, cache.get(), cache->notify);
1128 if (player == NULL) goto Exit;
1129 if (player->hardwareOutput()) goto Exit;
1130
1131 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1132
1133 // set data source
1134 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1135
1136 LOGV("prepare");
1137 player->prepareAsync();
1138
1139 LOGV("wait for prepare");
1140 if (cache->wait() != NO_ERROR) goto Exit;
1141
1142 LOGV("start");
1143 player->start();
1144
1145 LOGV("wait for playback complete");
1146 if (cache->wait() != NO_ERROR) goto Exit;
1147
1148 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1149 *pSampleRate = cache->sampleRate();
1150 *pNumChannels = cache->channelCount();
1151 *pFormat = cache->format();
1152 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1153
1154Exit:
1155 if (player != 0) player->reset();
1156 return mem;
1157}
1158
1159sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1160{
1161 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1162 sp<MemoryBase> mem;
1163 sp<MediaPlayerBase> player;
1164
1165 player_type playerType = getPlayerType(fd, offset, length);
1166 LOGV("player type = %d", playerType);
1167
1168 // create the right type of player
1169 sp<AudioCache> cache = new AudioCache("decode_fd");
1170 player = android::createPlayer(playerType, cache.get(), cache->notify);
1171 if (player == NULL) goto Exit;
1172 if (player->hardwareOutput()) goto Exit;
1173
1174 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1175
1176 // set data source
1177 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1178
1179 LOGV("prepare");
1180 player->prepareAsync();
1181
1182 LOGV("wait for prepare");
1183 if (cache->wait() != NO_ERROR) goto Exit;
1184
1185 LOGV("start");
1186 player->start();
1187
1188 LOGV("wait for playback complete");
1189 if (cache->wait() != NO_ERROR) goto Exit;
1190
1191 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1192 *pSampleRate = cache->sampleRate();
1193 *pNumChannels = cache->channelCount();
1194 *pFormat = cache->format();
1195 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1196
1197Exit:
1198 if (player != 0) player->reset();
1199 ::close(fd);
1200 return mem;
1201}
1202
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001203
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001204#undef LOG_TAG
1205#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001206MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001207 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001208 mCallbackCookie(NULL),
1209 mSessionId(sessionId) {
1210 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001211 mTrack = 0;
1212 mStreamType = AudioSystem::MUSIC;
1213 mLeftVolume = 1.0;
1214 mRightVolume = 1.0;
1215 mLatency = 0;
1216 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001217 mAuxEffectId = 0;
1218 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001219 setMinBufferCount();
1220}
1221
1222MediaPlayerService::AudioOutput::~AudioOutput()
1223{
1224 close();
1225}
1226
1227void MediaPlayerService::AudioOutput::setMinBufferCount()
1228{
1229 char value[PROPERTY_VALUE_MAX];
1230 if (property_get("ro.kernel.qemu", value, 0)) {
1231 mIsOnEmulator = true;
1232 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1233 }
1234}
1235
1236bool MediaPlayerService::AudioOutput::isOnEmulator()
1237{
1238 setMinBufferCount();
1239 return mIsOnEmulator;
1240}
1241
1242int MediaPlayerService::AudioOutput::getMinBufferCount()
1243{
1244 setMinBufferCount();
1245 return mMinBufferCount;
1246}
1247
1248ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1249{
1250 if (mTrack == 0) return NO_INIT;
1251 return mTrack->frameCount() * frameSize();
1252}
1253
1254ssize_t MediaPlayerService::AudioOutput::frameCount() const
1255{
1256 if (mTrack == 0) return NO_INIT;
1257 return mTrack->frameCount();
1258}
1259
1260ssize_t MediaPlayerService::AudioOutput::channelCount() const
1261{
1262 if (mTrack == 0) return NO_INIT;
1263 return mTrack->channelCount();
1264}
1265
1266ssize_t MediaPlayerService::AudioOutput::frameSize() const
1267{
1268 if (mTrack == 0) return NO_INIT;
1269 return mTrack->frameSize();
1270}
1271
1272uint32_t MediaPlayerService::AudioOutput::latency () const
1273{
1274 return mLatency;
1275}
1276
1277float MediaPlayerService::AudioOutput::msecsPerFrame() const
1278{
1279 return mMsecsPerFrame;
1280}
1281
Eric Laurent342e9cf2010-01-19 17:37:09 -08001282status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1283{
1284 if (mTrack == 0) return NO_INIT;
1285 return mTrack->getPosition(position);
1286}
1287
Andreas Huber20111aa2009-07-14 16:56:47 -07001288status_t MediaPlayerService::AudioOutput::open(
1289 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1290 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001291{
Andreas Huber20111aa2009-07-14 16:56:47 -07001292 mCallback = cb;
1293 mCallbackCookie = cookie;
1294
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001295 // Check argument "bufferCount" against the mininum buffer count
1296 if (bufferCount < mMinBufferCount) {
1297 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1298 bufferCount = mMinBufferCount;
1299
1300 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001301 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001302 if (mTrack) close();
1303 int afSampleRate;
1304 int afFrameCount;
1305 int frameCount;
1306
1307 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1308 return NO_INIT;
1309 }
1310 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1311 return NO_INIT;
1312 }
1313
1314 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001315
1316 AudioTrack *t;
1317 if (mCallback != NULL) {
1318 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001319 mStreamType,
1320 sampleRate,
1321 format,
1322 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1323 frameCount,
1324 0 /* flags */,
1325 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001326 this,
1327 0,
1328 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001329 } else {
1330 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001331 mStreamType,
1332 sampleRate,
1333 format,
1334 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001335 frameCount,
1336 0,
1337 NULL,
1338 NULL,
1339 0,
1340 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001341 }
1342
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001343 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1344 LOGE("Unable to create audio track");
1345 delete t;
1346 return NO_INIT;
1347 }
1348
1349 LOGV("setVolume");
1350 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001351
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001353 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001354 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001355
1356 t->setAuxEffectSendLevel(mSendLevel);
1357 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358}
1359
1360void MediaPlayerService::AudioOutput::start()
1361{
1362 LOGV("start");
1363 if (mTrack) {
1364 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001365 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366 mTrack->start();
1367 }
1368}
1369
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001370
1371
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1373{
Andreas Huber20111aa2009-07-14 16:56:47 -07001374 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1375
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001377 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001378 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001379 return ret;
1380 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001381 return NO_INIT;
1382}
1383
1384void MediaPlayerService::AudioOutput::stop()
1385{
1386 LOGV("stop");
1387 if (mTrack) mTrack->stop();
1388}
1389
1390void MediaPlayerService::AudioOutput::flush()
1391{
1392 LOGV("flush");
1393 if (mTrack) mTrack->flush();
1394}
1395
1396void MediaPlayerService::AudioOutput::pause()
1397{
1398 LOGV("pause");
1399 if (mTrack) mTrack->pause();
1400}
1401
1402void MediaPlayerService::AudioOutput::close()
1403{
1404 LOGV("close");
1405 delete mTrack;
1406 mTrack = 0;
1407}
1408
1409void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1410{
1411 LOGV("setVolume(%f, %f)", left, right);
1412 mLeftVolume = left;
1413 mRightVolume = right;
1414 if (mTrack) {
1415 mTrack->setVolume(left, right);
1416 }
1417}
1418
Eric Laurent2beeb502010-07-16 07:43:46 -07001419status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1420{
1421 LOGV("setAuxEffectSendLevel(%f)", level);
1422 mSendLevel = level;
1423 if (mTrack) {
1424 return mTrack->setAuxEffectSendLevel(level);
1425 }
1426 return NO_ERROR;
1427}
1428
1429status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1430{
1431 LOGV("attachAuxEffect(%d)", effectId);
1432 mAuxEffectId = effectId;
1433 if (mTrack) {
1434 return mTrack->attachAuxEffect(effectId);
1435 }
1436 return NO_ERROR;
1437}
1438
Andreas Huber20111aa2009-07-14 16:56:47 -07001439// static
1440void MediaPlayerService::AudioOutput::CallbackWrapper(
1441 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001442 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001443 if (event != AudioTrack::EVENT_MORE_DATA) {
1444 return;
1445 }
1446
1447 AudioOutput *me = (AudioOutput *)cookie;
1448 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1449
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001450 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001451 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001452
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001453 if (actualSize == 0 && buffer->size > 0) {
1454 // We've reached EOS but the audio track is not stopped yet,
1455 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001456
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001457 memset(buffer->raw, 0, buffer->size);
1458 actualSize = buffer->size;
1459 }
1460
1461 buffer->size = actualSize;
Andreas Huber20111aa2009-07-14 16:56:47 -07001462}
1463
Eric Laurent8c563ed2010-10-07 18:23:03 -07001464int MediaPlayerService::AudioOutput::getSessionId()
1465{
1466 return mSessionId;
1467}
1468
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001469#undef LOG_TAG
1470#define LOG_TAG "AudioCache"
1471MediaPlayerService::AudioCache::AudioCache(const char* name) :
1472 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1473 mError(NO_ERROR), mCommandComplete(false)
1474{
1475 // create ashmem heap
1476 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1477}
1478
1479uint32_t MediaPlayerService::AudioCache::latency () const
1480{
1481 return 0;
1482}
1483
1484float MediaPlayerService::AudioCache::msecsPerFrame() const
1485{
1486 return mMsecsPerFrame;
1487}
1488
Eric Laurent342e9cf2010-01-19 17:37:09 -08001489status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1490{
1491 if (position == 0) return BAD_VALUE;
1492 *position = mSize;
1493 return NO_ERROR;
1494}
1495
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001496////////////////////////////////////////////////////////////////////////////////
1497
1498struct CallbackThread : public Thread {
1499 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1500 MediaPlayerBase::AudioSink::AudioCallback cb,
1501 void *cookie);
1502
1503protected:
1504 virtual ~CallbackThread();
1505
1506 virtual bool threadLoop();
1507
1508private:
1509 wp<MediaPlayerBase::AudioSink> mSink;
1510 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1511 void *mCookie;
1512 void *mBuffer;
1513 size_t mBufferSize;
1514
1515 CallbackThread(const CallbackThread &);
1516 CallbackThread &operator=(const CallbackThread &);
1517};
1518
1519CallbackThread::CallbackThread(
1520 const wp<MediaPlayerBase::AudioSink> &sink,
1521 MediaPlayerBase::AudioSink::AudioCallback cb,
1522 void *cookie)
1523 : mSink(sink),
1524 mCallback(cb),
1525 mCookie(cookie),
1526 mBuffer(NULL),
1527 mBufferSize(0) {
1528}
1529
1530CallbackThread::~CallbackThread() {
1531 if (mBuffer) {
1532 free(mBuffer);
1533 mBuffer = NULL;
1534 }
1535}
1536
1537bool CallbackThread::threadLoop() {
1538 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1539 if (sink == NULL) {
1540 return false;
1541 }
1542
1543 if (mBuffer == NULL) {
1544 mBufferSize = sink->bufferSize();
1545 mBuffer = malloc(mBufferSize);
1546 }
1547
1548 size_t actualSize =
1549 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1550
1551 if (actualSize > 0) {
1552 sink->write(mBuffer, actualSize);
1553 }
1554
1555 return true;
1556}
1557
1558////////////////////////////////////////////////////////////////////////////////
1559
Andreas Huber20111aa2009-07-14 16:56:47 -07001560status_t MediaPlayerService::AudioCache::open(
1561 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1562 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001563{
Dave Sparks8eb80112009-12-09 20:20:26 -08001564 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001565 if (mHeap->getHeapID() < 0) {
1566 return NO_INIT;
1567 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001568
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001569 mSampleRate = sampleRate;
1570 mChannelCount = (uint16_t)channelCount;
1571 mFormat = (uint16_t)format;
1572 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001573
1574 if (cb != NULL) {
1575 mCallbackThread = new CallbackThread(this, cb, cookie);
1576 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001577 return NO_ERROR;
1578}
1579
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001580void MediaPlayerService::AudioCache::start() {
1581 if (mCallbackThread != NULL) {
1582 mCallbackThread->run("AudioCache callback");
1583 }
1584}
1585
1586void MediaPlayerService::AudioCache::stop() {
1587 if (mCallbackThread != NULL) {
1588 mCallbackThread->requestExitAndWait();
1589 }
1590}
1591
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001592ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1593{
1594 LOGV("write(%p, %u)", buffer, size);
1595 if ((buffer == 0) || (size == 0)) return size;
1596
1597 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1598 if (p == NULL) return NO_INIT;
1599 p += mSize;
1600 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1601 if (mSize + size > mHeap->getSize()) {
1602 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1603 size = mHeap->getSize() - mSize;
1604 }
1605 memcpy(p, buffer, size);
1606 mSize += size;
1607 return size;
1608}
1609
1610// call with lock held
1611status_t MediaPlayerService::AudioCache::wait()
1612{
1613 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001614 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001615 mSignal.wait(mLock);
1616 }
1617 mCommandComplete = false;
1618
1619 if (mError == NO_ERROR) {
1620 LOGV("wait - success");
1621 } else {
1622 LOGV("wait - error");
1623 }
1624 return mError;
1625}
1626
Gloria Wangb483c472011-04-11 17:23:27 -07001627void MediaPlayerService::AudioCache::notify(
1628 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001629{
1630 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1631 AudioCache* p = static_cast<AudioCache*>(cookie);
1632
1633 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001634 switch (msg)
1635 {
1636 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001637 LOGE("Error %d, %d occurred", ext1, ext2);
1638 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001639 break;
1640 case MEDIA_PREPARED:
1641 LOGV("prepared");
1642 break;
1643 case MEDIA_PLAYBACK_COMPLETE:
1644 LOGV("playback complete");
1645 break;
1646 default:
1647 LOGV("ignored");
1648 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001649 }
1650
1651 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001652 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001653 p->mCommandComplete = true;
1654 p->mSignal.signal();
1655}
1656
Eric Laurent8c563ed2010-10-07 18:23:03 -07001657int MediaPlayerService::AudioCache::getSessionId()
1658{
1659 return 0;
1660}
1661
Gloria Wang7cf180c2011-02-19 18:37:57 -08001662void MediaPlayerService::addBatteryData(uint32_t params)
1663{
1664 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001665
1666 int32_t time = systemTime() / 1000000L;
1667
1668 // change audio output devices. This notification comes from AudioFlinger
1669 if ((params & kBatteryDataSpeakerOn)
1670 || (params & kBatteryDataOtherAudioDeviceOn)) {
1671
1672 int deviceOn[NUM_AUDIO_DEVICES];
1673 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1674 deviceOn[i] = 0;
1675 }
1676
1677 if ((params & kBatteryDataSpeakerOn)
1678 && (params & kBatteryDataOtherAudioDeviceOn)) {
1679 deviceOn[SPEAKER_AND_OTHER] = 1;
1680 } else if (params & kBatteryDataSpeakerOn) {
1681 deviceOn[SPEAKER] = 1;
1682 } else {
1683 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1684 }
1685
1686 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1687 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1688
1689 if (mBatteryAudio.refCount > 0) { // if playing audio
1690 if (!deviceOn[i]) {
1691 mBatteryAudio.lastTime[i] += time;
1692 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1693 mBatteryAudio.lastTime[i] = 0;
1694 } else {
1695 mBatteryAudio.lastTime[i] = 0 - time;
1696 }
1697 }
1698
1699 mBatteryAudio.deviceOn[i] = deviceOn[i];
1700 }
1701 }
1702 return;
1703 }
1704
1705 // an sudio stream is started
1706 if (params & kBatteryDataAudioFlingerStart) {
1707 // record the start time only if currently no other audio
1708 // is being played
1709 if (mBatteryAudio.refCount == 0) {
1710 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1711 if (mBatteryAudio.deviceOn[i]) {
1712 mBatteryAudio.lastTime[i] -= time;
1713 }
1714 }
1715 }
1716
1717 mBatteryAudio.refCount ++;
1718 return;
1719
1720 } else if (params & kBatteryDataAudioFlingerStop) {
1721 if (mBatteryAudio.refCount <= 0) {
1722 LOGW("Battery track warning: refCount is <= 0");
1723 return;
1724 }
1725
1726 // record the stop time only if currently this is the only
1727 // audio being played
1728 if (mBatteryAudio.refCount == 1) {
1729 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1730 if (mBatteryAudio.deviceOn[i]) {
1731 mBatteryAudio.lastTime[i] += time;
1732 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1733 mBatteryAudio.lastTime[i] = 0;
1734 }
1735 }
1736 }
1737
1738 mBatteryAudio.refCount --;
1739 return;
1740 }
1741
Gloria Wang7cf180c2011-02-19 18:37:57 -08001742 int uid = IPCThreadState::self()->getCallingUid();
1743 if (uid == AID_MEDIA) {
1744 return;
1745 }
1746 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001747
1748 if (index < 0) { // create a new entry for this UID
1749 BatteryUsageInfo info;
1750 info.audioTotalTime = 0;
1751 info.videoTotalTime = 0;
1752 info.audioLastTime = 0;
1753 info.videoLastTime = 0;
1754 info.refCount = 0;
1755
Gloria Wang9ee159b2011-02-24 14:51:45 -08001756 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1757 LOGE("Battery track error: no memory for new app");
1758 return;
1759 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001760 }
1761
1762 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1763
1764 if (params & kBatteryDataCodecStarted) {
1765 if (params & kBatteryDataTrackAudio) {
1766 info.audioLastTime -= time;
1767 info.refCount ++;
1768 }
1769 if (params & kBatteryDataTrackVideo) {
1770 info.videoLastTime -= time;
1771 info.refCount ++;
1772 }
1773 } else {
1774 if (info.refCount == 0) {
1775 LOGW("Battery track warning: refCount is already 0");
1776 return;
1777 } else if (info.refCount < 0) {
1778 LOGE("Battery track error: refCount < 0");
1779 mBatteryData.removeItem(uid);
1780 return;
1781 }
1782
1783 if (params & kBatteryDataTrackAudio) {
1784 info.audioLastTime += time;
1785 info.refCount --;
1786 }
1787 if (params & kBatteryDataTrackVideo) {
1788 info.videoLastTime += time;
1789 info.refCount --;
1790 }
1791
1792 // no stream is being played by this UID
1793 if (info.refCount == 0) {
1794 info.audioTotalTime += info.audioLastTime;
1795 info.audioLastTime = 0;
1796 info.videoTotalTime += info.videoLastTime;
1797 info.videoLastTime = 0;
1798 }
1799 }
1800}
1801
1802status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1803 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001804
1805 // audio output devices usage
1806 int32_t time = systemTime() / 1000000L; //in ms
1807 int32_t totalTime;
1808
1809 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1810 totalTime = mBatteryAudio.totalTime[i];
1811
1812 if (mBatteryAudio.deviceOn[i]
1813 && (mBatteryAudio.lastTime[i] != 0)) {
1814 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1815 totalTime += tmpTime;
1816 }
1817
1818 reply->writeInt32(totalTime);
1819 // reset the total time
1820 mBatteryAudio.totalTime[i] = 0;
1821 }
1822
1823 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001824 BatteryUsageInfo info;
1825 int size = mBatteryData.size();
1826
1827 reply->writeInt32(size);
1828 int i = 0;
1829
1830 while (i < size) {
1831 info = mBatteryData.valueAt(i);
1832
1833 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1834 reply->writeInt32(info.audioTotalTime);
1835 reply->writeInt32(info.videoTotalTime);
1836
1837 info.audioTotalTime = 0;
1838 info.videoTotalTime = 0;
1839
1840 // remove the UID entry where no stream is being played
1841 if (info.refCount <= 0) {
1842 mBatteryData.removeItemsAt(i);
1843 size --;
1844 i --;
1845 }
1846 i++;
1847 }
1848 return NO_ERROR;
1849}
nikoa64c8c72009-07-20 15:07:26 -07001850} // namespace android