blob: f075706386423700eef9e1f2954d932a76dfcfe1 [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 Hubered8d14f2011-02-16 09:05:38 -0800613 if (!strncasecmp("http://", url, 7)) {
614 size_t len = strlen(url);
615 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
616 return NU_PLAYER;
617 }
Andreas Huber5bc087c2010-12-23 10:27:40 -0800618
Andreas Hubered8d14f2011-02-16 09:05:38 -0800619 if (strstr(url,"m3u8")) {
620 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800621 }
622 }
623
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 // use MidiFile for MIDI extensions
625 int lenURL = strlen(url);
626 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
627 int len = strlen(FILE_EXTS[i].extension);
628 int start = lenURL - len;
629 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900630 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700631 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632 }
633 }
634 }
635
Andreas Huber47f59cf2009-08-07 09:30:32 -0700636 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637}
638
639static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
640 notify_callback_f notifyFunc)
641{
642 sp<MediaPlayerBase> p;
643 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 case SONIVOX_PLAYER:
645 LOGV(" create MidiFile");
646 p = new MidiFile();
647 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700648 case STAGEFRIGHT_PLAYER:
649 LOGV(" create StagefrightPlayer");
650 p = new StagefrightPlayer;
651 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800652 case NU_PLAYER:
653 LOGV(" create NuPlayer");
654 p = new NuPlayerDriver;
655 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700656 case TEST_PLAYER:
657 LOGV("Create Test Player stub");
658 p = new TestPlayerStub();
659 break;
James Dong30d713a2010-11-10 18:42:40 -0800660 default:
661 LOGE("Unknown player type: %d", playerType);
662 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663 }
664 if (p != NULL) {
665 if (p->initCheck() == NO_ERROR) {
666 p->setNotifyCallback(cookie, notifyFunc);
667 } else {
668 p.clear();
669 }
670 }
671 if (p == NULL) {
672 LOGE("Failed to create player object");
673 }
674 return p;
675}
676
677sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
678{
679 // determine if we have the right player type
680 sp<MediaPlayerBase> p = mPlayer;
681 if ((p != NULL) && (p->playerType() != playerType)) {
682 LOGV("delete player");
683 p.clear();
684 }
685 if (p == NULL) {
686 p = android::createPlayer(playerType, this, notify);
687 }
688 return p;
689}
690
Andreas Huber2db84552010-01-28 11:19:57 -0800691status_t MediaPlayerService::Client::setDataSource(
692 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693{
694 LOGV("setDataSource(%s)", url);
695 if (url == NULL)
696 return UNKNOWN_ERROR;
697
698 if (strncmp(url, "content://", 10) == 0) {
699 // get a filedescriptor for the content Uri and
700 // pass it to the setDataSource(fd) method
701
702 String16 url16(url);
703 int fd = android::openContentProviderFile(url16);
704 if (fd < 0)
705 {
706 LOGE("Couldn't open fd for %s", url);
707 return UNKNOWN_ERROR;
708 }
709 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
710 close(fd);
711 return mStatus;
712 } else {
713 player_type playerType = getPlayerType(url);
714 LOGV("player type = %d", playerType);
715
716 // create the right type of player
717 sp<MediaPlayerBase> p = createPlayer(playerType);
718 if (p == NULL) return NO_INIT;
719
720 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700721 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
723 }
724
725 // now set data source
726 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800727 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700728 if (mStatus == NO_ERROR) {
729 mPlayer = p;
730 } else {
731 LOGE(" error: %d", mStatus);
732 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800733 return mStatus;
734 }
735}
736
737status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
738{
739 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
740 struct stat sb;
741 int ret = fstat(fd, &sb);
742 if (ret != 0) {
743 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
744 return UNKNOWN_ERROR;
745 }
746
747 LOGV("st_dev = %llu", sb.st_dev);
748 LOGV("st_mode = %u", sb.st_mode);
749 LOGV("st_uid = %lu", sb.st_uid);
750 LOGV("st_gid = %lu", sb.st_gid);
751 LOGV("st_size = %llu", sb.st_size);
752
753 if (offset >= sb.st_size) {
754 LOGE("offset error");
755 ::close(fd);
756 return UNKNOWN_ERROR;
757 }
758 if (offset + length > sb.st_size) {
759 length = sb.st_size - offset;
760 LOGV("calculated length = %lld", length);
761 }
762
763 player_type playerType = getPlayerType(fd, offset, length);
764 LOGV("player type = %d", playerType);
765
766 // create the right type of player
767 sp<MediaPlayerBase> p = createPlayer(playerType);
768 if (p == NULL) return NO_INIT;
769
770 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700771 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
773 }
774
775 // now set data source
776 mStatus = p->setDataSource(fd, offset, length);
777 if (mStatus == NO_ERROR) mPlayer = p;
778 return mStatus;
779}
780
Andreas Hubere2b10282010-11-23 11:41:34 -0800781status_t MediaPlayerService::Client::setDataSource(
782 const sp<IStreamSource> &source) {
783 // create the right type of player
Andreas Huberf9334412010-12-15 15:17:42 -0800784 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Hubere2b10282010-11-23 11:41:34 -0800785
786 if (p == NULL) {
787 return NO_INIT;
788 }
789
790 if (!p->hardwareOutput()) {
791 mAudioOutput = new AudioOutput(mAudioSessionId);
792 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
793 }
794
795 // now set data source
796 mStatus = p->setDataSource(source);
797
798 if (mStatus == OK) {
799 mPlayer = p;
800 }
801
802 return mStatus;
803}
804
Andreas Huber5daeb122010-08-16 08:49:37 -0700805status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800806{
807 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
808 sp<MediaPlayerBase> p = getPlayer();
809 if (p == 0) return UNKNOWN_ERROR;
810 return p->setVideoSurface(surface);
811}
812
Glenn Kasten11731182011-02-08 17:26:17 -0800813status_t MediaPlayerService::Client::setVideoSurfaceTexture(
814 const sp<ISurfaceTexture>& surfaceTexture)
815{
816 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
817 sp<MediaPlayerBase> p = getPlayer();
818 if (p == 0) return UNKNOWN_ERROR;
819 return p->setVideoSurfaceTexture(surfaceTexture);
820}
821
Nicolas Catania1d187f12009-05-12 23:25:55 -0700822status_t MediaPlayerService::Client::invoke(const Parcel& request,
823 Parcel *reply)
824{
825 sp<MediaPlayerBase> p = getPlayer();
826 if (p == NULL) return UNKNOWN_ERROR;
827 return p->invoke(request, reply);
828}
829
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700830// This call doesn't need to access the native player.
831status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
832{
833 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700834 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700835
Nicolas Catania48290382009-07-10 13:53:06 -0700836 if (unmarshallFilter(filter, &allow, &status) &&
837 unmarshallFilter(filter, &drop, &status)) {
838 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700839
840 mMetadataAllow = allow;
841 mMetadataDrop = drop;
842 }
843 return status;
844}
845
Nicolas Catania48290382009-07-10 13:53:06 -0700846status_t MediaPlayerService::Client::getMetadata(
847 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700848{
nikoa64c8c72009-07-20 15:07:26 -0700849 sp<MediaPlayerBase> player = getPlayer();
850 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700851
nikod608a812009-07-16 16:39:53 -0700852 status_t status;
853 // Placeholder for the return code, updated by the caller.
854 reply->writeInt32(-1);
855
nikoa64c8c72009-07-20 15:07:26 -0700856 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700857
858 // We don't block notifications while we fetch the data. We clear
859 // mMetadataUpdated first so we don't lose notifications happening
860 // during the rest of this call.
861 {
862 Mutex::Autolock lock(mLock);
863 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700864 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700865 }
866 mMetadataUpdated.clear();
867 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700868
nikoa64c8c72009-07-20 15:07:26 -0700869 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700870
nikoa64c8c72009-07-20 15:07:26 -0700871 metadata.appendHeader();
872 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700873
874 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700875 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700876 LOGE("getMetadata failed %d", status);
877 return status;
878 }
879
880 // FIXME: Implement filtering on the result. Not critical since
881 // filtering takes place on the update notifications already. This
882 // would be when all the metadata are fetch and a filter is set.
883
nikod608a812009-07-16 16:39:53 -0700884 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700885 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700886 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700887}
888
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800889status_t MediaPlayerService::Client::prepareAsync()
890{
891 LOGV("[%d] prepareAsync", mConnId);
892 sp<MediaPlayerBase> p = getPlayer();
893 if (p == 0) return UNKNOWN_ERROR;
894 status_t ret = p->prepareAsync();
895#if CALLBACK_ANTAGONIZER
896 LOGD("start Antagonizer");
897 if (ret == NO_ERROR) mAntagonizer->start();
898#endif
899 return ret;
900}
901
902status_t MediaPlayerService::Client::start()
903{
904 LOGV("[%d] start", mConnId);
905 sp<MediaPlayerBase> p = getPlayer();
906 if (p == 0) return UNKNOWN_ERROR;
907 p->setLooping(mLoop);
908 return p->start();
909}
910
911status_t MediaPlayerService::Client::stop()
912{
913 LOGV("[%d] stop", mConnId);
914 sp<MediaPlayerBase> p = getPlayer();
915 if (p == 0) return UNKNOWN_ERROR;
916 return p->stop();
917}
918
919status_t MediaPlayerService::Client::pause()
920{
921 LOGV("[%d] pause", mConnId);
922 sp<MediaPlayerBase> p = getPlayer();
923 if (p == 0) return UNKNOWN_ERROR;
924 return p->pause();
925}
926
927status_t MediaPlayerService::Client::isPlaying(bool* state)
928{
929 *state = false;
930 sp<MediaPlayerBase> p = getPlayer();
931 if (p == 0) return UNKNOWN_ERROR;
932 *state = p->isPlaying();
933 LOGV("[%d] isPlaying: %d", mConnId, *state);
934 return NO_ERROR;
935}
936
937status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
938{
939 LOGV("getCurrentPosition");
940 sp<MediaPlayerBase> p = getPlayer();
941 if (p == 0) return UNKNOWN_ERROR;
942 status_t ret = p->getCurrentPosition(msec);
943 if (ret == NO_ERROR) {
944 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
945 } else {
946 LOGE("getCurrentPosition returned %d", ret);
947 }
948 return ret;
949}
950
951status_t MediaPlayerService::Client::getDuration(int *msec)
952{
953 LOGV("getDuration");
954 sp<MediaPlayerBase> p = getPlayer();
955 if (p == 0) return UNKNOWN_ERROR;
956 status_t ret = p->getDuration(msec);
957 if (ret == NO_ERROR) {
958 LOGV("[%d] getDuration = %d", mConnId, *msec);
959 } else {
960 LOGE("getDuration returned %d", ret);
961 }
962 return ret;
963}
964
965status_t MediaPlayerService::Client::seekTo(int msec)
966{
967 LOGV("[%d] seekTo(%d)", mConnId, msec);
968 sp<MediaPlayerBase> p = getPlayer();
969 if (p == 0) return UNKNOWN_ERROR;
970 return p->seekTo(msec);
971}
972
973status_t MediaPlayerService::Client::reset()
974{
975 LOGV("[%d] reset", mConnId);
976 sp<MediaPlayerBase> p = getPlayer();
977 if (p == 0) return UNKNOWN_ERROR;
978 return p->reset();
979}
980
981status_t MediaPlayerService::Client::setAudioStreamType(int type)
982{
983 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
984 // TODO: for hardware output, call player instead
985 Mutex::Autolock l(mLock);
986 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
987 return NO_ERROR;
988}
989
990status_t MediaPlayerService::Client::setLooping(int loop)
991{
992 LOGV("[%d] setLooping(%d)", mConnId, loop);
993 mLoop = loop;
994 sp<MediaPlayerBase> p = getPlayer();
995 if (p != 0) return p->setLooping(loop);
996 return NO_ERROR;
997}
998
999status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1000{
1001 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1002 // TODO: for hardware output, call player instead
1003 Mutex::Autolock l(mLock);
1004 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1005 return NO_ERROR;
1006}
1007
Eric Laurent2beeb502010-07-16 07:43:46 -07001008status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1009{
1010 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1011 Mutex::Autolock l(mLock);
1012 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1013 return NO_ERROR;
1014}
1015
1016status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1017{
1018 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1019 Mutex::Autolock l(mLock);
1020 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1021 return NO_ERROR;
1022}
Nicolas Catania48290382009-07-10 13:53:06 -07001023
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001024void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1025{
1026 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001027
1028 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001029 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001030 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001031
1032 if(client->shouldDropMetadata(metadata_type)) {
1033 return;
1034 }
1035
1036 // Update the list of metadata that have changed. getMetadata
1037 // also access mMetadataUpdated and clears it.
1038 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001039 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001040 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1041 client->mClient->notify(msg, ext1, ext2);
1042}
1043
Nicolas Catania48290382009-07-10 13:53:06 -07001044
nikoa64c8c72009-07-20 15:07:26 -07001045bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001046{
Nicolas Catania48290382009-07-10 13:53:06 -07001047 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001048
Nicolas Catania48290382009-07-10 13:53:06 -07001049 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001050 return true;
1051 }
1052
Nicolas Catania48290382009-07-10 13:53:06 -07001053 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001054 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001055 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001056 return true;
1057 }
1058}
1059
Nicolas Catania48290382009-07-10 13:53:06 -07001060
nikoa64c8c72009-07-20 15:07:26 -07001061void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001062 Mutex::Autolock lock(mLock);
1063 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1064 mMetadataUpdated.add(metadata_type);
1065 }
1066}
1067
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068#if CALLBACK_ANTAGONIZER
1069const int Antagonizer::interval = 10000; // 10 msecs
1070
1071Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1072 mExit(false), mActive(false), mClient(client), mCb(cb)
1073{
1074 createThread(callbackThread, this);
1075}
1076
1077void Antagonizer::kill()
1078{
1079 Mutex::Autolock _l(mLock);
1080 mActive = false;
1081 mExit = true;
1082 mCondition.wait(mLock);
1083}
1084
1085int Antagonizer::callbackThread(void* user)
1086{
1087 LOGD("Antagonizer started");
1088 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1089 while (!p->mExit) {
1090 if (p->mActive) {
1091 LOGV("send event");
1092 p->mCb(p->mClient, 0, 0, 0);
1093 }
1094 usleep(interval);
1095 }
1096 Mutex::Autolock _l(p->mLock);
1097 p->mCondition.signal();
1098 LOGD("Antagonizer stopped");
1099 return 0;
1100}
1101#endif
1102
1103static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1104
1105sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1106{
1107 LOGV("decode(%s)", url);
1108 sp<MemoryBase> mem;
1109 sp<MediaPlayerBase> player;
1110
1111 // Protect our precious, precious DRMd ringtones by only allowing
1112 // decoding of http, but not filesystem paths or content Uris.
1113 // If the application wants to decode those, it should open a
1114 // filedescriptor for them and use that.
1115 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1116 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1117 return mem;
1118 }
1119
1120 player_type playerType = getPlayerType(url);
1121 LOGV("player type = %d", playerType);
1122
1123 // create the right type of player
1124 sp<AudioCache> cache = new AudioCache(url);
1125 player = android::createPlayer(playerType, cache.get(), cache->notify);
1126 if (player == NULL) goto Exit;
1127 if (player->hardwareOutput()) goto Exit;
1128
1129 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1130
1131 // set data source
1132 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1133
1134 LOGV("prepare");
1135 player->prepareAsync();
1136
1137 LOGV("wait for prepare");
1138 if (cache->wait() != NO_ERROR) goto Exit;
1139
1140 LOGV("start");
1141 player->start();
1142
1143 LOGV("wait for playback complete");
1144 if (cache->wait() != NO_ERROR) goto Exit;
1145
1146 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1147 *pSampleRate = cache->sampleRate();
1148 *pNumChannels = cache->channelCount();
1149 *pFormat = cache->format();
1150 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1151
1152Exit:
1153 if (player != 0) player->reset();
1154 return mem;
1155}
1156
1157sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1158{
1159 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1160 sp<MemoryBase> mem;
1161 sp<MediaPlayerBase> player;
1162
1163 player_type playerType = getPlayerType(fd, offset, length);
1164 LOGV("player type = %d", playerType);
1165
1166 // create the right type of player
1167 sp<AudioCache> cache = new AudioCache("decode_fd");
1168 player = android::createPlayer(playerType, cache.get(), cache->notify);
1169 if (player == NULL) goto Exit;
1170 if (player->hardwareOutput()) goto Exit;
1171
1172 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1173
1174 // set data source
1175 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1176
1177 LOGV("prepare");
1178 player->prepareAsync();
1179
1180 LOGV("wait for prepare");
1181 if (cache->wait() != NO_ERROR) goto Exit;
1182
1183 LOGV("start");
1184 player->start();
1185
1186 LOGV("wait for playback complete");
1187 if (cache->wait() != NO_ERROR) goto Exit;
1188
1189 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1190 *pSampleRate = cache->sampleRate();
1191 *pNumChannels = cache->channelCount();
1192 *pFormat = cache->format();
1193 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1194
1195Exit:
1196 if (player != 0) player->reset();
1197 ::close(fd);
1198 return mem;
1199}
1200
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001201
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001202#undef LOG_TAG
1203#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001204MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001205 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001206 mCallbackCookie(NULL),
1207 mSessionId(sessionId) {
1208 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001209 mTrack = 0;
1210 mStreamType = AudioSystem::MUSIC;
1211 mLeftVolume = 1.0;
1212 mRightVolume = 1.0;
1213 mLatency = 0;
1214 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001215 mAuxEffectId = 0;
1216 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001217 setMinBufferCount();
1218}
1219
1220MediaPlayerService::AudioOutput::~AudioOutput()
1221{
1222 close();
1223}
1224
1225void MediaPlayerService::AudioOutput::setMinBufferCount()
1226{
1227 char value[PROPERTY_VALUE_MAX];
1228 if (property_get("ro.kernel.qemu", value, 0)) {
1229 mIsOnEmulator = true;
1230 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1231 }
1232}
1233
1234bool MediaPlayerService::AudioOutput::isOnEmulator()
1235{
1236 setMinBufferCount();
1237 return mIsOnEmulator;
1238}
1239
1240int MediaPlayerService::AudioOutput::getMinBufferCount()
1241{
1242 setMinBufferCount();
1243 return mMinBufferCount;
1244}
1245
1246ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1247{
1248 if (mTrack == 0) return NO_INIT;
1249 return mTrack->frameCount() * frameSize();
1250}
1251
1252ssize_t MediaPlayerService::AudioOutput::frameCount() const
1253{
1254 if (mTrack == 0) return NO_INIT;
1255 return mTrack->frameCount();
1256}
1257
1258ssize_t MediaPlayerService::AudioOutput::channelCount() const
1259{
1260 if (mTrack == 0) return NO_INIT;
1261 return mTrack->channelCount();
1262}
1263
1264ssize_t MediaPlayerService::AudioOutput::frameSize() const
1265{
1266 if (mTrack == 0) return NO_INIT;
1267 return mTrack->frameSize();
1268}
1269
1270uint32_t MediaPlayerService::AudioOutput::latency () const
1271{
1272 return mLatency;
1273}
1274
1275float MediaPlayerService::AudioOutput::msecsPerFrame() const
1276{
1277 return mMsecsPerFrame;
1278}
1279
Eric Laurent342e9cf2010-01-19 17:37:09 -08001280status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1281{
1282 if (mTrack == 0) return NO_INIT;
1283 return mTrack->getPosition(position);
1284}
1285
Andreas Huber20111aa2009-07-14 16:56:47 -07001286status_t MediaPlayerService::AudioOutput::open(
1287 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1288 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289{
Andreas Huber20111aa2009-07-14 16:56:47 -07001290 mCallback = cb;
1291 mCallbackCookie = cookie;
1292
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293 // Check argument "bufferCount" against the mininum buffer count
1294 if (bufferCount < mMinBufferCount) {
1295 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1296 bufferCount = mMinBufferCount;
1297
1298 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001299 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001300 if (mTrack) close();
1301 int afSampleRate;
1302 int afFrameCount;
1303 int frameCount;
1304
1305 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1306 return NO_INIT;
1307 }
1308 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1309 return NO_INIT;
1310 }
1311
1312 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001313
1314 AudioTrack *t;
1315 if (mCallback != NULL) {
1316 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001317 mStreamType,
1318 sampleRate,
1319 format,
1320 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1321 frameCount,
1322 0 /* flags */,
1323 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001324 this,
1325 0,
1326 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001327 } else {
1328 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001329 mStreamType,
1330 sampleRate,
1331 format,
1332 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001333 frameCount,
1334 0,
1335 NULL,
1336 NULL,
1337 0,
1338 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001339 }
1340
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001341 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1342 LOGE("Unable to create audio track");
1343 delete t;
1344 return NO_INIT;
1345 }
1346
1347 LOGV("setVolume");
1348 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001349
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001351 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001353
1354 t->setAuxEffectSendLevel(mSendLevel);
1355 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001356}
1357
1358void MediaPlayerService::AudioOutput::start()
1359{
1360 LOGV("start");
1361 if (mTrack) {
1362 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001363 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364 mTrack->start();
1365 }
1366}
1367
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001368
1369
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1371{
Andreas Huber20111aa2009-07-14 16:56:47 -07001372 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1373
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001375 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001376 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001377 return ret;
1378 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001379 return NO_INIT;
1380}
1381
1382void MediaPlayerService::AudioOutput::stop()
1383{
1384 LOGV("stop");
1385 if (mTrack) mTrack->stop();
1386}
1387
1388void MediaPlayerService::AudioOutput::flush()
1389{
1390 LOGV("flush");
1391 if (mTrack) mTrack->flush();
1392}
1393
1394void MediaPlayerService::AudioOutput::pause()
1395{
1396 LOGV("pause");
1397 if (mTrack) mTrack->pause();
1398}
1399
1400void MediaPlayerService::AudioOutput::close()
1401{
1402 LOGV("close");
1403 delete mTrack;
1404 mTrack = 0;
1405}
1406
1407void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1408{
1409 LOGV("setVolume(%f, %f)", left, right);
1410 mLeftVolume = left;
1411 mRightVolume = right;
1412 if (mTrack) {
1413 mTrack->setVolume(left, right);
1414 }
1415}
1416
Eric Laurent2beeb502010-07-16 07:43:46 -07001417status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1418{
1419 LOGV("setAuxEffectSendLevel(%f)", level);
1420 mSendLevel = level;
1421 if (mTrack) {
1422 return mTrack->setAuxEffectSendLevel(level);
1423 }
1424 return NO_ERROR;
1425}
1426
1427status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1428{
1429 LOGV("attachAuxEffect(%d)", effectId);
1430 mAuxEffectId = effectId;
1431 if (mTrack) {
1432 return mTrack->attachAuxEffect(effectId);
1433 }
1434 return NO_ERROR;
1435}
1436
Andreas Huber20111aa2009-07-14 16:56:47 -07001437// static
1438void MediaPlayerService::AudioOutput::CallbackWrapper(
1439 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001440 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001441 if (event != AudioTrack::EVENT_MORE_DATA) {
1442 return;
1443 }
1444
1445 AudioOutput *me = (AudioOutput *)cookie;
1446 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1447
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001448 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001449 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001450
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001451 buffer->size = actualSize;
1452
Andreas Huber20111aa2009-07-14 16:56:47 -07001453}
1454
Eric Laurent8c563ed2010-10-07 18:23:03 -07001455int MediaPlayerService::AudioOutput::getSessionId()
1456{
1457 return mSessionId;
1458}
1459
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001460#undef LOG_TAG
1461#define LOG_TAG "AudioCache"
1462MediaPlayerService::AudioCache::AudioCache(const char* name) :
1463 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1464 mError(NO_ERROR), mCommandComplete(false)
1465{
1466 // create ashmem heap
1467 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1468}
1469
1470uint32_t MediaPlayerService::AudioCache::latency () const
1471{
1472 return 0;
1473}
1474
1475float MediaPlayerService::AudioCache::msecsPerFrame() const
1476{
1477 return mMsecsPerFrame;
1478}
1479
Eric Laurent342e9cf2010-01-19 17:37:09 -08001480status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1481{
1482 if (position == 0) return BAD_VALUE;
1483 *position = mSize;
1484 return NO_ERROR;
1485}
1486
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001487////////////////////////////////////////////////////////////////////////////////
1488
1489struct CallbackThread : public Thread {
1490 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1491 MediaPlayerBase::AudioSink::AudioCallback cb,
1492 void *cookie);
1493
1494protected:
1495 virtual ~CallbackThread();
1496
1497 virtual bool threadLoop();
1498
1499private:
1500 wp<MediaPlayerBase::AudioSink> mSink;
1501 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1502 void *mCookie;
1503 void *mBuffer;
1504 size_t mBufferSize;
1505
1506 CallbackThread(const CallbackThread &);
1507 CallbackThread &operator=(const CallbackThread &);
1508};
1509
1510CallbackThread::CallbackThread(
1511 const wp<MediaPlayerBase::AudioSink> &sink,
1512 MediaPlayerBase::AudioSink::AudioCallback cb,
1513 void *cookie)
1514 : mSink(sink),
1515 mCallback(cb),
1516 mCookie(cookie),
1517 mBuffer(NULL),
1518 mBufferSize(0) {
1519}
1520
1521CallbackThread::~CallbackThread() {
1522 if (mBuffer) {
1523 free(mBuffer);
1524 mBuffer = NULL;
1525 }
1526}
1527
1528bool CallbackThread::threadLoop() {
1529 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1530 if (sink == NULL) {
1531 return false;
1532 }
1533
1534 if (mBuffer == NULL) {
1535 mBufferSize = sink->bufferSize();
1536 mBuffer = malloc(mBufferSize);
1537 }
1538
1539 size_t actualSize =
1540 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1541
1542 if (actualSize > 0) {
1543 sink->write(mBuffer, actualSize);
1544 }
1545
1546 return true;
1547}
1548
1549////////////////////////////////////////////////////////////////////////////////
1550
Andreas Huber20111aa2009-07-14 16:56:47 -07001551status_t MediaPlayerService::AudioCache::open(
1552 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1553 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001554{
Dave Sparks8eb80112009-12-09 20:20:26 -08001555 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001556 if (mHeap->getHeapID() < 0) {
1557 return NO_INIT;
1558 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001559
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001560 mSampleRate = sampleRate;
1561 mChannelCount = (uint16_t)channelCount;
1562 mFormat = (uint16_t)format;
1563 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001564
1565 if (cb != NULL) {
1566 mCallbackThread = new CallbackThread(this, cb, cookie);
1567 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001568 return NO_ERROR;
1569}
1570
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001571void MediaPlayerService::AudioCache::start() {
1572 if (mCallbackThread != NULL) {
1573 mCallbackThread->run("AudioCache callback");
1574 }
1575}
1576
1577void MediaPlayerService::AudioCache::stop() {
1578 if (mCallbackThread != NULL) {
1579 mCallbackThread->requestExitAndWait();
1580 }
1581}
1582
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1584{
1585 LOGV("write(%p, %u)", buffer, size);
1586 if ((buffer == 0) || (size == 0)) return size;
1587
1588 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1589 if (p == NULL) return NO_INIT;
1590 p += mSize;
1591 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1592 if (mSize + size > mHeap->getSize()) {
1593 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1594 size = mHeap->getSize() - mSize;
1595 }
1596 memcpy(p, buffer, size);
1597 mSize += size;
1598 return size;
1599}
1600
1601// call with lock held
1602status_t MediaPlayerService::AudioCache::wait()
1603{
1604 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001605 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606 mSignal.wait(mLock);
1607 }
1608 mCommandComplete = false;
1609
1610 if (mError == NO_ERROR) {
1611 LOGV("wait - success");
1612 } else {
1613 LOGV("wait - error");
1614 }
1615 return mError;
1616}
1617
1618void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1619{
1620 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1621 AudioCache* p = static_cast<AudioCache*>(cookie);
1622
1623 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001624 switch (msg)
1625 {
1626 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627 LOGE("Error %d, %d occurred", ext1, ext2);
1628 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001629 break;
1630 case MEDIA_PREPARED:
1631 LOGV("prepared");
1632 break;
1633 case MEDIA_PLAYBACK_COMPLETE:
1634 LOGV("playback complete");
1635 break;
1636 default:
1637 LOGV("ignored");
1638 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639 }
1640
1641 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001642 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001643 p->mCommandComplete = true;
1644 p->mSignal.signal();
1645}
1646
Eric Laurent8c563ed2010-10-07 18:23:03 -07001647int MediaPlayerService::AudioCache::getSessionId()
1648{
1649 return 0;
1650}
1651
Gloria Wang7cf180c2011-02-19 18:37:57 -08001652void MediaPlayerService::addBatteryData(uint32_t params)
1653{
1654 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001655
1656 int32_t time = systemTime() / 1000000L;
1657
1658 // change audio output devices. This notification comes from AudioFlinger
1659 if ((params & kBatteryDataSpeakerOn)
1660 || (params & kBatteryDataOtherAudioDeviceOn)) {
1661
1662 int deviceOn[NUM_AUDIO_DEVICES];
1663 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1664 deviceOn[i] = 0;
1665 }
1666
1667 if ((params & kBatteryDataSpeakerOn)
1668 && (params & kBatteryDataOtherAudioDeviceOn)) {
1669 deviceOn[SPEAKER_AND_OTHER] = 1;
1670 } else if (params & kBatteryDataSpeakerOn) {
1671 deviceOn[SPEAKER] = 1;
1672 } else {
1673 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1674 }
1675
1676 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1677 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1678
1679 if (mBatteryAudio.refCount > 0) { // if playing audio
1680 if (!deviceOn[i]) {
1681 mBatteryAudio.lastTime[i] += time;
1682 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1683 mBatteryAudio.lastTime[i] = 0;
1684 } else {
1685 mBatteryAudio.lastTime[i] = 0 - time;
1686 }
1687 }
1688
1689 mBatteryAudio.deviceOn[i] = deviceOn[i];
1690 }
1691 }
1692 return;
1693 }
1694
1695 // an sudio stream is started
1696 if (params & kBatteryDataAudioFlingerStart) {
1697 // record the start time only if currently no other audio
1698 // is being played
1699 if (mBatteryAudio.refCount == 0) {
1700 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1701 if (mBatteryAudio.deviceOn[i]) {
1702 mBatteryAudio.lastTime[i] -= time;
1703 }
1704 }
1705 }
1706
1707 mBatteryAudio.refCount ++;
1708 return;
1709
1710 } else if (params & kBatteryDataAudioFlingerStop) {
1711 if (mBatteryAudio.refCount <= 0) {
1712 LOGW("Battery track warning: refCount is <= 0");
1713 return;
1714 }
1715
1716 // record the stop time only if currently this is the only
1717 // audio being played
1718 if (mBatteryAudio.refCount == 1) {
1719 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1720 if (mBatteryAudio.deviceOn[i]) {
1721 mBatteryAudio.lastTime[i] += time;
1722 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1723 mBatteryAudio.lastTime[i] = 0;
1724 }
1725 }
1726 }
1727
1728 mBatteryAudio.refCount --;
1729 return;
1730 }
1731
Gloria Wang7cf180c2011-02-19 18:37:57 -08001732 int uid = IPCThreadState::self()->getCallingUid();
1733 if (uid == AID_MEDIA) {
1734 return;
1735 }
1736 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001737
1738 if (index < 0) { // create a new entry for this UID
1739 BatteryUsageInfo info;
1740 info.audioTotalTime = 0;
1741 info.videoTotalTime = 0;
1742 info.audioLastTime = 0;
1743 info.videoLastTime = 0;
1744 info.refCount = 0;
1745
Gloria Wang9ee159b2011-02-24 14:51:45 -08001746 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1747 LOGE("Battery track error: no memory for new app");
1748 return;
1749 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001750 }
1751
1752 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1753
1754 if (params & kBatteryDataCodecStarted) {
1755 if (params & kBatteryDataTrackAudio) {
1756 info.audioLastTime -= time;
1757 info.refCount ++;
1758 }
1759 if (params & kBatteryDataTrackVideo) {
1760 info.videoLastTime -= time;
1761 info.refCount ++;
1762 }
1763 } else {
1764 if (info.refCount == 0) {
1765 LOGW("Battery track warning: refCount is already 0");
1766 return;
1767 } else if (info.refCount < 0) {
1768 LOGE("Battery track error: refCount < 0");
1769 mBatteryData.removeItem(uid);
1770 return;
1771 }
1772
1773 if (params & kBatteryDataTrackAudio) {
1774 info.audioLastTime += time;
1775 info.refCount --;
1776 }
1777 if (params & kBatteryDataTrackVideo) {
1778 info.videoLastTime += time;
1779 info.refCount --;
1780 }
1781
1782 // no stream is being played by this UID
1783 if (info.refCount == 0) {
1784 info.audioTotalTime += info.audioLastTime;
1785 info.audioLastTime = 0;
1786 info.videoTotalTime += info.videoLastTime;
1787 info.videoLastTime = 0;
1788 }
1789 }
1790}
1791
1792status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1793 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001794
1795 // audio output devices usage
1796 int32_t time = systemTime() / 1000000L; //in ms
1797 int32_t totalTime;
1798
1799 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1800 totalTime = mBatteryAudio.totalTime[i];
1801
1802 if (mBatteryAudio.deviceOn[i]
1803 && (mBatteryAudio.lastTime[i] != 0)) {
1804 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1805 totalTime += tmpTime;
1806 }
1807
1808 reply->writeInt32(totalTime);
1809 // reset the total time
1810 mBatteryAudio.totalTime[i] = 0;
1811 }
1812
1813 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001814 BatteryUsageInfo info;
1815 int size = mBatteryData.size();
1816
1817 reply->writeInt32(size);
1818 int i = 0;
1819
1820 while (i < size) {
1821 info = mBatteryData.valueAt(i);
1822
1823 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1824 reply->writeInt32(info.audioTotalTime);
1825 reply->writeInt32(info.videoTotalTime);
1826
1827 info.audioTotalTime = 0;
1828 info.videoTotalTime = 0;
1829
1830 // remove the UID entry where no stream is being played
1831 if (info.refCount <= 0) {
1832 mBatteryData.removeItemsAt(i);
1833 size --;
1834 i --;
1835 }
1836 i++;
1837 }
1838 return NO_ERROR;
1839}
nikoa64c8c72009-07-20 15:07:26 -07001840} // namespace android