blob: 1e7c9693bc1a20efd4e50714adab89bca2381f09 [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 Zavin34bb4192011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070057
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
Nicolas Cataniab2c69392009-07-08 08:57:42 -070071namespace {
nikobc726922009-07-20 15:07:26 -070072using android::media::Metadata;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070073using android::status_t;
74using android::OK;
75using android::BAD_VALUE;
76using android::NOT_ENOUGH_DATA;
77using android::Parcel;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070078
79// Max number of entries in the filter.
80const int kMaxFilterSize = 64; // I pulled that out of thin air.
81
nikobc726922009-07-20 15:07:26 -070082// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070083
Nicolas Cataniab2c69392009-07-08 08:57:42 -070084
85// Unmarshall a filter from a Parcel.
86// Filter format in a parcel:
87//
88// 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
89// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
90// | number of entries (n) |
91// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92// | metadata type 1 |
93// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94// | metadata type 2 |
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// ....
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// | metadata type n |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100//
101// @param p Parcel that should start with a filter.
102// @param[out] filter On exit contains the list of metadata type to be
103// filtered.
104// @param[out] status On exit contains the status code to be returned.
105// @return true if the parcel starts with a valid filter.
106bool unmarshallFilter(const Parcel& p,
nikobc726922009-07-20 15:07:26 -0700107 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700108 status_t *status)
109{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700110 int32_t val;
111 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700112 {
113 LOGE("Failed to read filter's length");
114 *status = NOT_ENOUGH_DATA;
115 return false;
116 }
117
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700118 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700119 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700120 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700121 *status = BAD_VALUE;
122 return false;
123 }
124
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700125 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700126
127 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700128 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700129
nikobc726922009-07-20 15:07:26 -0700130 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700131
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700132
133 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700134 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700135 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700136 *status = NOT_ENOUGH_DATA;
137 return false;
138 }
139
nikobc726922009-07-20 15:07:26 -0700140 const Metadata::Type *data =
141 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700142
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700143 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700144 {
145 LOGE("Filter had no data");
146 *status = BAD_VALUE;
147 return false;
148 }
149
150 // TODO: The stl impl of vector would be more efficient here
151 // because it degenerates into a memcpy on pod types. Try to
152 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700153 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700154 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700155 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700156 ++data;
157 }
158 *status = OK;
159 return true;
160}
161
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700162// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700163// @param val To be searched.
164// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700165bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700166{
167 // Deal with empty and ANY right away
168 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700169 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700170
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700171 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700172}
173
174} // anonymous namespace
175
176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177namespace android {
178
179// TODO: Temp hack until we can register players
180typedef struct {
181 const char *extension;
182 const player_type playertype;
183} extmap;
184extmap FILE_EXTS [] = {
185 {".mid", SONIVOX_PLAYER},
186 {".midi", SONIVOX_PLAYER},
187 {".smf", SONIVOX_PLAYER},
188 {".xmf", SONIVOX_PLAYER},
189 {".imy", SONIVOX_PLAYER},
190 {".rtttl", SONIVOX_PLAYER},
191 {".rtx", SONIVOX_PLAYER},
192 {".ota", SONIVOX_PLAYER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193};
194
195// 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 -0800196/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
197/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
198
199void MediaPlayerService::instantiate() {
200 defaultServiceManager()->addService(
201 String16("media.player"), new MediaPlayerService());
202}
203
204MediaPlayerService::MediaPlayerService()
205{
206 LOGV("MediaPlayerService created");
207 mNextConnId = 1;
Gloria Wang9b3f1522011-02-24 14:51:45 -0800208
209 mBatteryAudio.refCount = 0;
210 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
211 mBatteryAudio.deviceOn[i] = 0;
212 mBatteryAudio.lastTime[i] = 0;
213 mBatteryAudio.totalTime[i] = 0;
214 }
215 // speaker is on by default
216 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217}
218
219MediaPlayerService::~MediaPlayerService()
220{
221 LOGV("MediaPlayerService destroyed");
222}
223
224sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
225{
Gloria Wang608a2632009-10-29 15:46:37 -0700226 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
227 wp<MediaRecorderClient> w = recorder;
228 Mutex::Autolock lock(mLock);
229 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 LOGV("Create new media recorder client from pid %d", pid);
231 return recorder;
232}
233
Gloria Wang608a2632009-10-29 15:46:37 -0700234void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
235{
236 Mutex::Autolock lock(mLock);
237 mMediaRecorderClients.remove(client);
238 LOGV("Delete media recorder client");
239}
240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
242{
243 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
244 LOGV("Create new media retriever from pid %d", pid);
245 return retriever;
246}
247
Andreas Huber25643002010-01-28 11:19:57 -0800248sp<IMediaPlayer> MediaPlayerService::create(
249 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
Eric Laurent619346f2010-06-21 09:27:30 -0700250 const KeyedVector<String8, String8> *headers, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251{
252 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700253
254 sp<Client> c = new Client(
255 this, pid, connId, client, audioSessionId,
256 IPCThreadState::self()->getCallingUid());
257
Eric Laurent619346f2010-06-21 09:27:30 -0700258 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
259 connId, pid, url, connId, audioSessionId);
Andreas Huber25643002010-01-28 11:19:57 -0800260 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 {
262 c.clear();
263 return c;
264 }
265 wp<Client> w = c;
266 Mutex::Autolock lock(mLock);
267 mClients.add(w);
268 return c;
269}
270
271sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Eric Laurent619346f2010-06-21 09:27:30 -0700272 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273{
274 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700275
276 sp<Client> c = new Client(
277 this, pid, connId, client, audioSessionId,
278 IPCThreadState::self()->getCallingUid());
279
Eric Laurent619346f2010-06-21 09:27:30 -0700280 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
281 connId, pid, fd, offset, length, audioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
283 c.clear();
284 } else {
285 wp<Client> w = c;
286 Mutex::Autolock lock(mLock);
287 mClients.add(w);
288 }
289 ::close(fd);
290 return c;
291}
292
Andreas Huber52b52cd2010-11-23 11:41:34 -0800293sp<IMediaPlayer> MediaPlayerService::create(
294 pid_t pid, const sp<IMediaPlayerClient> &client,
295 const sp<IStreamSource> &source, int audioSessionId) {
296 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700297
298 sp<Client> c = new Client(
299 this, pid, connId, client, audioSessionId,
300 IPCThreadState::self()->getCallingUid());
Andreas Huber52b52cd2010-11-23 11:41:34 -0800301
302 LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
303 connId, pid, audioSessionId);
304
305 if (OK != c->setDataSource(source)) {
306 c.clear();
307 } else {
308 wp<Client> w = c;
309 Mutex::Autolock lock(mLock);
310 mClients.add(w);
311 }
312
313 return c;
314}
315
Andreas Huber784202e2009-10-15 13:46:54 -0700316sp<IOMX> MediaPlayerService::getOMX() {
317 Mutex::Autolock autoLock(mLock);
318
319 if (mOMX.get() == NULL) {
320 mOMX = new OMX;
321 }
322
323 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700324}
325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
327{
328 const size_t SIZE = 256;
329 char buffer[SIZE];
330 String8 result;
331
332 result.append(" AudioCache\n");
333 if (mHeap != 0) {
334 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
335 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
336 result.append(buffer);
337 }
338 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
339 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
340 result.append(buffer);
341 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
342 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
343 result.append(buffer);
344 ::write(fd, result.string(), result.size());
345 return NO_ERROR;
346}
347
348status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
349{
350 const size_t SIZE = 256;
351 char buffer[SIZE];
352 String8 result;
353
354 result.append(" AudioOutput\n");
355 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
356 mStreamType, mLeftVolume, mRightVolume);
357 result.append(buffer);
358 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
359 mMsecsPerFrame, mLatency);
360 result.append(buffer);
Eric Laurent7070b362010-07-16 07:43:46 -0700361 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
362 mAuxEffectId, mSendLevel);
363 result.append(buffer);
364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 ::write(fd, result.string(), result.size());
366 if (mTrack != 0) {
367 mTrack->dump(fd, args);
368 }
369 return NO_ERROR;
370}
371
372status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
373{
374 const size_t SIZE = 256;
375 char buffer[SIZE];
376 String8 result;
377 result.append(" Client\n");
378 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
379 mPid, mConnId, mStatus, mLoop?"true": "false");
380 result.append(buffer);
381 write(fd, result.string(), result.size());
Andreas Huberfddf5d92011-06-07 15:52:25 -0700382 if (mPlayer != NULL) {
383 mPlayer->dump(fd, args);
384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 if (mAudioOutput != 0) {
386 mAudioOutput->dump(fd, args);
387 }
388 write(fd, "\n", 1);
389 return NO_ERROR;
390}
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
393{
394 const size_t SIZE = 256;
395 char buffer[SIZE];
396 String8 result;
397 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
398 snprintf(buffer, SIZE, "Permission Denial: "
399 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
400 IPCThreadState::self()->getCallingPid(),
401 IPCThreadState::self()->getCallingUid());
402 result.append(buffer);
403 } else {
404 Mutex::Autolock lock(mLock);
405 for (int i = 0, n = mClients.size(); i < n; ++i) {
406 sp<Client> c = mClients[i].promote();
407 if (c != 0) c->dump(fd, args);
408 }
James Dong929642e2010-07-08 11:16:11 -0700409 if (mMediaRecorderClients.size() == 0) {
410 result.append(" No media recorder client\n\n");
411 } else {
412 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
413 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
414 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
415 result.append(buffer);
416 write(fd, result.string(), result.size());
417 result = "\n";
418 c->dump(fd, args);
419 }
Gloria Wang608a2632009-10-29 15:46:37 -0700420 }
421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 result.append(" Files opened and/or mapped:\n");
Glenn Kasten6af763b2011-05-04 17:58:57 -0700423 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 FILE *f = fopen(buffer, "r");
425 if (f) {
426 while (!feof(f)) {
427 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700428 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700430 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 strstr(buffer, " /system/media/")) {
432 result.append(" ");
433 result.append(buffer);
434 }
435 }
436 fclose(f);
437 } else {
438 result.append("couldn't open ");
439 result.append(buffer);
440 result.append("\n");
441 }
442
Glenn Kasten6af763b2011-05-04 17:58:57 -0700443 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 DIR *d = opendir(buffer);
445 if (d) {
446 struct dirent *ent;
447 while((ent = readdir(d)) != NULL) {
448 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten6af763b2011-05-04 17:58:57 -0700449 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 struct stat s;
451 if (lstat(buffer, &s) == 0) {
452 if ((s.st_mode & S_IFMT) == S_IFLNK) {
453 char linkto[256];
454 int len = readlink(buffer, linkto, sizeof(linkto));
455 if(len > 0) {
456 if(len > 255) {
457 linkto[252] = '.';
458 linkto[253] = '.';
459 linkto[254] = '.';
460 linkto[255] = 0;
461 } else {
462 linkto[len] = 0;
463 }
Dave Sparks124a3462010-09-27 16:55:18 -0700464 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700466 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 strstr(linkto, "/system/media/") == linkto) {
468 result.append(" ");
469 result.append(buffer);
470 result.append(" -> ");
471 result.append(linkto);
472 result.append("\n");
473 }
474 }
475 } else {
476 result.append(" unexpected type for ");
477 result.append(buffer);
478 result.append("\n");
479 }
480 }
481 }
482 }
483 closedir(d);
484 } else {
485 result.append("couldn't open ");
486 result.append(buffer);
487 result.append("\n");
488 }
489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 bool dumpMem = false;
491 for (size_t i = 0; i < args.size(); i++) {
492 if (args[i] == String16("-m")) {
493 dumpMem = true;
494 }
495 }
496 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700497 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500 write(fd, result.string(), result.size());
501 return NO_ERROR;
502}
503
504void MediaPlayerService::removeClient(wp<Client> client)
505{
506 Mutex::Autolock lock(mLock);
507 mClients.remove(client);
508}
509
Andreas Huber603d7392011-06-30 15:47:02 -0700510MediaPlayerService::Client::Client(
511 const sp<MediaPlayerService>& service, pid_t pid,
512 int32_t connId, const sp<IMediaPlayerClient>& client,
513 int audioSessionId, uid_t uid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514{
515 LOGV("Client(%d) constructor", connId);
516 mPid = pid;
517 mConnId = connId;
518 mService = service;
519 mClient = client;
520 mLoop = false;
521 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700522 mAudioSessionId = audioSessionId;
Andreas Huber603d7392011-06-30 15:47:02 -0700523 mUID = uid;
Eric Laurent619346f2010-06-21 09:27:30 -0700524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525#if CALLBACK_ANTAGONIZER
526 LOGD("create Antagonizer");
527 mAntagonizer = new Antagonizer(notify, this);
528#endif
529}
530
531MediaPlayerService::Client::~Client()
532{
533 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
534 mAudioOutput.clear();
535 wp<Client> client(this);
536 disconnect();
537 mService->removeClient(client);
538}
539
540void MediaPlayerService::Client::disconnect()
541{
542 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
543 // grab local reference and clear main reference to prevent future
544 // access to object
545 sp<MediaPlayerBase> p;
546 {
547 Mutex::Autolock l(mLock);
548 p = mPlayer;
549 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700550 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 mPlayer.clear();
553
554 // clear the notification to prevent callbacks to dead client
555 // and reset the player. We assume the player will serialize
556 // access to itself if necessary.
557 if (p != 0) {
558 p->setNotifyCallback(0, 0);
559#if CALLBACK_ANTAGONIZER
560 LOGD("kill Antagonizer");
561 mAntagonizer->kill();
562#endif
563 p->reset();
564 }
565
566 IPCThreadState::self()->flushCommands();
567}
568
Andreas Huber0d596d42009-08-07 09:30:32 -0700569static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700570 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700571}
572
James Dong392ff3b2009-09-06 14:29:45 -0700573player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574{
575 char buf[20];
576 lseek(fd, offset, SEEK_SET);
577 read(fd, buf, sizeof(buf));
578 lseek(fd, offset, SEEK_SET);
579
580 long ident = *((long*)buf);
581
582 // Ogg vorbis?
583 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700584 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585
586 // Some kind of MIDI?
587 EAS_DATA_HANDLE easdata;
588 if (EAS_Init(&easdata) == EAS_SUCCESS) {
589 EAS_FILE locator;
590 locator.path = NULL;
591 locator.fd = fd;
592 locator.offset = offset;
593 locator.length = length;
594 EAS_HANDLE eashandle;
595 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
596 EAS_CloseFile(easdata, eashandle);
597 EAS_Shutdown(easdata);
598 return SONIVOX_PLAYER;
599 }
600 EAS_Shutdown(easdata);
601 }
602
Andreas Huber0d596d42009-08-07 09:30:32 -0700603 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604}
605
James Dong392ff3b2009-09-06 14:29:45 -0700606player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700608 if (TestPlayerStub::canBeUsed(url)) {
609 return TEST_PLAYER;
610 }
611
Andreas Huber554d0ea2011-03-21 16:28:04 -0700612 if (!strncasecmp("http://", url, 7)
613 || !strncasecmp("https://", url, 8)) {
Andreas Huberd6c421f2011-02-16 09:05:38 -0800614 size_t len = strlen(url);
615 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
616 return NU_PLAYER;
617 }
Andreas Huber54e66492010-12-23 10:27:40 -0800618
Andreas Huberd6c421f2011-02-16 09:05:38 -0800619 if (strstr(url,"m3u8")) {
620 return NU_PLAYER;
Andreas Huber54e66492010-12-23 10:27:40 -0800621 }
622 }
623
The Android Open Source Project9066cfe2009-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 Enoebcc51d2010-03-19 23:18:02 +0900630 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700631 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633 }
634 }
635
Andreas Huber0d596d42009-08-07 09:30:32 -0700636 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -0800644 case SONIVOX_PLAYER:
645 LOGV(" create MidiFile");
646 p = new MidiFile();
647 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700648 case STAGEFRIGHT_PLAYER:
649 LOGV(" create StagefrightPlayer");
650 p = new StagefrightPlayer;
651 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800652 case NU_PLAYER:
653 LOGV(" create NuPlayer");
654 p = new NuPlayerDriver;
655 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700656 case TEST_PLAYER:
657 LOGV("Create Test Player stub");
658 p = new TestPlayerStub();
659 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800660 default:
661 LOGE("Unknown player type: %d", playerType);
662 return NULL;
The Android Open Source Project9066cfe2009-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 }
Andreas Huber603d7392011-06-30 15:47:02 -0700688
689 p->setUID(mUID);
690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 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 Wangd01ec6e2011-04-25 17:28:22 -07001027status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1028 LOGV("[%d] setParameter(%d)", mConnId, key);
1029 sp<MediaPlayerBase> p = getPlayer();
1030 if (p == 0) return UNKNOWN_ERROR;
1031 return p->setParameter(key, request);
1032}
1033
1034status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1035 LOGV("[%d] getParameter(%d)", mConnId, key);
1036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 return p->getParameter(key, reply);
1039}
1040
Gloria Wang162ee492011-04-11 17:23:27 -07001041void MediaPlayerService::Client::notify(
1042 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043{
1044 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001045
1046 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001047 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001048 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001049
1050 if(client->shouldDropMetadata(metadata_type)) {
1051 return;
1052 }
1053
1054 // Update the list of metadata that have changed. getMetadata
1055 // also access mMetadataUpdated and clears it.
1056 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001059 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060}
1061
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001062
nikobc726922009-07-20 15:07:26 -07001063bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001064{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001065 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001066
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001067 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001068 return true;
1069 }
1070
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001071 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001072 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001073 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001074 return true;
1075 }
1076}
1077
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001078
nikobc726922009-07-20 15:07:26 -07001079void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001080 Mutex::Autolock lock(mLock);
1081 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1082 mMetadataUpdated.add(metadata_type);
1083 }
1084}
1085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086#if CALLBACK_ANTAGONIZER
1087const int Antagonizer::interval = 10000; // 10 msecs
1088
1089Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1090 mExit(false), mActive(false), mClient(client), mCb(cb)
1091{
1092 createThread(callbackThread, this);
1093}
1094
1095void Antagonizer::kill()
1096{
1097 Mutex::Autolock _l(mLock);
1098 mActive = false;
1099 mExit = true;
1100 mCondition.wait(mLock);
1101}
1102
1103int Antagonizer::callbackThread(void* user)
1104{
1105 LOGD("Antagonizer started");
1106 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1107 while (!p->mExit) {
1108 if (p->mActive) {
1109 LOGV("send event");
1110 p->mCb(p->mClient, 0, 0, 0);
1111 }
1112 usleep(interval);
1113 }
1114 Mutex::Autolock _l(p->mLock);
1115 p->mCondition.signal();
1116 LOGD("Antagonizer stopped");
1117 return 0;
1118}
1119#endif
1120
1121static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1122
1123sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1124{
1125 LOGV("decode(%s)", url);
1126 sp<MemoryBase> mem;
1127 sp<MediaPlayerBase> player;
1128
1129 // Protect our precious, precious DRMd ringtones by only allowing
1130 // decoding of http, but not filesystem paths or content Uris.
1131 // If the application wants to decode those, it should open a
1132 // filedescriptor for them and use that.
1133 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1134 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1135 return mem;
1136 }
1137
1138 player_type playerType = getPlayerType(url);
1139 LOGV("player type = %d", playerType);
1140
1141 // create the right type of player
1142 sp<AudioCache> cache = new AudioCache(url);
1143 player = android::createPlayer(playerType, cache.get(), cache->notify);
1144 if (player == NULL) goto Exit;
1145 if (player->hardwareOutput()) goto Exit;
1146
1147 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1148
1149 // set data source
1150 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1151
1152 LOGV("prepare");
1153 player->prepareAsync();
1154
1155 LOGV("wait for prepare");
1156 if (cache->wait() != NO_ERROR) goto Exit;
1157
1158 LOGV("start");
1159 player->start();
1160
1161 LOGV("wait for playback complete");
1162 if (cache->wait() != NO_ERROR) goto Exit;
1163
1164 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1165 *pSampleRate = cache->sampleRate();
1166 *pNumChannels = cache->channelCount();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001167 *pFormat = (int)cache->format();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1169
1170Exit:
1171 if (player != 0) player->reset();
1172 return mem;
1173}
1174
1175sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1176{
1177 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1178 sp<MemoryBase> mem;
1179 sp<MediaPlayerBase> player;
1180
1181 player_type playerType = getPlayerType(fd, offset, length);
1182 LOGV("player type = %d", playerType);
1183
1184 // create the right type of player
1185 sp<AudioCache> cache = new AudioCache("decode_fd");
1186 player = android::createPlayer(playerType, cache.get(), cache->notify);
1187 if (player == NULL) goto Exit;
1188 if (player->hardwareOutput()) goto Exit;
1189
1190 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1191
1192 // set data source
1193 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1194
1195 LOGV("prepare");
1196 player->prepareAsync();
1197
1198 LOGV("wait for prepare");
1199 if (cache->wait() != NO_ERROR) goto Exit;
1200
1201 LOGV("start");
1202 player->start();
1203
1204 LOGV("wait for playback complete");
1205 if (cache->wait() != NO_ERROR) goto Exit;
1206
1207 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1208 *pSampleRate = cache->sampleRate();
1209 *pNumChannels = cache->channelCount();
1210 *pFormat = cache->format();
1211 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1212
1213Exit:
1214 if (player != 0) player->reset();
1215 ::close(fd);
1216 return mem;
1217}
1218
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220#undef LOG_TAG
1221#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001222MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001223 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001224 mCallbackCookie(NULL),
1225 mSessionId(sessionId) {
1226 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001228 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 mLeftVolume = 1.0;
1230 mRightVolume = 1.0;
1231 mLatency = 0;
1232 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001233 mAuxEffectId = 0;
1234 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 setMinBufferCount();
1236}
1237
1238MediaPlayerService::AudioOutput::~AudioOutput()
1239{
1240 close();
1241}
1242
1243void MediaPlayerService::AudioOutput::setMinBufferCount()
1244{
1245 char value[PROPERTY_VALUE_MAX];
1246 if (property_get("ro.kernel.qemu", value, 0)) {
1247 mIsOnEmulator = true;
1248 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1249 }
1250}
1251
1252bool MediaPlayerService::AudioOutput::isOnEmulator()
1253{
1254 setMinBufferCount();
1255 return mIsOnEmulator;
1256}
1257
1258int MediaPlayerService::AudioOutput::getMinBufferCount()
1259{
1260 setMinBufferCount();
1261 return mMinBufferCount;
1262}
1263
1264ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1265{
1266 if (mTrack == 0) return NO_INIT;
1267 return mTrack->frameCount() * frameSize();
1268}
1269
1270ssize_t MediaPlayerService::AudioOutput::frameCount() const
1271{
1272 if (mTrack == 0) return NO_INIT;
1273 return mTrack->frameCount();
1274}
1275
1276ssize_t MediaPlayerService::AudioOutput::channelCount() const
1277{
1278 if (mTrack == 0) return NO_INIT;
1279 return mTrack->channelCount();
1280}
1281
1282ssize_t MediaPlayerService::AudioOutput::frameSize() const
1283{
1284 if (mTrack == 0) return NO_INIT;
1285 return mTrack->frameSize();
1286}
1287
1288uint32_t MediaPlayerService::AudioOutput::latency () const
1289{
1290 return mLatency;
1291}
1292
1293float MediaPlayerService::AudioOutput::msecsPerFrame() const
1294{
1295 return mMsecsPerFrame;
1296}
1297
Eric Laurent0986e792010-01-19 17:37:09 -08001298status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1299{
1300 if (mTrack == 0) return NO_INIT;
1301 return mTrack->getPosition(position);
1302}
1303
Andreas Hubere46b7be2009-07-14 16:56:47 -07001304status_t MediaPlayerService::AudioOutput::open(
1305 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1306 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001308 mCallback = cb;
1309 mCallbackCookie = cookie;
1310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 // Check argument "bufferCount" against the mininum buffer count
1312 if (bufferCount < mMinBufferCount) {
1313 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1314 bufferCount = mMinBufferCount;
1315
1316 }
Eric Laurent619346f2010-06-21 09:27:30 -07001317 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 if (mTrack) close();
1319 int afSampleRate;
1320 int afFrameCount;
1321 int frameCount;
1322
1323 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1324 return NO_INIT;
1325 }
1326 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1327 return NO_INIT;
1328 }
1329
1330 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001331
1332 AudioTrack *t;
1333 if (mCallback != NULL) {
1334 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001335 mStreamType,
1336 sampleRate,
1337 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001338 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001339 frameCount,
1340 0 /* flags */,
1341 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001342 this,
1343 0,
1344 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001345 } else {
1346 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001347 mStreamType,
1348 sampleRate,
1349 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001350 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001351 frameCount,
1352 0,
1353 NULL,
1354 NULL,
1355 0,
1356 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001357 }
1358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1360 LOGE("Unable to create audio track");
1361 delete t;
1362 return NO_INIT;
1363 }
1364
1365 LOGV("setVolume");
1366 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001369 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001371
1372 t->setAuxEffectSendLevel(mSendLevel);
1373 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374}
1375
1376void MediaPlayerService::AudioOutput::start()
1377{
1378 LOGV("start");
1379 if (mTrack) {
1380 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001381 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 mTrack->start();
1383 }
1384}
1385
Marco Nelissene274db12010-01-12 09:23:54 -08001386
1387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1389{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001390 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001393 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001394 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001395 return ret;
1396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 return NO_INIT;
1398}
1399
1400void MediaPlayerService::AudioOutput::stop()
1401{
1402 LOGV("stop");
1403 if (mTrack) mTrack->stop();
1404}
1405
1406void MediaPlayerService::AudioOutput::flush()
1407{
1408 LOGV("flush");
1409 if (mTrack) mTrack->flush();
1410}
1411
1412void MediaPlayerService::AudioOutput::pause()
1413{
1414 LOGV("pause");
1415 if (mTrack) mTrack->pause();
1416}
1417
1418void MediaPlayerService::AudioOutput::close()
1419{
1420 LOGV("close");
1421 delete mTrack;
1422 mTrack = 0;
1423}
1424
1425void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1426{
1427 LOGV("setVolume(%f, %f)", left, right);
1428 mLeftVolume = left;
1429 mRightVolume = right;
1430 if (mTrack) {
1431 mTrack->setVolume(left, right);
1432 }
1433}
1434
Eric Laurent7070b362010-07-16 07:43:46 -07001435status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1436{
1437 LOGV("setAuxEffectSendLevel(%f)", level);
1438 mSendLevel = level;
1439 if (mTrack) {
1440 return mTrack->setAuxEffectSendLevel(level);
1441 }
1442 return NO_ERROR;
1443}
1444
1445status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1446{
1447 LOGV("attachAuxEffect(%d)", effectId);
1448 mAuxEffectId = effectId;
1449 if (mTrack) {
1450 return mTrack->attachAuxEffect(effectId);
1451 }
1452 return NO_ERROR;
1453}
1454
Andreas Hubere46b7be2009-07-14 16:56:47 -07001455// static
1456void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastene46a86f2011-06-01 15:20:35 -07001457 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001458 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001459 if (event != AudioTrack::EVENT_MORE_DATA) {
1460 return;
1461 }
1462
1463 AudioOutput *me = (AudioOutput *)cookie;
1464 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1465
Andreas Huber6ed937e2010-02-09 16:59:18 -08001466 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001467 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001468
Andreas Huberc6e3b272011-04-04 11:43:40 -07001469 if (actualSize == 0 && buffer->size > 0) {
1470 // We've reached EOS but the audio track is not stopped yet,
1471 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001472
Andreas Huberc6e3b272011-04-04 11:43:40 -07001473 memset(buffer->raw, 0, buffer->size);
1474 actualSize = buffer->size;
1475 }
1476
1477 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001478}
1479
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001480int MediaPlayerService::AudioOutput::getSessionId()
1481{
1482 return mSessionId;
1483}
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485#undef LOG_TAG
1486#define LOG_TAG "AudioCache"
1487MediaPlayerService::AudioCache::AudioCache(const char* name) :
1488 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1489 mError(NO_ERROR), mCommandComplete(false)
1490{
1491 // create ashmem heap
1492 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1493}
1494
1495uint32_t MediaPlayerService::AudioCache::latency () const
1496{
1497 return 0;
1498}
1499
1500float MediaPlayerService::AudioCache::msecsPerFrame() const
1501{
1502 return mMsecsPerFrame;
1503}
1504
Eric Laurent0986e792010-01-19 17:37:09 -08001505status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1506{
1507 if (position == 0) return BAD_VALUE;
1508 *position = mSize;
1509 return NO_ERROR;
1510}
1511
Andreas Huber6ed937e2010-02-09 16:59:18 -08001512////////////////////////////////////////////////////////////////////////////////
1513
1514struct CallbackThread : public Thread {
1515 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1516 MediaPlayerBase::AudioSink::AudioCallback cb,
1517 void *cookie);
1518
1519protected:
1520 virtual ~CallbackThread();
1521
1522 virtual bool threadLoop();
1523
1524private:
1525 wp<MediaPlayerBase::AudioSink> mSink;
1526 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1527 void *mCookie;
1528 void *mBuffer;
1529 size_t mBufferSize;
1530
1531 CallbackThread(const CallbackThread &);
1532 CallbackThread &operator=(const CallbackThread &);
1533};
1534
1535CallbackThread::CallbackThread(
1536 const wp<MediaPlayerBase::AudioSink> &sink,
1537 MediaPlayerBase::AudioSink::AudioCallback cb,
1538 void *cookie)
1539 : mSink(sink),
1540 mCallback(cb),
1541 mCookie(cookie),
1542 mBuffer(NULL),
1543 mBufferSize(0) {
1544}
1545
1546CallbackThread::~CallbackThread() {
1547 if (mBuffer) {
1548 free(mBuffer);
1549 mBuffer = NULL;
1550 }
1551}
1552
1553bool CallbackThread::threadLoop() {
1554 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1555 if (sink == NULL) {
1556 return false;
1557 }
1558
1559 if (mBuffer == NULL) {
1560 mBufferSize = sink->bufferSize();
1561 mBuffer = malloc(mBufferSize);
1562 }
1563
1564 size_t actualSize =
1565 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1566
1567 if (actualSize > 0) {
1568 sink->write(mBuffer, actualSize);
1569 }
1570
1571 return true;
1572}
1573
1574////////////////////////////////////////////////////////////////////////////////
1575
Andreas Hubere46b7be2009-07-14 16:56:47 -07001576status_t MediaPlayerService::AudioCache::open(
1577 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1578 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579{
Dave Sparks14f89402009-12-09 20:20:26 -08001580 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001581 if (mHeap->getHeapID() < 0) {
1582 return NO_INIT;
1583 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 mSampleRate = sampleRate;
1586 mChannelCount = (uint16_t)channelCount;
1587 mFormat = (uint16_t)format;
1588 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001589
1590 if (cb != NULL) {
1591 mCallbackThread = new CallbackThread(this, cb, cookie);
1592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 return NO_ERROR;
1594}
1595
Andreas Huber6ed937e2010-02-09 16:59:18 -08001596void MediaPlayerService::AudioCache::start() {
1597 if (mCallbackThread != NULL) {
1598 mCallbackThread->run("AudioCache callback");
1599 }
1600}
1601
1602void MediaPlayerService::AudioCache::stop() {
1603 if (mCallbackThread != NULL) {
1604 mCallbackThread->requestExitAndWait();
1605 }
1606}
1607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1609{
1610 LOGV("write(%p, %u)", buffer, size);
1611 if ((buffer == 0) || (size == 0)) return size;
1612
1613 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1614 if (p == NULL) return NO_INIT;
1615 p += mSize;
1616 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1617 if (mSize + size > mHeap->getSize()) {
1618 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1619 size = mHeap->getSize() - mSize;
1620 }
1621 memcpy(p, buffer, size);
1622 mSize += size;
1623 return size;
1624}
1625
1626// call with lock held
1627status_t MediaPlayerService::AudioCache::wait()
1628{
1629 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001630 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 mSignal.wait(mLock);
1632 }
1633 mCommandComplete = false;
1634
1635 if (mError == NO_ERROR) {
1636 LOGV("wait - success");
1637 } else {
1638 LOGV("wait - error");
1639 }
1640 return mError;
1641}
1642
Gloria Wang162ee492011-04-11 17:23:27 -07001643void MediaPlayerService::AudioCache::notify(
1644 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645{
1646 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1647 AudioCache* p = static_cast<AudioCache*>(cookie);
1648
1649 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001650 switch (msg)
1651 {
1652 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 LOGE("Error %d, %d occurred", ext1, ext2);
1654 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001655 break;
1656 case MEDIA_PREPARED:
1657 LOGV("prepared");
1658 break;
1659 case MEDIA_PLAYBACK_COMPLETE:
1660 LOGV("playback complete");
1661 break;
1662 default:
1663 LOGV("ignored");
1664 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666
1667 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001668 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 p->mCommandComplete = true;
1670 p->mSignal.signal();
1671}
1672
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001673int MediaPlayerService::AudioCache::getSessionId()
1674{
1675 return 0;
1676}
1677
Gloria Wangd211f412011-02-19 18:37:57 -08001678void MediaPlayerService::addBatteryData(uint32_t params)
1679{
1680 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001681
1682 int32_t time = systemTime() / 1000000L;
1683
1684 // change audio output devices. This notification comes from AudioFlinger
1685 if ((params & kBatteryDataSpeakerOn)
1686 || (params & kBatteryDataOtherAudioDeviceOn)) {
1687
1688 int deviceOn[NUM_AUDIO_DEVICES];
1689 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1690 deviceOn[i] = 0;
1691 }
1692
1693 if ((params & kBatteryDataSpeakerOn)
1694 && (params & kBatteryDataOtherAudioDeviceOn)) {
1695 deviceOn[SPEAKER_AND_OTHER] = 1;
1696 } else if (params & kBatteryDataSpeakerOn) {
1697 deviceOn[SPEAKER] = 1;
1698 } else {
1699 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1700 }
1701
1702 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1703 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1704
1705 if (mBatteryAudio.refCount > 0) { // if playing audio
1706 if (!deviceOn[i]) {
1707 mBatteryAudio.lastTime[i] += time;
1708 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1709 mBatteryAudio.lastTime[i] = 0;
1710 } else {
1711 mBatteryAudio.lastTime[i] = 0 - time;
1712 }
1713 }
1714
1715 mBatteryAudio.deviceOn[i] = deviceOn[i];
1716 }
1717 }
1718 return;
1719 }
1720
1721 // an sudio stream is started
1722 if (params & kBatteryDataAudioFlingerStart) {
1723 // record the start time only if currently no other audio
1724 // is being played
1725 if (mBatteryAudio.refCount == 0) {
1726 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1727 if (mBatteryAudio.deviceOn[i]) {
1728 mBatteryAudio.lastTime[i] -= time;
1729 }
1730 }
1731 }
1732
1733 mBatteryAudio.refCount ++;
1734 return;
1735
1736 } else if (params & kBatteryDataAudioFlingerStop) {
1737 if (mBatteryAudio.refCount <= 0) {
1738 LOGW("Battery track warning: refCount is <= 0");
1739 return;
1740 }
1741
1742 // record the stop time only if currently this is the only
1743 // audio being played
1744 if (mBatteryAudio.refCount == 1) {
1745 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1746 if (mBatteryAudio.deviceOn[i]) {
1747 mBatteryAudio.lastTime[i] += time;
1748 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1749 mBatteryAudio.lastTime[i] = 0;
1750 }
1751 }
1752 }
1753
1754 mBatteryAudio.refCount --;
1755 return;
1756 }
1757
Gloria Wangd211f412011-02-19 18:37:57 -08001758 int uid = IPCThreadState::self()->getCallingUid();
1759 if (uid == AID_MEDIA) {
1760 return;
1761 }
1762 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001763
1764 if (index < 0) { // create a new entry for this UID
1765 BatteryUsageInfo info;
1766 info.audioTotalTime = 0;
1767 info.videoTotalTime = 0;
1768 info.audioLastTime = 0;
1769 info.videoLastTime = 0;
1770 info.refCount = 0;
1771
Gloria Wang9b3f1522011-02-24 14:51:45 -08001772 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1773 LOGE("Battery track error: no memory for new app");
1774 return;
1775 }
Gloria Wangd211f412011-02-19 18:37:57 -08001776 }
1777
1778 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1779
1780 if (params & kBatteryDataCodecStarted) {
1781 if (params & kBatteryDataTrackAudio) {
1782 info.audioLastTime -= time;
1783 info.refCount ++;
1784 }
1785 if (params & kBatteryDataTrackVideo) {
1786 info.videoLastTime -= time;
1787 info.refCount ++;
1788 }
1789 } else {
1790 if (info.refCount == 0) {
1791 LOGW("Battery track warning: refCount is already 0");
1792 return;
1793 } else if (info.refCount < 0) {
1794 LOGE("Battery track error: refCount < 0");
1795 mBatteryData.removeItem(uid);
1796 return;
1797 }
1798
1799 if (params & kBatteryDataTrackAudio) {
1800 info.audioLastTime += time;
1801 info.refCount --;
1802 }
1803 if (params & kBatteryDataTrackVideo) {
1804 info.videoLastTime += time;
1805 info.refCount --;
1806 }
1807
1808 // no stream is being played by this UID
1809 if (info.refCount == 0) {
1810 info.audioTotalTime += info.audioLastTime;
1811 info.audioLastTime = 0;
1812 info.videoTotalTime += info.videoLastTime;
1813 info.videoLastTime = 0;
1814 }
1815 }
1816}
1817
1818status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1819 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001820
1821 // audio output devices usage
1822 int32_t time = systemTime() / 1000000L; //in ms
1823 int32_t totalTime;
1824
1825 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1826 totalTime = mBatteryAudio.totalTime[i];
1827
1828 if (mBatteryAudio.deviceOn[i]
1829 && (mBatteryAudio.lastTime[i] != 0)) {
1830 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1831 totalTime += tmpTime;
1832 }
1833
1834 reply->writeInt32(totalTime);
1835 // reset the total time
1836 mBatteryAudio.totalTime[i] = 0;
1837 }
1838
1839 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001840 BatteryUsageInfo info;
1841 int size = mBatteryData.size();
1842
1843 reply->writeInt32(size);
1844 int i = 0;
1845
1846 while (i < size) {
1847 info = mBatteryData.valueAt(i);
1848
1849 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1850 reply->writeInt32(info.audioTotalTime);
1851 reply->writeInt32(info.videoTotalTime);
1852
1853 info.audioTotalTime = 0;
1854 info.videoTotalTime = 0;
1855
1856 // remove the UID entry where no stream is being played
1857 if (info.refCount <= 0) {
1858 mBatteryData.removeItemsAt(i);
1859 size --;
1860 i --;
1861 }
1862 i++;
1863 }
1864 return NO_ERROR;
1865}
nikobc726922009-07-20 15:07:26 -07001866} // namespace android