blob: 9dd353beb0fae66e590347f3b98e7e8d50e76ab3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Wangd211f412011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopiana650aaa2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036
37#include <android_runtime/ActivityManager.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070038
Mathias Agopian07952722009-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 Catania20cb94e2009-05-12 23:25:55 -070043#include <utils/Errors.h> // for status_t
44#include <utils/String8.h>
Marco Nelissenc39d2e32009-09-20 10:42:13 -070045#include <utils/SystemClock.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project9066cfe2009-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>
nikobc726922009-07-20 15:07:26 -070052#include <media/Metadata.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053#include <media/AudioTrack.h>
James Donged732462011-03-14 17:01:38 -070054#include <media/MemoryLeakTrackUtil.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Dima Zavin24fc2fb2011-04-19 22:30:36 -070056#include <hardware/audio.h>
57
Gloria Wangd211f412011-02-19 18:37:57 -080058#include <private/android_filesystem_config.h>
59
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060#include "MediaRecorderClient.h"
61#include "MediaPlayerService.h"
62#include "MetadataRetrieverClient.h"
63
64#include "MidiFile.h"
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070065#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070066#include "StagefrightPlayer.h"
Andreas Hubera1587462010-12-15 15:17:42 -080067#include "nuplayer/NuPlayerDriver.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070068
Andreas Hubere46b7be2009-07-14 16:56:47 -070069#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071/* desktop Linux needs a little help with gettid() */
72#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
73#define __KERNEL__
74# include <linux/unistd.h>
75#ifdef _syscall0
76_syscall0(pid_t,gettid)
77#else
78pid_t gettid() { return syscall(__NR_gettid);}
79#endif
80#undef __KERNEL__
81#endif
82
Nicolas Cataniab2c69392009-07-08 08:57:42 -070083namespace {
nikobc726922009-07-20 15:07:26 -070084using android::media::Metadata;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070085using android::status_t;
86using android::OK;
87using android::BAD_VALUE;
88using android::NOT_ENOUGH_DATA;
89using android::Parcel;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070090
91// Max number of entries in the filter.
92const int kMaxFilterSize = 64; // I pulled that out of thin air.
93
nikobc726922009-07-20 15:07:26 -070094// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070095
Nicolas Cataniab2c69392009-07-08 08:57:42 -070096
97// Unmarshall a filter from a Parcel.
98// Filter format in a parcel:
99//
100// 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
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// | number of entries (n) |
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | metadata type 1 |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | metadata type 2 |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// ....
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type n |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112//
113// @param p Parcel that should start with a filter.
114// @param[out] filter On exit contains the list of metadata type to be
115// filtered.
116// @param[out] status On exit contains the status code to be returned.
117// @return true if the parcel starts with a valid filter.
118bool unmarshallFilter(const Parcel& p,
nikobc726922009-07-20 15:07:26 -0700119 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700120 status_t *status)
121{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700122 int32_t val;
123 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700124 {
125 LOGE("Failed to read filter's length");
126 *status = NOT_ENOUGH_DATA;
127 return false;
128 }
129
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700130 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700131 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700132 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700133 *status = BAD_VALUE;
134 return false;
135 }
136
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700137 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700138
139 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700140 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700141
nikobc726922009-07-20 15:07:26 -0700142 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700143
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700144
145 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700146 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700147 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700148 *status = NOT_ENOUGH_DATA;
149 return false;
150 }
151
nikobc726922009-07-20 15:07:26 -0700152 const Metadata::Type *data =
153 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700154
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700155 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700156 {
157 LOGE("Filter had no data");
158 *status = BAD_VALUE;
159 return false;
160 }
161
162 // TODO: The stl impl of vector would be more efficient here
163 // because it degenerates into a memcpy on pod types. Try to
164 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700165 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700166 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700167 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700168 ++data;
169 }
170 *status = OK;
171 return true;
172}
173
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700174// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700175// @param val To be searched.
176// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700177bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700178{
179 // Deal with empty and ANY right away
180 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700181 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700182
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700183 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700184}
185
186} // anonymous namespace
187
188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189namespace android {
190
191// TODO: Temp hack until we can register players
192typedef struct {
193 const char *extension;
194 const player_type playertype;
195} extmap;
196extmap FILE_EXTS [] = {
197 {".mid", SONIVOX_PLAYER},
198 {".midi", SONIVOX_PLAYER},
199 {".smf", SONIVOX_PLAYER},
200 {".xmf", SONIVOX_PLAYER},
201 {".imy", SONIVOX_PLAYER},
202 {".rtttl", SONIVOX_PLAYER},
203 {".rtx", SONIVOX_PLAYER},
204 {".ota", SONIVOX_PLAYER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205};
206
207// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
209/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
210
211void MediaPlayerService::instantiate() {
212 defaultServiceManager()->addService(
213 String16("media.player"), new MediaPlayerService());
214}
215
216MediaPlayerService::MediaPlayerService()
217{
218 LOGV("MediaPlayerService created");
219 mNextConnId = 1;
Gloria Wang9b3f1522011-02-24 14:51:45 -0800220
221 mBatteryAudio.refCount = 0;
222 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
223 mBatteryAudio.deviceOn[i] = 0;
224 mBatteryAudio.lastTime[i] = 0;
225 mBatteryAudio.totalTime[i] = 0;
226 }
227 // speaker is on by default
228 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229}
230
231MediaPlayerService::~MediaPlayerService()
232{
233 LOGV("MediaPlayerService destroyed");
234}
235
236sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
237{
Gloria Wang608a2632009-10-29 15:46:37 -0700238 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
239 wp<MediaRecorderClient> w = recorder;
240 Mutex::Autolock lock(mLock);
241 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 LOGV("Create new media recorder client from pid %d", pid);
243 return recorder;
244}
245
Gloria Wang608a2632009-10-29 15:46:37 -0700246void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
247{
248 Mutex::Autolock lock(mLock);
249 mMediaRecorderClients.remove(client);
250 LOGV("Delete media recorder client");
251}
252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
254{
255 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
256 LOGV("Create new media retriever from pid %d", pid);
257 return retriever;
258}
259
Andreas Huber25643002010-01-28 11:19:57 -0800260sp<IMediaPlayer> MediaPlayerService::create(
261 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
Eric Laurent619346f2010-06-21 09:27:30 -0700262 const KeyedVector<String8, String8> *headers, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263{
264 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurent619346f2010-06-21 09:27:30 -0700265 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
266 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
267 connId, pid, url, connId, audioSessionId);
Andreas Huber25643002010-01-28 11:19:57 -0800268 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 {
270 c.clear();
271 return c;
272 }
273 wp<Client> w = c;
274 Mutex::Autolock lock(mLock);
275 mClients.add(w);
276 return c;
277}
278
279sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Eric Laurent619346f2010-06-21 09:27:30 -0700280 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281{
282 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurent619346f2010-06-21 09:27:30 -0700283 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
284 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
285 connId, pid, fd, offset, length, audioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
287 c.clear();
288 } else {
289 wp<Client> w = c;
290 Mutex::Autolock lock(mLock);
291 mClients.add(w);
292 }
293 ::close(fd);
294 return c;
295}
296
Andreas Huber52b52cd2010-11-23 11:41:34 -0800297sp<IMediaPlayer> MediaPlayerService::create(
298 pid_t pid, const sp<IMediaPlayerClient> &client,
299 const sp<IStreamSource> &source, int audioSessionId) {
300 int32_t connId = android_atomic_inc(&mNextConnId);
301 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
302
303 LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
304 connId, pid, audioSessionId);
305
306 if (OK != c->setDataSource(source)) {
307 c.clear();
308 } else {
309 wp<Client> w = c;
310 Mutex::Autolock lock(mLock);
311 mClients.add(w);
312 }
313
314 return c;
315}
316
Andreas Huber784202e2009-10-15 13:46:54 -0700317sp<IOMX> MediaPlayerService::getOMX() {
318 Mutex::Autolock autoLock(mLock);
319
320 if (mOMX.get() == NULL) {
321 mOMX = new OMX;
322 }
323
324 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700325}
326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
328{
329 const size_t SIZE = 256;
330 char buffer[SIZE];
331 String8 result;
332
333 result.append(" AudioCache\n");
334 if (mHeap != 0) {
335 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
336 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
337 result.append(buffer);
338 }
339 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
340 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
341 result.append(buffer);
342 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
343 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
344 result.append(buffer);
345 ::write(fd, result.string(), result.size());
346 return NO_ERROR;
347}
348
349status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
350{
351 const size_t SIZE = 256;
352 char buffer[SIZE];
353 String8 result;
354
355 result.append(" AudioOutput\n");
356 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
357 mStreamType, mLeftVolume, mRightVolume);
358 result.append(buffer);
359 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
360 mMsecsPerFrame, mLatency);
361 result.append(buffer);
Eric Laurent7070b362010-07-16 07:43:46 -0700362 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
363 mAuxEffectId, mSendLevel);
364 result.append(buffer);
365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 ::write(fd, result.string(), result.size());
367 if (mTrack != 0) {
368 mTrack->dump(fd, args);
369 }
370 return NO_ERROR;
371}
372
373status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
374{
375 const size_t SIZE = 256;
376 char buffer[SIZE];
377 String8 result;
378 result.append(" Client\n");
379 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
380 mPid, mConnId, mStatus, mLoop?"true": "false");
381 result.append(buffer);
382 write(fd, result.string(), result.size());
383 if (mAudioOutput != 0) {
384 mAudioOutput->dump(fd, args);
385 }
386 write(fd, "\n", 1);
387 return NO_ERROR;
388}
389
390static int myTid() {
391#ifdef HAVE_GETTID
392 return gettid();
393#else
394 return getpid();
395#endif
396}
397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
399{
400 const size_t SIZE = 256;
401 char buffer[SIZE];
402 String8 result;
403 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
404 snprintf(buffer, SIZE, "Permission Denial: "
405 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
406 IPCThreadState::self()->getCallingPid(),
407 IPCThreadState::self()->getCallingUid());
408 result.append(buffer);
409 } else {
410 Mutex::Autolock lock(mLock);
411 for (int i = 0, n = mClients.size(); i < n; ++i) {
412 sp<Client> c = mClients[i].promote();
413 if (c != 0) c->dump(fd, args);
414 }
James Dong929642e2010-07-08 11:16:11 -0700415 if (mMediaRecorderClients.size() == 0) {
416 result.append(" No media recorder client\n\n");
417 } else {
418 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
419 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
420 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
421 result.append(buffer);
422 write(fd, result.string(), result.size());
423 result = "\n";
424 c->dump(fd, args);
425 }
Gloria Wang608a2632009-10-29 15:46:37 -0700426 }
427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 result.append(" Files opened and/or mapped:\n");
429 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
430 FILE *f = fopen(buffer, "r");
431 if (f) {
432 while (!feof(f)) {
433 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700434 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700436 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 strstr(buffer, " /system/media/")) {
438 result.append(" ");
439 result.append(buffer);
440 }
441 }
442 fclose(f);
443 } else {
444 result.append("couldn't open ");
445 result.append(buffer);
446 result.append("\n");
447 }
448
449 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
450 DIR *d = opendir(buffer);
451 if (d) {
452 struct dirent *ent;
453 while((ent = readdir(d)) != NULL) {
454 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
455 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
456 struct stat s;
457 if (lstat(buffer, &s) == 0) {
458 if ((s.st_mode & S_IFMT) == S_IFLNK) {
459 char linkto[256];
460 int len = readlink(buffer, linkto, sizeof(linkto));
461 if(len > 0) {
462 if(len > 255) {
463 linkto[252] = '.';
464 linkto[253] = '.';
465 linkto[254] = '.';
466 linkto[255] = 0;
467 } else {
468 linkto[len] = 0;
469 }
Dave Sparks124a3462010-09-27 16:55:18 -0700470 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700472 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 strstr(linkto, "/system/media/") == linkto) {
474 result.append(" ");
475 result.append(buffer);
476 result.append(" -> ");
477 result.append(linkto);
478 result.append("\n");
479 }
480 }
481 } else {
482 result.append(" unexpected type for ");
483 result.append(buffer);
484 result.append("\n");
485 }
486 }
487 }
488 }
489 closedir(d);
490 } else {
491 result.append("couldn't open ");
492 result.append(buffer);
493 result.append("\n");
494 }
495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 bool dumpMem = false;
497 for (size_t i = 0; i < args.size(); i++) {
498 if (args[i] == String16("-m")) {
499 dumpMem = true;
500 }
501 }
502 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700503 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 }
506 write(fd, result.string(), result.size());
507 return NO_ERROR;
508}
509
510void MediaPlayerService::removeClient(wp<Client> client)
511{
512 Mutex::Autolock lock(mLock);
513 mClients.remove(client);
514}
515
516MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
Eric Laurent619346f2010-06-21 09:27:30 -0700517 int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518{
519 LOGV("Client(%d) constructor", connId);
520 mPid = pid;
521 mConnId = connId;
522 mService = service;
523 mClient = client;
524 mLoop = false;
525 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700526 mAudioSessionId = audioSessionId;
527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528#if CALLBACK_ANTAGONIZER
529 LOGD("create Antagonizer");
530 mAntagonizer = new Antagonizer(notify, this);
531#endif
532}
533
534MediaPlayerService::Client::~Client()
535{
536 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
537 mAudioOutput.clear();
538 wp<Client> client(this);
539 disconnect();
540 mService->removeClient(client);
541}
542
543void MediaPlayerService::Client::disconnect()
544{
545 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
546 // grab local reference and clear main reference to prevent future
547 // access to object
548 sp<MediaPlayerBase> p;
549 {
550 Mutex::Autolock l(mLock);
551 p = mPlayer;
552 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700553 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 mPlayer.clear();
556
557 // clear the notification to prevent callbacks to dead client
558 // and reset the player. We assume the player will serialize
559 // access to itself if necessary.
560 if (p != 0) {
561 p->setNotifyCallback(0, 0);
562#if CALLBACK_ANTAGONIZER
563 LOGD("kill Antagonizer");
564 mAntagonizer->kill();
565#endif
566 p->reset();
567 }
568
569 IPCThreadState::self()->flushCommands();
570}
571
Andreas Huber0d596d42009-08-07 09:30:32 -0700572static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700573 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700574}
575
James Dong392ff3b2009-09-06 14:29:45 -0700576player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577{
578 char buf[20];
579 lseek(fd, offset, SEEK_SET);
580 read(fd, buf, sizeof(buf));
581 lseek(fd, offset, SEEK_SET);
582
583 long ident = *((long*)buf);
584
585 // Ogg vorbis?
586 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700587 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588
589 // Some kind of MIDI?
590 EAS_DATA_HANDLE easdata;
591 if (EAS_Init(&easdata) == EAS_SUCCESS) {
592 EAS_FILE locator;
593 locator.path = NULL;
594 locator.fd = fd;
595 locator.offset = offset;
596 locator.length = length;
597 EAS_HANDLE eashandle;
598 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
599 EAS_CloseFile(easdata, eashandle);
600 EAS_Shutdown(easdata);
601 return SONIVOX_PLAYER;
602 }
603 EAS_Shutdown(easdata);
604 }
605
Andreas Huber0d596d42009-08-07 09:30:32 -0700606 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607}
608
James Dong392ff3b2009-09-06 14:29:45 -0700609player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700611 if (TestPlayerStub::canBeUsed(url)) {
612 return TEST_PLAYER;
613 }
614
Andreas Huber554d0ea2011-03-21 16:28:04 -0700615 if (!strncasecmp("http://", url, 7)
616 || !strncasecmp("https://", url, 8)) {
Andreas Huberd6c421f2011-02-16 09:05:38 -0800617 size_t len = strlen(url);
618 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
619 return NU_PLAYER;
620 }
Andreas Huber54e66492010-12-23 10:27:40 -0800621
Andreas Huberd6c421f2011-02-16 09:05:38 -0800622 if (strstr(url,"m3u8")) {
623 return NU_PLAYER;
Andreas Huber54e66492010-12-23 10:27:40 -0800624 }
625 }
626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 // use MidiFile for MIDI extensions
628 int lenURL = strlen(url);
629 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
630 int len = strlen(FILE_EXTS[i].extension);
631 int start = lenURL - len;
632 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900633 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700634 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636 }
637 }
638
Andreas Huber0d596d42009-08-07 09:30:32 -0700639 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640}
641
642static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
643 notify_callback_f notifyFunc)
644{
645 sp<MediaPlayerBase> p;
646 switch (playerType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 case SONIVOX_PLAYER:
648 LOGV(" create MidiFile");
649 p = new MidiFile();
650 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700651 case STAGEFRIGHT_PLAYER:
652 LOGV(" create StagefrightPlayer");
653 p = new StagefrightPlayer;
654 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800655 case NU_PLAYER:
656 LOGV(" create NuPlayer");
657 p = new NuPlayerDriver;
658 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700659 case TEST_PLAYER:
660 LOGV("Create Test Player stub");
661 p = new TestPlayerStub();
662 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800663 default:
664 LOGE("Unknown player type: %d", playerType);
665 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667 if (p != NULL) {
668 if (p->initCheck() == NO_ERROR) {
669 p->setNotifyCallback(cookie, notifyFunc);
670 } else {
671 p.clear();
672 }
673 }
674 if (p == NULL) {
675 LOGE("Failed to create player object");
676 }
677 return p;
678}
679
680sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
681{
682 // determine if we have the right player type
683 sp<MediaPlayerBase> p = mPlayer;
684 if ((p != NULL) && (p->playerType() != playerType)) {
685 LOGV("delete player");
686 p.clear();
687 }
688 if (p == NULL) {
689 p = android::createPlayer(playerType, this, notify);
690 }
691 return p;
692}
693
Andreas Huber25643002010-01-28 11:19:57 -0800694status_t MediaPlayerService::Client::setDataSource(
695 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696{
697 LOGV("setDataSource(%s)", url);
698 if (url == NULL)
699 return UNKNOWN_ERROR;
700
701 if (strncmp(url, "content://", 10) == 0) {
702 // get a filedescriptor for the content Uri and
703 // pass it to the setDataSource(fd) method
704
705 String16 url16(url);
706 int fd = android::openContentProviderFile(url16);
707 if (fd < 0)
708 {
709 LOGE("Couldn't open fd for %s", url);
710 return UNKNOWN_ERROR;
711 }
712 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
713 close(fd);
714 return mStatus;
715 } else {
716 player_type playerType = getPlayerType(url);
717 LOGV("player type = %d", playerType);
718
719 // create the right type of player
720 sp<MediaPlayerBase> p = createPlayer(playerType);
721 if (p == NULL) return NO_INIT;
722
723 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700724 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
726 }
727
728 // now set data source
729 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800730 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700731 if (mStatus == NO_ERROR) {
732 mPlayer = p;
733 } else {
734 LOGE(" error: %d", mStatus);
735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 return mStatus;
737 }
738}
739
740status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
741{
742 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
743 struct stat sb;
744 int ret = fstat(fd, &sb);
745 if (ret != 0) {
746 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
747 return UNKNOWN_ERROR;
748 }
749
750 LOGV("st_dev = %llu", sb.st_dev);
751 LOGV("st_mode = %u", sb.st_mode);
752 LOGV("st_uid = %lu", sb.st_uid);
753 LOGV("st_gid = %lu", sb.st_gid);
754 LOGV("st_size = %llu", sb.st_size);
755
756 if (offset >= sb.st_size) {
757 LOGE("offset error");
758 ::close(fd);
759 return UNKNOWN_ERROR;
760 }
761 if (offset + length > sb.st_size) {
762 length = sb.st_size - offset;
763 LOGV("calculated length = %lld", length);
764 }
765
766 player_type playerType = getPlayerType(fd, offset, length);
767 LOGV("player type = %d", playerType);
768
769 // create the right type of player
770 sp<MediaPlayerBase> p = createPlayer(playerType);
771 if (p == NULL) return NO_INIT;
772
773 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700774 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
776 }
777
778 // now set data source
779 mStatus = p->setDataSource(fd, offset, length);
780 if (mStatus == NO_ERROR) mPlayer = p;
781 return mStatus;
782}
783
Andreas Huber52b52cd2010-11-23 11:41:34 -0800784status_t MediaPlayerService::Client::setDataSource(
785 const sp<IStreamSource> &source) {
786 // create the right type of player
Andreas Hubera1587462010-12-15 15:17:42 -0800787 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Huber52b52cd2010-11-23 11:41:34 -0800788
789 if (p == NULL) {
790 return NO_INIT;
791 }
792
793 if (!p->hardwareOutput()) {
794 mAudioOutput = new AudioOutput(mAudioSessionId);
795 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
796 }
797
798 // now set data source
799 mStatus = p->setDataSource(source);
800
801 if (mStatus == OK) {
802 mPlayer = p;
803 }
804
805 return mStatus;
806}
807
Andreas Hubere3c01832010-08-16 08:49:37 -0700808status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809{
810 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
811 sp<MediaPlayerBase> p = getPlayer();
812 if (p == 0) return UNKNOWN_ERROR;
813 return p->setVideoSurface(surface);
814}
815
Glenn Kastencc562a32011-02-08 17:26:17 -0800816status_t MediaPlayerService::Client::setVideoSurfaceTexture(
817 const sp<ISurfaceTexture>& surfaceTexture)
818{
819 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
820 sp<MediaPlayerBase> p = getPlayer();
821 if (p == 0) return UNKNOWN_ERROR;
822 return p->setVideoSurfaceTexture(surfaceTexture);
823}
824
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700825status_t MediaPlayerService::Client::invoke(const Parcel& request,
826 Parcel *reply)
827{
828 sp<MediaPlayerBase> p = getPlayer();
829 if (p == NULL) return UNKNOWN_ERROR;
830 return p->invoke(request, reply);
831}
832
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700833// This call doesn't need to access the native player.
834status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
835{
836 status_t status;
nikobc726922009-07-20 15:07:26 -0700837 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700838
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700839 if (unmarshallFilter(filter, &allow, &status) &&
840 unmarshallFilter(filter, &drop, &status)) {
841 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700842
843 mMetadataAllow = allow;
844 mMetadataDrop = drop;
845 }
846 return status;
847}
848
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700849status_t MediaPlayerService::Client::getMetadata(
850 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700851{
nikobc726922009-07-20 15:07:26 -0700852 sp<MediaPlayerBase> player = getPlayer();
853 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700854
niko89948372009-07-16 16:39:53 -0700855 status_t status;
856 // Placeholder for the return code, updated by the caller.
857 reply->writeInt32(-1);
858
nikobc726922009-07-20 15:07:26 -0700859 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700860
861 // We don't block notifications while we fetch the data. We clear
862 // mMetadataUpdated first so we don't lose notifications happening
863 // during the rest of this call.
864 {
865 Mutex::Autolock lock(mLock);
866 if (update_only) {
niko89948372009-07-16 16:39:53 -0700867 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700868 }
869 mMetadataUpdated.clear();
870 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700871
nikobc726922009-07-20 15:07:26 -0700872 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700873
nikobc726922009-07-20 15:07:26 -0700874 metadata.appendHeader();
875 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700876
877 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700878 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700879 LOGE("getMetadata failed %d", status);
880 return status;
881 }
882
883 // FIXME: Implement filtering on the result. Not critical since
884 // filtering takes place on the update notifications already. This
885 // would be when all the metadata are fetch and a filter is set.
886
niko89948372009-07-16 16:39:53 -0700887 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700888 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700889 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700890}
891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892status_t MediaPlayerService::Client::prepareAsync()
893{
894 LOGV("[%d] prepareAsync", mConnId);
895 sp<MediaPlayerBase> p = getPlayer();
896 if (p == 0) return UNKNOWN_ERROR;
897 status_t ret = p->prepareAsync();
898#if CALLBACK_ANTAGONIZER
899 LOGD("start Antagonizer");
900 if (ret == NO_ERROR) mAntagonizer->start();
901#endif
902 return ret;
903}
904
905status_t MediaPlayerService::Client::start()
906{
907 LOGV("[%d] start", mConnId);
908 sp<MediaPlayerBase> p = getPlayer();
909 if (p == 0) return UNKNOWN_ERROR;
910 p->setLooping(mLoop);
911 return p->start();
912}
913
914status_t MediaPlayerService::Client::stop()
915{
916 LOGV("[%d] stop", mConnId);
917 sp<MediaPlayerBase> p = getPlayer();
918 if (p == 0) return UNKNOWN_ERROR;
919 return p->stop();
920}
921
922status_t MediaPlayerService::Client::pause()
923{
924 LOGV("[%d] pause", mConnId);
925 sp<MediaPlayerBase> p = getPlayer();
926 if (p == 0) return UNKNOWN_ERROR;
927 return p->pause();
928}
929
930status_t MediaPlayerService::Client::isPlaying(bool* state)
931{
932 *state = false;
933 sp<MediaPlayerBase> p = getPlayer();
934 if (p == 0) return UNKNOWN_ERROR;
935 *state = p->isPlaying();
936 LOGV("[%d] isPlaying: %d", mConnId, *state);
937 return NO_ERROR;
938}
939
940status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
941{
942 LOGV("getCurrentPosition");
943 sp<MediaPlayerBase> p = getPlayer();
944 if (p == 0) return UNKNOWN_ERROR;
945 status_t ret = p->getCurrentPosition(msec);
946 if (ret == NO_ERROR) {
947 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
948 } else {
949 LOGE("getCurrentPosition returned %d", ret);
950 }
951 return ret;
952}
953
954status_t MediaPlayerService::Client::getDuration(int *msec)
955{
956 LOGV("getDuration");
957 sp<MediaPlayerBase> p = getPlayer();
958 if (p == 0) return UNKNOWN_ERROR;
959 status_t ret = p->getDuration(msec);
960 if (ret == NO_ERROR) {
961 LOGV("[%d] getDuration = %d", mConnId, *msec);
962 } else {
963 LOGE("getDuration returned %d", ret);
964 }
965 return ret;
966}
967
968status_t MediaPlayerService::Client::seekTo(int msec)
969{
970 LOGV("[%d] seekTo(%d)", mConnId, msec);
971 sp<MediaPlayerBase> p = getPlayer();
972 if (p == 0) return UNKNOWN_ERROR;
973 return p->seekTo(msec);
974}
975
976status_t MediaPlayerService::Client::reset()
977{
978 LOGV("[%d] reset", mConnId);
979 sp<MediaPlayerBase> p = getPlayer();
980 if (p == 0) return UNKNOWN_ERROR;
981 return p->reset();
982}
983
984status_t MediaPlayerService::Client::setAudioStreamType(int type)
985{
986 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
987 // TODO: for hardware output, call player instead
988 Mutex::Autolock l(mLock);
989 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
990 return NO_ERROR;
991}
992
993status_t MediaPlayerService::Client::setLooping(int loop)
994{
995 LOGV("[%d] setLooping(%d)", mConnId, loop);
996 mLoop = loop;
997 sp<MediaPlayerBase> p = getPlayer();
998 if (p != 0) return p->setLooping(loop);
999 return NO_ERROR;
1000}
1001
1002status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1003{
1004 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1005 // TODO: for hardware output, call player instead
1006 Mutex::Autolock l(mLock);
1007 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1008 return NO_ERROR;
1009}
1010
Eric Laurent7070b362010-07-16 07:43:46 -07001011status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1012{
1013 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1014 Mutex::Autolock l(mLock);
1015 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1016 return NO_ERROR;
1017}
1018
1019status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1020{
1021 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1022 Mutex::Autolock l(mLock);
1023 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1024 return NO_ERROR;
1025}
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001026
Gloria Wang162ee492011-04-11 17:23:27 -07001027void MediaPlayerService::Client::notify(
1028 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029{
1030 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001031
1032 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001033 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001034 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001035
1036 if(client->shouldDropMetadata(metadata_type)) {
1037 return;
1038 }
1039
1040 // Update the list of metadata that have changed. getMetadata
1041 // also access mMetadataUpdated and clears it.
1042 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001045 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046}
1047
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001048
nikobc726922009-07-20 15:07:26 -07001049bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001050{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001051 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001052
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001053 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001054 return true;
1055 }
1056
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001057 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001058 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001059 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001060 return true;
1061 }
1062}
1063
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001064
nikobc726922009-07-20 15:07:26 -07001065void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001066 Mutex::Autolock lock(mLock);
1067 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1068 mMetadataUpdated.add(metadata_type);
1069 }
1070}
1071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072#if CALLBACK_ANTAGONIZER
1073const int Antagonizer::interval = 10000; // 10 msecs
1074
1075Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1076 mExit(false), mActive(false), mClient(client), mCb(cb)
1077{
1078 createThread(callbackThread, this);
1079}
1080
1081void Antagonizer::kill()
1082{
1083 Mutex::Autolock _l(mLock);
1084 mActive = false;
1085 mExit = true;
1086 mCondition.wait(mLock);
1087}
1088
1089int Antagonizer::callbackThread(void* user)
1090{
1091 LOGD("Antagonizer started");
1092 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1093 while (!p->mExit) {
1094 if (p->mActive) {
1095 LOGV("send event");
1096 p->mCb(p->mClient, 0, 0, 0);
1097 }
1098 usleep(interval);
1099 }
1100 Mutex::Autolock _l(p->mLock);
1101 p->mCondition.signal();
1102 LOGD("Antagonizer stopped");
1103 return 0;
1104}
1105#endif
1106
1107static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1108
1109sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1110{
1111 LOGV("decode(%s)", url);
1112 sp<MemoryBase> mem;
1113 sp<MediaPlayerBase> player;
1114
1115 // Protect our precious, precious DRMd ringtones by only allowing
1116 // decoding of http, but not filesystem paths or content Uris.
1117 // If the application wants to decode those, it should open a
1118 // filedescriptor for them and use that.
1119 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1120 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1121 return mem;
1122 }
1123
1124 player_type playerType = getPlayerType(url);
1125 LOGV("player type = %d", playerType);
1126
1127 // create the right type of player
1128 sp<AudioCache> cache = new AudioCache(url);
1129 player = android::createPlayer(playerType, cache.get(), cache->notify);
1130 if (player == NULL) goto Exit;
1131 if (player->hardwareOutput()) goto Exit;
1132
1133 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1134
1135 // set data source
1136 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1137
1138 LOGV("prepare");
1139 player->prepareAsync();
1140
1141 LOGV("wait for prepare");
1142 if (cache->wait() != NO_ERROR) goto Exit;
1143
1144 LOGV("start");
1145 player->start();
1146
1147 LOGV("wait for playback complete");
1148 if (cache->wait() != NO_ERROR) goto Exit;
1149
1150 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1151 *pSampleRate = cache->sampleRate();
1152 *pNumChannels = cache->channelCount();
1153 *pFormat = cache->format();
1154 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1155
1156Exit:
1157 if (player != 0) player->reset();
1158 return mem;
1159}
1160
1161sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1162{
1163 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1164 sp<MemoryBase> mem;
1165 sp<MediaPlayerBase> player;
1166
1167 player_type playerType = getPlayerType(fd, offset, length);
1168 LOGV("player type = %d", playerType);
1169
1170 // create the right type of player
1171 sp<AudioCache> cache = new AudioCache("decode_fd");
1172 player = android::createPlayer(playerType, cache.get(), cache->notify);
1173 if (player == NULL) goto Exit;
1174 if (player->hardwareOutput()) goto Exit;
1175
1176 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1177
1178 // set data source
1179 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1180
1181 LOGV("prepare");
1182 player->prepareAsync();
1183
1184 LOGV("wait for prepare");
1185 if (cache->wait() != NO_ERROR) goto Exit;
1186
1187 LOGV("start");
1188 player->start();
1189
1190 LOGV("wait for playback complete");
1191 if (cache->wait() != NO_ERROR) goto Exit;
1192
1193 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1194 *pSampleRate = cache->sampleRate();
1195 *pNumChannels = cache->channelCount();
1196 *pFormat = cache->format();
1197 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1198
1199Exit:
1200 if (player != 0) player->reset();
1201 ::close(fd);
1202 return mem;
1203}
1204
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206#undef LOG_TAG
1207#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001208MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001209 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001210 mCallbackCookie(NULL),
1211 mSessionId(sessionId) {
1212 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001214 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 mLeftVolume = 1.0;
1216 mRightVolume = 1.0;
1217 mLatency = 0;
1218 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001219 mAuxEffectId = 0;
1220 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 setMinBufferCount();
1222}
1223
1224MediaPlayerService::AudioOutput::~AudioOutput()
1225{
1226 close();
1227}
1228
1229void MediaPlayerService::AudioOutput::setMinBufferCount()
1230{
1231 char value[PROPERTY_VALUE_MAX];
1232 if (property_get("ro.kernel.qemu", value, 0)) {
1233 mIsOnEmulator = true;
1234 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1235 }
1236}
1237
1238bool MediaPlayerService::AudioOutput::isOnEmulator()
1239{
1240 setMinBufferCount();
1241 return mIsOnEmulator;
1242}
1243
1244int MediaPlayerService::AudioOutput::getMinBufferCount()
1245{
1246 setMinBufferCount();
1247 return mMinBufferCount;
1248}
1249
1250ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1251{
1252 if (mTrack == 0) return NO_INIT;
1253 return mTrack->frameCount() * frameSize();
1254}
1255
1256ssize_t MediaPlayerService::AudioOutput::frameCount() const
1257{
1258 if (mTrack == 0) return NO_INIT;
1259 return mTrack->frameCount();
1260}
1261
1262ssize_t MediaPlayerService::AudioOutput::channelCount() const
1263{
1264 if (mTrack == 0) return NO_INIT;
1265 return mTrack->channelCount();
1266}
1267
1268ssize_t MediaPlayerService::AudioOutput::frameSize() const
1269{
1270 if (mTrack == 0) return NO_INIT;
1271 return mTrack->frameSize();
1272}
1273
1274uint32_t MediaPlayerService::AudioOutput::latency () const
1275{
1276 return mLatency;
1277}
1278
1279float MediaPlayerService::AudioOutput::msecsPerFrame() const
1280{
1281 return mMsecsPerFrame;
1282}
1283
Eric Laurent0986e792010-01-19 17:37:09 -08001284status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1285{
1286 if (mTrack == 0) return NO_INIT;
1287 return mTrack->getPosition(position);
1288}
1289
Andreas Hubere46b7be2009-07-14 16:56:47 -07001290status_t MediaPlayerService::AudioOutput::open(
1291 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1292 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001294 mCallback = cb;
1295 mCallbackCookie = cookie;
1296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 // Check argument "bufferCount" against the mininum buffer count
1298 if (bufferCount < mMinBufferCount) {
1299 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1300 bufferCount = mMinBufferCount;
1301
1302 }
Eric Laurent619346f2010-06-21 09:27:30 -07001303 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 if (mTrack) close();
1305 int afSampleRate;
1306 int afFrameCount;
1307 int frameCount;
1308
1309 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1310 return NO_INIT;
1311 }
1312 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1313 return NO_INIT;
1314 }
1315
1316 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001317
1318 AudioTrack *t;
1319 if (mCallback != NULL) {
1320 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001321 mStreamType,
1322 sampleRate,
1323 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001324 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001325 frameCount,
1326 0 /* flags */,
1327 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001328 this,
1329 0,
1330 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001331 } else {
1332 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001333 mStreamType,
1334 sampleRate,
1335 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001336 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001337 frameCount,
1338 0,
1339 NULL,
1340 NULL,
1341 0,
1342 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001343 }
1344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1346 LOGE("Unable to create audio track");
1347 delete t;
1348 return NO_INIT;
1349 }
1350
1351 LOGV("setVolume");
1352 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001355 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001357
1358 t->setAuxEffectSendLevel(mSendLevel);
1359 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360}
1361
1362void MediaPlayerService::AudioOutput::start()
1363{
1364 LOGV("start");
1365 if (mTrack) {
1366 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001367 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 mTrack->start();
1369 }
1370}
1371
Marco Nelissene274db12010-01-12 09:23:54 -08001372
1373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1375{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001376 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001379 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001380 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001381 return ret;
1382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 return NO_INIT;
1384}
1385
1386void MediaPlayerService::AudioOutput::stop()
1387{
1388 LOGV("stop");
1389 if (mTrack) mTrack->stop();
1390}
1391
1392void MediaPlayerService::AudioOutput::flush()
1393{
1394 LOGV("flush");
1395 if (mTrack) mTrack->flush();
1396}
1397
1398void MediaPlayerService::AudioOutput::pause()
1399{
1400 LOGV("pause");
1401 if (mTrack) mTrack->pause();
1402}
1403
1404void MediaPlayerService::AudioOutput::close()
1405{
1406 LOGV("close");
1407 delete mTrack;
1408 mTrack = 0;
1409}
1410
1411void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1412{
1413 LOGV("setVolume(%f, %f)", left, right);
1414 mLeftVolume = left;
1415 mRightVolume = right;
1416 if (mTrack) {
1417 mTrack->setVolume(left, right);
1418 }
1419}
1420
Eric Laurent7070b362010-07-16 07:43:46 -07001421status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1422{
1423 LOGV("setAuxEffectSendLevel(%f)", level);
1424 mSendLevel = level;
1425 if (mTrack) {
1426 return mTrack->setAuxEffectSendLevel(level);
1427 }
1428 return NO_ERROR;
1429}
1430
1431status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1432{
1433 LOGV("attachAuxEffect(%d)", effectId);
1434 mAuxEffectId = effectId;
1435 if (mTrack) {
1436 return mTrack->attachAuxEffect(effectId);
1437 }
1438 return NO_ERROR;
1439}
1440
Andreas Hubere46b7be2009-07-14 16:56:47 -07001441// static
1442void MediaPlayerService::AudioOutput::CallbackWrapper(
1443 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001444 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001445 if (event != AudioTrack::EVENT_MORE_DATA) {
1446 return;
1447 }
1448
1449 AudioOutput *me = (AudioOutput *)cookie;
1450 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1451
Andreas Huber6ed937e2010-02-09 16:59:18 -08001452 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001453 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001454
Andreas Huberc6e3b272011-04-04 11:43:40 -07001455 if (actualSize == 0 && buffer->size > 0) {
1456 // We've reached EOS but the audio track is not stopped yet,
1457 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001458
Andreas Huberc6e3b272011-04-04 11:43:40 -07001459 memset(buffer->raw, 0, buffer->size);
1460 actualSize = buffer->size;
1461 }
1462
1463 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001464}
1465
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001466int MediaPlayerService::AudioOutput::getSessionId()
1467{
1468 return mSessionId;
1469}
1470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471#undef LOG_TAG
1472#define LOG_TAG "AudioCache"
1473MediaPlayerService::AudioCache::AudioCache(const char* name) :
1474 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1475 mError(NO_ERROR), mCommandComplete(false)
1476{
1477 // create ashmem heap
1478 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1479}
1480
1481uint32_t MediaPlayerService::AudioCache::latency () const
1482{
1483 return 0;
1484}
1485
1486float MediaPlayerService::AudioCache::msecsPerFrame() const
1487{
1488 return mMsecsPerFrame;
1489}
1490
Eric Laurent0986e792010-01-19 17:37:09 -08001491status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1492{
1493 if (position == 0) return BAD_VALUE;
1494 *position = mSize;
1495 return NO_ERROR;
1496}
1497
Andreas Huber6ed937e2010-02-09 16:59:18 -08001498////////////////////////////////////////////////////////////////////////////////
1499
1500struct CallbackThread : public Thread {
1501 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1502 MediaPlayerBase::AudioSink::AudioCallback cb,
1503 void *cookie);
1504
1505protected:
1506 virtual ~CallbackThread();
1507
1508 virtual bool threadLoop();
1509
1510private:
1511 wp<MediaPlayerBase::AudioSink> mSink;
1512 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1513 void *mCookie;
1514 void *mBuffer;
1515 size_t mBufferSize;
1516
1517 CallbackThread(const CallbackThread &);
1518 CallbackThread &operator=(const CallbackThread &);
1519};
1520
1521CallbackThread::CallbackThread(
1522 const wp<MediaPlayerBase::AudioSink> &sink,
1523 MediaPlayerBase::AudioSink::AudioCallback cb,
1524 void *cookie)
1525 : mSink(sink),
1526 mCallback(cb),
1527 mCookie(cookie),
1528 mBuffer(NULL),
1529 mBufferSize(0) {
1530}
1531
1532CallbackThread::~CallbackThread() {
1533 if (mBuffer) {
1534 free(mBuffer);
1535 mBuffer = NULL;
1536 }
1537}
1538
1539bool CallbackThread::threadLoop() {
1540 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1541 if (sink == NULL) {
1542 return false;
1543 }
1544
1545 if (mBuffer == NULL) {
1546 mBufferSize = sink->bufferSize();
1547 mBuffer = malloc(mBufferSize);
1548 }
1549
1550 size_t actualSize =
1551 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1552
1553 if (actualSize > 0) {
1554 sink->write(mBuffer, actualSize);
1555 }
1556
1557 return true;
1558}
1559
1560////////////////////////////////////////////////////////////////////////////////
1561
Andreas Hubere46b7be2009-07-14 16:56:47 -07001562status_t MediaPlayerService::AudioCache::open(
1563 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1564 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565{
Dave Sparks14f89402009-12-09 20:20:26 -08001566 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001567 if (mHeap->getHeapID() < 0) {
1568 return NO_INIT;
1569 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 mSampleRate = sampleRate;
1572 mChannelCount = (uint16_t)channelCount;
1573 mFormat = (uint16_t)format;
1574 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001575
1576 if (cb != NULL) {
1577 mCallbackThread = new CallbackThread(this, cb, cookie);
1578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 return NO_ERROR;
1580}
1581
Andreas Huber6ed937e2010-02-09 16:59:18 -08001582void MediaPlayerService::AudioCache::start() {
1583 if (mCallbackThread != NULL) {
1584 mCallbackThread->run("AudioCache callback");
1585 }
1586}
1587
1588void MediaPlayerService::AudioCache::stop() {
1589 if (mCallbackThread != NULL) {
1590 mCallbackThread->requestExitAndWait();
1591 }
1592}
1593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1595{
1596 LOGV("write(%p, %u)", buffer, size);
1597 if ((buffer == 0) || (size == 0)) return size;
1598
1599 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1600 if (p == NULL) return NO_INIT;
1601 p += mSize;
1602 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1603 if (mSize + size > mHeap->getSize()) {
1604 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1605 size = mHeap->getSize() - mSize;
1606 }
1607 memcpy(p, buffer, size);
1608 mSize += size;
1609 return size;
1610}
1611
1612// call with lock held
1613status_t MediaPlayerService::AudioCache::wait()
1614{
1615 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001616 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 mSignal.wait(mLock);
1618 }
1619 mCommandComplete = false;
1620
1621 if (mError == NO_ERROR) {
1622 LOGV("wait - success");
1623 } else {
1624 LOGV("wait - error");
1625 }
1626 return mError;
1627}
1628
Gloria Wang162ee492011-04-11 17:23:27 -07001629void MediaPlayerService::AudioCache::notify(
1630 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631{
1632 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1633 AudioCache* p = static_cast<AudioCache*>(cookie);
1634
1635 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001636 switch (msg)
1637 {
1638 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 LOGE("Error %d, %d occurred", ext1, ext2);
1640 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001641 break;
1642 case MEDIA_PREPARED:
1643 LOGV("prepared");
1644 break;
1645 case MEDIA_PLAYBACK_COMPLETE:
1646 LOGV("playback complete");
1647 break;
1648 default:
1649 LOGV("ignored");
1650 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652
1653 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001654 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 p->mCommandComplete = true;
1656 p->mSignal.signal();
1657}
1658
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001659int MediaPlayerService::AudioCache::getSessionId()
1660{
1661 return 0;
1662}
1663
Gloria Wangd211f412011-02-19 18:37:57 -08001664void MediaPlayerService::addBatteryData(uint32_t params)
1665{
1666 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001667
1668 int32_t time = systemTime() / 1000000L;
1669
1670 // change audio output devices. This notification comes from AudioFlinger
1671 if ((params & kBatteryDataSpeakerOn)
1672 || (params & kBatteryDataOtherAudioDeviceOn)) {
1673
1674 int deviceOn[NUM_AUDIO_DEVICES];
1675 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1676 deviceOn[i] = 0;
1677 }
1678
1679 if ((params & kBatteryDataSpeakerOn)
1680 && (params & kBatteryDataOtherAudioDeviceOn)) {
1681 deviceOn[SPEAKER_AND_OTHER] = 1;
1682 } else if (params & kBatteryDataSpeakerOn) {
1683 deviceOn[SPEAKER] = 1;
1684 } else {
1685 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1686 }
1687
1688 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1689 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1690
1691 if (mBatteryAudio.refCount > 0) { // if playing audio
1692 if (!deviceOn[i]) {
1693 mBatteryAudio.lastTime[i] += time;
1694 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1695 mBatteryAudio.lastTime[i] = 0;
1696 } else {
1697 mBatteryAudio.lastTime[i] = 0 - time;
1698 }
1699 }
1700
1701 mBatteryAudio.deviceOn[i] = deviceOn[i];
1702 }
1703 }
1704 return;
1705 }
1706
1707 // an sudio stream is started
1708 if (params & kBatteryDataAudioFlingerStart) {
1709 // record the start time only if currently no other audio
1710 // is being played
1711 if (mBatteryAudio.refCount == 0) {
1712 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1713 if (mBatteryAudio.deviceOn[i]) {
1714 mBatteryAudio.lastTime[i] -= time;
1715 }
1716 }
1717 }
1718
1719 mBatteryAudio.refCount ++;
1720 return;
1721
1722 } else if (params & kBatteryDataAudioFlingerStop) {
1723 if (mBatteryAudio.refCount <= 0) {
1724 LOGW("Battery track warning: refCount is <= 0");
1725 return;
1726 }
1727
1728 // record the stop time only if currently this is the only
1729 // audio being played
1730 if (mBatteryAudio.refCount == 1) {
1731 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1732 if (mBatteryAudio.deviceOn[i]) {
1733 mBatteryAudio.lastTime[i] += time;
1734 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1735 mBatteryAudio.lastTime[i] = 0;
1736 }
1737 }
1738 }
1739
1740 mBatteryAudio.refCount --;
1741 return;
1742 }
1743
Gloria Wangd211f412011-02-19 18:37:57 -08001744 int uid = IPCThreadState::self()->getCallingUid();
1745 if (uid == AID_MEDIA) {
1746 return;
1747 }
1748 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001749
1750 if (index < 0) { // create a new entry for this UID
1751 BatteryUsageInfo info;
1752 info.audioTotalTime = 0;
1753 info.videoTotalTime = 0;
1754 info.audioLastTime = 0;
1755 info.videoLastTime = 0;
1756 info.refCount = 0;
1757
Gloria Wang9b3f1522011-02-24 14:51:45 -08001758 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1759 LOGE("Battery track error: no memory for new app");
1760 return;
1761 }
Gloria Wangd211f412011-02-19 18:37:57 -08001762 }
1763
1764 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1765
1766 if (params & kBatteryDataCodecStarted) {
1767 if (params & kBatteryDataTrackAudio) {
1768 info.audioLastTime -= time;
1769 info.refCount ++;
1770 }
1771 if (params & kBatteryDataTrackVideo) {
1772 info.videoLastTime -= time;
1773 info.refCount ++;
1774 }
1775 } else {
1776 if (info.refCount == 0) {
1777 LOGW("Battery track warning: refCount is already 0");
1778 return;
1779 } else if (info.refCount < 0) {
1780 LOGE("Battery track error: refCount < 0");
1781 mBatteryData.removeItem(uid);
1782 return;
1783 }
1784
1785 if (params & kBatteryDataTrackAudio) {
1786 info.audioLastTime += time;
1787 info.refCount --;
1788 }
1789 if (params & kBatteryDataTrackVideo) {
1790 info.videoLastTime += time;
1791 info.refCount --;
1792 }
1793
1794 // no stream is being played by this UID
1795 if (info.refCount == 0) {
1796 info.audioTotalTime += info.audioLastTime;
1797 info.audioLastTime = 0;
1798 info.videoTotalTime += info.videoLastTime;
1799 info.videoLastTime = 0;
1800 }
1801 }
1802}
1803
1804status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1805 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001806
1807 // audio output devices usage
1808 int32_t time = systemTime() / 1000000L; //in ms
1809 int32_t totalTime;
1810
1811 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1812 totalTime = mBatteryAudio.totalTime[i];
1813
1814 if (mBatteryAudio.deviceOn[i]
1815 && (mBatteryAudio.lastTime[i] != 0)) {
1816 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1817 totalTime += tmpTime;
1818 }
1819
1820 reply->writeInt32(totalTime);
1821 // reset the total time
1822 mBatteryAudio.totalTime[i] = 0;
1823 }
1824
1825 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001826 BatteryUsageInfo info;
1827 int size = mBatteryData.size();
1828
1829 reply->writeInt32(size);
1830 int i = 0;
1831
1832 while (i < size) {
1833 info = mBatteryData.valueAt(i);
1834
1835 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1836 reply->writeInt32(info.audioTotalTime);
1837 reply->writeInt32(info.videoTotalTime);
1838
1839 info.audioTotalTime = 0;
1840 info.videoTotalTime = 0;
1841
1842 // remove the UID entry where no stream is being played
1843 if (info.refCount <= 0) {
1844 mBatteryData.removeItemsAt(i);
1845 size --;
1846 i --;
1847 }
1848 i++;
1849 }
1850 return NO_ERROR;
1851}
nikobc726922009-07-20 15:07:26 -07001852} // namespace android