blob: 8630ec1945b81f730c5c3172d9c548b9a7bf9a36 [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
Ashish Sharmad5a20d82011-07-07 17:57:05 -0700258 LOGV("Create new client(%d) from pid %d, uid %d, url=%s, connId=%d, audioSessionId=%d",
259 connId, pid, IPCThreadState::self()->getCallingUid(), 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
Ashish Sharmad5a20d82011-07-07 17:57:05 -0700280 LOGV("Create new client(%d) from pid %d, uid %d, fd=%d, offset=%lld, "
281 "length=%lld, audioSessionId=%d", connId, pid,
282 IPCThreadState::self()->getCallingUid(), fd, offset, length, audioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
284 c.clear();
285 } else {
286 wp<Client> w = c;
287 Mutex::Autolock lock(mLock);
288 mClients.add(w);
289 }
290 ::close(fd);
291 return c;
292}
293
Andreas Huber52b52cd2010-11-23 11:41:34 -0800294sp<IMediaPlayer> MediaPlayerService::create(
295 pid_t pid, const sp<IMediaPlayerClient> &client,
296 const sp<IStreamSource> &source, int audioSessionId) {
297 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700298
299 sp<Client> c = new Client(
300 this, pid, connId, client, audioSessionId,
301 IPCThreadState::self()->getCallingUid());
Andreas Huber52b52cd2010-11-23 11:41:34 -0800302
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());
Andreas Huberfddf5d92011-06-07 15:52:25 -0700383 if (mPlayer != NULL) {
384 mPlayer->dump(fd, args);
385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 if (mAudioOutput != 0) {
387 mAudioOutput->dump(fd, args);
388 }
389 write(fd, "\n", 1);
390 return NO_ERROR;
391}
392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
394{
395 const size_t SIZE = 256;
396 char buffer[SIZE];
397 String8 result;
398 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
399 snprintf(buffer, SIZE, "Permission Denial: "
400 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
401 IPCThreadState::self()->getCallingPid(),
402 IPCThreadState::self()->getCallingUid());
403 result.append(buffer);
404 } else {
405 Mutex::Autolock lock(mLock);
406 for (int i = 0, n = mClients.size(); i < n; ++i) {
407 sp<Client> c = mClients[i].promote();
408 if (c != 0) c->dump(fd, args);
409 }
James Dong929642e2010-07-08 11:16:11 -0700410 if (mMediaRecorderClients.size() == 0) {
411 result.append(" No media recorder client\n\n");
412 } else {
413 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
414 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
415 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
416 result.append(buffer);
417 write(fd, result.string(), result.size());
418 result = "\n";
419 c->dump(fd, args);
420 }
Gloria Wang608a2632009-10-29 15:46:37 -0700421 }
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 result.append(" Files opened and/or mapped:\n");
Glenn Kasten6af763b2011-05-04 17:58:57 -0700424 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 FILE *f = fopen(buffer, "r");
426 if (f) {
427 while (!feof(f)) {
428 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700429 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700431 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 strstr(buffer, " /system/media/")) {
433 result.append(" ");
434 result.append(buffer);
435 }
436 }
437 fclose(f);
438 } else {
439 result.append("couldn't open ");
440 result.append(buffer);
441 result.append("\n");
442 }
443
Glenn Kasten6af763b2011-05-04 17:58:57 -0700444 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 DIR *d = opendir(buffer);
446 if (d) {
447 struct dirent *ent;
448 while((ent = readdir(d)) != NULL) {
449 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten6af763b2011-05-04 17:58:57 -0700450 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 struct stat s;
452 if (lstat(buffer, &s) == 0) {
453 if ((s.st_mode & S_IFMT) == S_IFLNK) {
454 char linkto[256];
455 int len = readlink(buffer, linkto, sizeof(linkto));
456 if(len > 0) {
457 if(len > 255) {
458 linkto[252] = '.';
459 linkto[253] = '.';
460 linkto[254] = '.';
461 linkto[255] = 0;
462 } else {
463 linkto[len] = 0;
464 }
Dave Sparks124a3462010-09-27 16:55:18 -0700465 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700467 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 strstr(linkto, "/system/media/") == linkto) {
469 result.append(" ");
470 result.append(buffer);
471 result.append(" -> ");
472 result.append(linkto);
473 result.append("\n");
474 }
475 }
476 } else {
477 result.append(" unexpected type for ");
478 result.append(buffer);
479 result.append("\n");
480 }
481 }
482 }
483 }
484 closedir(d);
485 } else {
486 result.append("couldn't open ");
487 result.append(buffer);
488 result.append("\n");
489 }
490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 bool dumpMem = false;
492 for (size_t i = 0; i < args.size(); i++) {
493 if (args[i] == String16("-m")) {
494 dumpMem = true;
495 }
496 }
497 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700498 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
501 write(fd, result.string(), result.size());
502 return NO_ERROR;
503}
504
505void MediaPlayerService::removeClient(wp<Client> client)
506{
507 Mutex::Autolock lock(mLock);
508 mClients.remove(client);
509}
510
Andreas Huber603d7392011-06-30 15:47:02 -0700511MediaPlayerService::Client::Client(
512 const sp<MediaPlayerService>& service, pid_t pid,
513 int32_t connId, const sp<IMediaPlayerClient>& client,
514 int audioSessionId, uid_t uid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515{
516 LOGV("Client(%d) constructor", connId);
517 mPid = pid;
518 mConnId = connId;
519 mService = service;
520 mClient = client;
521 mLoop = false;
522 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700523 mAudioSessionId = audioSessionId;
Andreas Huber603d7392011-06-30 15:47:02 -0700524 mUID = uid;
Eric Laurent619346f2010-06-21 09:27:30 -0700525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526#if CALLBACK_ANTAGONIZER
527 LOGD("create Antagonizer");
528 mAntagonizer = new Antagonizer(notify, this);
529#endif
530}
531
532MediaPlayerService::Client::~Client()
533{
534 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
535 mAudioOutput.clear();
536 wp<Client> client(this);
537 disconnect();
538 mService->removeClient(client);
539}
540
541void MediaPlayerService::Client::disconnect()
542{
543 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
544 // grab local reference and clear main reference to prevent future
545 // access to object
546 sp<MediaPlayerBase> p;
547 {
548 Mutex::Autolock l(mLock);
549 p = mPlayer;
550 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700551 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 mPlayer.clear();
554
555 // clear the notification to prevent callbacks to dead client
556 // and reset the player. We assume the player will serialize
557 // access to itself if necessary.
558 if (p != 0) {
559 p->setNotifyCallback(0, 0);
560#if CALLBACK_ANTAGONIZER
561 LOGD("kill Antagonizer");
562 mAntagonizer->kill();
563#endif
564 p->reset();
565 }
566
567 IPCThreadState::self()->flushCommands();
568}
569
Andreas Huber0d596d42009-08-07 09:30:32 -0700570static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700571 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700572}
573
James Dong392ff3b2009-09-06 14:29:45 -0700574player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575{
576 char buf[20];
577 lseek(fd, offset, SEEK_SET);
578 read(fd, buf, sizeof(buf));
579 lseek(fd, offset, SEEK_SET);
580
581 long ident = *((long*)buf);
582
583 // Ogg vorbis?
584 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700585 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 // Some kind of MIDI?
588 EAS_DATA_HANDLE easdata;
589 if (EAS_Init(&easdata) == EAS_SUCCESS) {
590 EAS_FILE locator;
591 locator.path = NULL;
592 locator.fd = fd;
593 locator.offset = offset;
594 locator.length = length;
595 EAS_HANDLE eashandle;
596 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
597 EAS_CloseFile(easdata, eashandle);
598 EAS_Shutdown(easdata);
599 return SONIVOX_PLAYER;
600 }
601 EAS_Shutdown(easdata);
602 }
603
Andreas Huber0d596d42009-08-07 09:30:32 -0700604 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605}
606
James Dong392ff3b2009-09-06 14:29:45 -0700607player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700609 if (TestPlayerStub::canBeUsed(url)) {
610 return TEST_PLAYER;
611 }
612
Andreas Huber554d0ea2011-03-21 16:28:04 -0700613 if (!strncasecmp("http://", url, 7)
614 || !strncasecmp("https://", url, 8)) {
Andreas Huberd6c421f2011-02-16 09:05:38 -0800615 size_t len = strlen(url);
616 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
617 return NU_PLAYER;
618 }
Andreas Huber54e66492010-12-23 10:27:40 -0800619
Andreas Huberd6c421f2011-02-16 09:05:38 -0800620 if (strstr(url,"m3u8")) {
621 return NU_PLAYER;
Andreas Huber54e66492010-12-23 10:27:40 -0800622 }
623 }
624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 // use MidiFile for MIDI extensions
626 int lenURL = strlen(url);
627 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
628 int len = strlen(FILE_EXTS[i].extension);
629 int start = lenURL - len;
630 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900631 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700632 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 }
634 }
635 }
636
Andreas Huber0d596d42009-08-07 09:30:32 -0700637 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638}
639
640static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
641 notify_callback_f notifyFunc)
642{
643 sp<MediaPlayerBase> p;
644 switch (playerType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 case SONIVOX_PLAYER:
646 LOGV(" create MidiFile");
647 p = new MidiFile();
648 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700649 case STAGEFRIGHT_PLAYER:
650 LOGV(" create StagefrightPlayer");
651 p = new StagefrightPlayer;
652 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800653 case NU_PLAYER:
654 LOGV(" create NuPlayer");
655 p = new NuPlayerDriver;
656 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700657 case TEST_PLAYER:
658 LOGV("Create Test Player stub");
659 p = new TestPlayerStub();
660 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800661 default:
662 LOGE("Unknown player type: %d", playerType);
663 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 }
665 if (p != NULL) {
666 if (p->initCheck() == NO_ERROR) {
667 p->setNotifyCallback(cookie, notifyFunc);
668 } else {
669 p.clear();
670 }
671 }
672 if (p == NULL) {
673 LOGE("Failed to create player object");
674 }
675 return p;
676}
677
678sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
679{
680 // determine if we have the right player type
681 sp<MediaPlayerBase> p = mPlayer;
682 if ((p != NULL) && (p->playerType() != playerType)) {
683 LOGV("delete player");
684 p.clear();
685 }
686 if (p == NULL) {
687 p = android::createPlayer(playerType, this, notify);
688 }
Andreas Huber603d7392011-06-30 15:47:02 -0700689
690 p->setUID(mUID);
691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 return p;
693}
694
Andreas Huber25643002010-01-28 11:19:57 -0800695status_t MediaPlayerService::Client::setDataSource(
696 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697{
698 LOGV("setDataSource(%s)", url);
699 if (url == NULL)
700 return UNKNOWN_ERROR;
701
702 if (strncmp(url, "content://", 10) == 0) {
703 // get a filedescriptor for the content Uri and
704 // pass it to the setDataSource(fd) method
705
706 String16 url16(url);
707 int fd = android::openContentProviderFile(url16);
708 if (fd < 0)
709 {
710 LOGE("Couldn't open fd for %s", url);
711 return UNKNOWN_ERROR;
712 }
713 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
714 close(fd);
715 return mStatus;
716 } else {
717 player_type playerType = getPlayerType(url);
718 LOGV("player type = %d", playerType);
719
720 // create the right type of player
721 sp<MediaPlayerBase> p = createPlayer(playerType);
722 if (p == NULL) return NO_INIT;
723
724 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700725 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
727 }
728
729 // now set data source
730 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800731 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700732 if (mStatus == NO_ERROR) {
733 mPlayer = p;
734 } else {
735 LOGE(" error: %d", mStatus);
736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 return mStatus;
738 }
739}
740
741status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
742{
743 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
744 struct stat sb;
745 int ret = fstat(fd, &sb);
746 if (ret != 0) {
747 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
748 return UNKNOWN_ERROR;
749 }
750
751 LOGV("st_dev = %llu", sb.st_dev);
752 LOGV("st_mode = %u", sb.st_mode);
753 LOGV("st_uid = %lu", sb.st_uid);
754 LOGV("st_gid = %lu", sb.st_gid);
755 LOGV("st_size = %llu", sb.st_size);
756
757 if (offset >= sb.st_size) {
758 LOGE("offset error");
759 ::close(fd);
760 return UNKNOWN_ERROR;
761 }
762 if (offset + length > sb.st_size) {
763 length = sb.st_size - offset;
764 LOGV("calculated length = %lld", length);
765 }
766
767 player_type playerType = getPlayerType(fd, offset, length);
768 LOGV("player type = %d", playerType);
769
770 // create the right type of player
771 sp<MediaPlayerBase> p = createPlayer(playerType);
772 if (p == NULL) return NO_INIT;
773
774 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700775 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
777 }
778
779 // now set data source
780 mStatus = p->setDataSource(fd, offset, length);
781 if (mStatus == NO_ERROR) mPlayer = p;
782 return mStatus;
783}
784
Andreas Huber52b52cd2010-11-23 11:41:34 -0800785status_t MediaPlayerService::Client::setDataSource(
786 const sp<IStreamSource> &source) {
787 // create the right type of player
Andreas Hubera1587462010-12-15 15:17:42 -0800788 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Huber52b52cd2010-11-23 11:41:34 -0800789
790 if (p == NULL) {
791 return NO_INIT;
792 }
793
794 if (!p->hardwareOutput()) {
795 mAudioOutput = new AudioOutput(mAudioSessionId);
796 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
797 }
798
799 // now set data source
800 mStatus = p->setDataSource(source);
801
802 if (mStatus == OK) {
803 mPlayer = p;
804 }
805
806 return mStatus;
807}
808
Andreas Hubere3c01832010-08-16 08:49:37 -0700809status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810{
811 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
812 sp<MediaPlayerBase> p = getPlayer();
813 if (p == 0) return UNKNOWN_ERROR;
814 return p->setVideoSurface(surface);
815}
816
Glenn Kastencc562a32011-02-08 17:26:17 -0800817status_t MediaPlayerService::Client::setVideoSurfaceTexture(
818 const sp<ISurfaceTexture>& surfaceTexture)
819{
820 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
821 sp<MediaPlayerBase> p = getPlayer();
822 if (p == 0) return UNKNOWN_ERROR;
823 return p->setVideoSurfaceTexture(surfaceTexture);
824}
825
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700826status_t MediaPlayerService::Client::invoke(const Parcel& request,
827 Parcel *reply)
828{
829 sp<MediaPlayerBase> p = getPlayer();
830 if (p == NULL) return UNKNOWN_ERROR;
831 return p->invoke(request, reply);
832}
833
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700834// This call doesn't need to access the native player.
835status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
836{
837 status_t status;
nikobc726922009-07-20 15:07:26 -0700838 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700839
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700840 if (unmarshallFilter(filter, &allow, &status) &&
841 unmarshallFilter(filter, &drop, &status)) {
842 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700843
844 mMetadataAllow = allow;
845 mMetadataDrop = drop;
846 }
847 return status;
848}
849
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700850status_t MediaPlayerService::Client::getMetadata(
851 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700852{
nikobc726922009-07-20 15:07:26 -0700853 sp<MediaPlayerBase> player = getPlayer();
854 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700855
niko89948372009-07-16 16:39:53 -0700856 status_t status;
857 // Placeholder for the return code, updated by the caller.
858 reply->writeInt32(-1);
859
nikobc726922009-07-20 15:07:26 -0700860 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700861
862 // We don't block notifications while we fetch the data. We clear
863 // mMetadataUpdated first so we don't lose notifications happening
864 // during the rest of this call.
865 {
866 Mutex::Autolock lock(mLock);
867 if (update_only) {
niko89948372009-07-16 16:39:53 -0700868 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700869 }
870 mMetadataUpdated.clear();
871 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700872
nikobc726922009-07-20 15:07:26 -0700873 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700874
nikobc726922009-07-20 15:07:26 -0700875 metadata.appendHeader();
876 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700877
878 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700879 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700880 LOGE("getMetadata failed %d", status);
881 return status;
882 }
883
884 // FIXME: Implement filtering on the result. Not critical since
885 // filtering takes place on the update notifications already. This
886 // would be when all the metadata are fetch and a filter is set.
887
niko89948372009-07-16 16:39:53 -0700888 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700889 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700890 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700891}
892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893status_t MediaPlayerService::Client::prepareAsync()
894{
895 LOGV("[%d] prepareAsync", mConnId);
896 sp<MediaPlayerBase> p = getPlayer();
897 if (p == 0) return UNKNOWN_ERROR;
898 status_t ret = p->prepareAsync();
899#if CALLBACK_ANTAGONIZER
900 LOGD("start Antagonizer");
901 if (ret == NO_ERROR) mAntagonizer->start();
902#endif
903 return ret;
904}
905
906status_t MediaPlayerService::Client::start()
907{
908 LOGV("[%d] start", mConnId);
909 sp<MediaPlayerBase> p = getPlayer();
910 if (p == 0) return UNKNOWN_ERROR;
911 p->setLooping(mLoop);
912 return p->start();
913}
914
915status_t MediaPlayerService::Client::stop()
916{
917 LOGV("[%d] stop", mConnId);
918 sp<MediaPlayerBase> p = getPlayer();
919 if (p == 0) return UNKNOWN_ERROR;
920 return p->stop();
921}
922
923status_t MediaPlayerService::Client::pause()
924{
925 LOGV("[%d] pause", mConnId);
926 sp<MediaPlayerBase> p = getPlayer();
927 if (p == 0) return UNKNOWN_ERROR;
928 return p->pause();
929}
930
931status_t MediaPlayerService::Client::isPlaying(bool* state)
932{
933 *state = false;
934 sp<MediaPlayerBase> p = getPlayer();
935 if (p == 0) return UNKNOWN_ERROR;
936 *state = p->isPlaying();
937 LOGV("[%d] isPlaying: %d", mConnId, *state);
938 return NO_ERROR;
939}
940
941status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
942{
943 LOGV("getCurrentPosition");
944 sp<MediaPlayerBase> p = getPlayer();
945 if (p == 0) return UNKNOWN_ERROR;
946 status_t ret = p->getCurrentPosition(msec);
947 if (ret == NO_ERROR) {
948 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
949 } else {
950 LOGE("getCurrentPosition returned %d", ret);
951 }
952 return ret;
953}
954
955status_t MediaPlayerService::Client::getDuration(int *msec)
956{
957 LOGV("getDuration");
958 sp<MediaPlayerBase> p = getPlayer();
959 if (p == 0) return UNKNOWN_ERROR;
960 status_t ret = p->getDuration(msec);
961 if (ret == NO_ERROR) {
962 LOGV("[%d] getDuration = %d", mConnId, *msec);
963 } else {
964 LOGE("getDuration returned %d", ret);
965 }
966 return ret;
967}
968
969status_t MediaPlayerService::Client::seekTo(int msec)
970{
971 LOGV("[%d] seekTo(%d)", mConnId, msec);
972 sp<MediaPlayerBase> p = getPlayer();
973 if (p == 0) return UNKNOWN_ERROR;
974 return p->seekTo(msec);
975}
976
977status_t MediaPlayerService::Client::reset()
978{
979 LOGV("[%d] reset", mConnId);
980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == 0) return UNKNOWN_ERROR;
982 return p->reset();
983}
984
985status_t MediaPlayerService::Client::setAudioStreamType(int type)
986{
987 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
988 // TODO: for hardware output, call player instead
989 Mutex::Autolock l(mLock);
990 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
991 return NO_ERROR;
992}
993
994status_t MediaPlayerService::Client::setLooping(int loop)
995{
996 LOGV("[%d] setLooping(%d)", mConnId, loop);
997 mLoop = loop;
998 sp<MediaPlayerBase> p = getPlayer();
999 if (p != 0) return p->setLooping(loop);
1000 return NO_ERROR;
1001}
1002
1003status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1004{
1005 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1006 // TODO: for hardware output, call player instead
1007 Mutex::Autolock l(mLock);
1008 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1009 return NO_ERROR;
1010}
1011
Eric Laurent7070b362010-07-16 07:43:46 -07001012status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1013{
1014 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1015 Mutex::Autolock l(mLock);
1016 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1017 return NO_ERROR;
1018}
1019
1020status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1021{
1022 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1023 Mutex::Autolock l(mLock);
1024 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1025 return NO_ERROR;
1026}
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001027
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001028status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1029 LOGV("[%d] setParameter(%d)", mConnId, key);
1030 sp<MediaPlayerBase> p = getPlayer();
1031 if (p == 0) return UNKNOWN_ERROR;
1032 return p->setParameter(key, request);
1033}
1034
1035status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1036 LOGV("[%d] getParameter(%d)", mConnId, key);
1037 sp<MediaPlayerBase> p = getPlayer();
1038 if (p == 0) return UNKNOWN_ERROR;
1039 return p->getParameter(key, reply);
1040}
1041
Gloria Wang162ee492011-04-11 17:23:27 -07001042void MediaPlayerService::Client::notify(
1043 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044{
1045 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001046
1047 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001048 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001049 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001050
1051 if(client->shouldDropMetadata(metadata_type)) {
1052 return;
1053 }
1054
1055 // Update the list of metadata that have changed. getMetadata
1056 // also access mMetadataUpdated and clears it.
1057 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001060 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061}
1062
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001063
nikobc726922009-07-20 15:07:26 -07001064bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001065{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001066 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001067
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001068 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001069 return true;
1070 }
1071
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001072 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001073 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001074 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001075 return true;
1076 }
1077}
1078
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001079
nikobc726922009-07-20 15:07:26 -07001080void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001081 Mutex::Autolock lock(mLock);
1082 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1083 mMetadataUpdated.add(metadata_type);
1084 }
1085}
1086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087#if CALLBACK_ANTAGONIZER
1088const int Antagonizer::interval = 10000; // 10 msecs
1089
1090Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1091 mExit(false), mActive(false), mClient(client), mCb(cb)
1092{
1093 createThread(callbackThread, this);
1094}
1095
1096void Antagonizer::kill()
1097{
1098 Mutex::Autolock _l(mLock);
1099 mActive = false;
1100 mExit = true;
1101 mCondition.wait(mLock);
1102}
1103
1104int Antagonizer::callbackThread(void* user)
1105{
1106 LOGD("Antagonizer started");
1107 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1108 while (!p->mExit) {
1109 if (p->mActive) {
1110 LOGV("send event");
1111 p->mCb(p->mClient, 0, 0, 0);
1112 }
1113 usleep(interval);
1114 }
1115 Mutex::Autolock _l(p->mLock);
1116 p->mCondition.signal();
1117 LOGD("Antagonizer stopped");
1118 return 0;
1119}
1120#endif
1121
1122static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1123
1124sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1125{
1126 LOGV("decode(%s)", url);
1127 sp<MemoryBase> mem;
1128 sp<MediaPlayerBase> player;
1129
1130 // Protect our precious, precious DRMd ringtones by only allowing
1131 // decoding of http, but not filesystem paths or content Uris.
1132 // If the application wants to decode those, it should open a
1133 // filedescriptor for them and use that.
1134 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1135 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1136 return mem;
1137 }
1138
1139 player_type playerType = getPlayerType(url);
1140 LOGV("player type = %d", playerType);
1141
1142 // create the right type of player
1143 sp<AudioCache> cache = new AudioCache(url);
1144 player = android::createPlayer(playerType, cache.get(), cache->notify);
1145 if (player == NULL) goto Exit;
1146 if (player->hardwareOutput()) goto Exit;
1147
1148 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1149
1150 // set data source
1151 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1152
1153 LOGV("prepare");
1154 player->prepareAsync();
1155
1156 LOGV("wait for prepare");
1157 if (cache->wait() != NO_ERROR) goto Exit;
1158
1159 LOGV("start");
1160 player->start();
1161
1162 LOGV("wait for playback complete");
1163 if (cache->wait() != NO_ERROR) goto Exit;
1164
1165 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1166 *pSampleRate = cache->sampleRate();
1167 *pNumChannels = cache->channelCount();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001168 *pFormat = (int)cache->format();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1170
1171Exit:
1172 if (player != 0) player->reset();
1173 return mem;
1174}
1175
1176sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1177{
1178 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1179 sp<MemoryBase> mem;
1180 sp<MediaPlayerBase> player;
1181
1182 player_type playerType = getPlayerType(fd, offset, length);
1183 LOGV("player type = %d", playerType);
1184
1185 // create the right type of player
1186 sp<AudioCache> cache = new AudioCache("decode_fd");
1187 player = android::createPlayer(playerType, cache.get(), cache->notify);
1188 if (player == NULL) goto Exit;
1189 if (player->hardwareOutput()) goto Exit;
1190
1191 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1192
1193 // set data source
1194 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1195
1196 LOGV("prepare");
1197 player->prepareAsync();
1198
1199 LOGV("wait for prepare");
1200 if (cache->wait() != NO_ERROR) goto Exit;
1201
1202 LOGV("start");
1203 player->start();
1204
1205 LOGV("wait for playback complete");
1206 if (cache->wait() != NO_ERROR) goto Exit;
1207
1208 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1209 *pSampleRate = cache->sampleRate();
1210 *pNumChannels = cache->channelCount();
1211 *pFormat = cache->format();
1212 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1213
1214Exit:
1215 if (player != 0) player->reset();
1216 ::close(fd);
1217 return mem;
1218}
1219
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221#undef LOG_TAG
1222#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001223MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001224 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001225 mCallbackCookie(NULL),
1226 mSessionId(sessionId) {
1227 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001229 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 mLeftVolume = 1.0;
1231 mRightVolume = 1.0;
1232 mLatency = 0;
1233 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001234 mAuxEffectId = 0;
1235 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 setMinBufferCount();
1237}
1238
1239MediaPlayerService::AudioOutput::~AudioOutput()
1240{
1241 close();
1242}
1243
1244void MediaPlayerService::AudioOutput::setMinBufferCount()
1245{
1246 char value[PROPERTY_VALUE_MAX];
1247 if (property_get("ro.kernel.qemu", value, 0)) {
1248 mIsOnEmulator = true;
1249 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1250 }
1251}
1252
1253bool MediaPlayerService::AudioOutput::isOnEmulator()
1254{
1255 setMinBufferCount();
1256 return mIsOnEmulator;
1257}
1258
1259int MediaPlayerService::AudioOutput::getMinBufferCount()
1260{
1261 setMinBufferCount();
1262 return mMinBufferCount;
1263}
1264
1265ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1266{
1267 if (mTrack == 0) return NO_INIT;
1268 return mTrack->frameCount() * frameSize();
1269}
1270
1271ssize_t MediaPlayerService::AudioOutput::frameCount() const
1272{
1273 if (mTrack == 0) return NO_INIT;
1274 return mTrack->frameCount();
1275}
1276
1277ssize_t MediaPlayerService::AudioOutput::channelCount() const
1278{
1279 if (mTrack == 0) return NO_INIT;
1280 return mTrack->channelCount();
1281}
1282
1283ssize_t MediaPlayerService::AudioOutput::frameSize() const
1284{
1285 if (mTrack == 0) return NO_INIT;
1286 return mTrack->frameSize();
1287}
1288
1289uint32_t MediaPlayerService::AudioOutput::latency () const
1290{
1291 return mLatency;
1292}
1293
1294float MediaPlayerService::AudioOutput::msecsPerFrame() const
1295{
1296 return mMsecsPerFrame;
1297}
1298
Eric Laurent0986e792010-01-19 17:37:09 -08001299status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1300{
1301 if (mTrack == 0) return NO_INIT;
1302 return mTrack->getPosition(position);
1303}
1304
Andreas Hubere46b7be2009-07-14 16:56:47 -07001305status_t MediaPlayerService::AudioOutput::open(
1306 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1307 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001309 mCallback = cb;
1310 mCallbackCookie = cookie;
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 // Check argument "bufferCount" against the mininum buffer count
1313 if (bufferCount < mMinBufferCount) {
1314 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1315 bufferCount = mMinBufferCount;
1316
1317 }
Eric Laurent619346f2010-06-21 09:27:30 -07001318 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 if (mTrack) close();
1320 int afSampleRate;
1321 int afFrameCount;
1322 int frameCount;
1323
1324 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1325 return NO_INIT;
1326 }
1327 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1328 return NO_INIT;
1329 }
1330
1331 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001332
1333 AudioTrack *t;
1334 if (mCallback != NULL) {
1335 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001336 mStreamType,
1337 sampleRate,
1338 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001339 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001340 frameCount,
1341 0 /* flags */,
1342 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001343 this,
1344 0,
1345 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001346 } else {
1347 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001348 mStreamType,
1349 sampleRate,
1350 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001351 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001352 frameCount,
1353 0,
1354 NULL,
1355 NULL,
1356 0,
1357 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001358 }
1359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1361 LOGE("Unable to create audio track");
1362 delete t;
1363 return NO_INIT;
1364 }
1365
1366 LOGV("setVolume");
1367 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001370 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001372
1373 t->setAuxEffectSendLevel(mSendLevel);
1374 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375}
1376
1377void MediaPlayerService::AudioOutput::start()
1378{
1379 LOGV("start");
1380 if (mTrack) {
1381 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001382 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 mTrack->start();
1384 }
1385}
1386
Marco Nelissene274db12010-01-12 09:23:54 -08001387
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1390{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001391 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001394 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001395 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001396 return ret;
1397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 return NO_INIT;
1399}
1400
1401void MediaPlayerService::AudioOutput::stop()
1402{
1403 LOGV("stop");
1404 if (mTrack) mTrack->stop();
1405}
1406
1407void MediaPlayerService::AudioOutput::flush()
1408{
1409 LOGV("flush");
1410 if (mTrack) mTrack->flush();
1411}
1412
1413void MediaPlayerService::AudioOutput::pause()
1414{
1415 LOGV("pause");
1416 if (mTrack) mTrack->pause();
1417}
1418
1419void MediaPlayerService::AudioOutput::close()
1420{
1421 LOGV("close");
1422 delete mTrack;
1423 mTrack = 0;
1424}
1425
1426void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1427{
1428 LOGV("setVolume(%f, %f)", left, right);
1429 mLeftVolume = left;
1430 mRightVolume = right;
1431 if (mTrack) {
1432 mTrack->setVolume(left, right);
1433 }
1434}
1435
Eric Laurent7070b362010-07-16 07:43:46 -07001436status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1437{
1438 LOGV("setAuxEffectSendLevel(%f)", level);
1439 mSendLevel = level;
1440 if (mTrack) {
1441 return mTrack->setAuxEffectSendLevel(level);
1442 }
1443 return NO_ERROR;
1444}
1445
1446status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1447{
1448 LOGV("attachAuxEffect(%d)", effectId);
1449 mAuxEffectId = effectId;
1450 if (mTrack) {
1451 return mTrack->attachAuxEffect(effectId);
1452 }
1453 return NO_ERROR;
1454}
1455
Andreas Hubere46b7be2009-07-14 16:56:47 -07001456// static
1457void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastene46a86f2011-06-01 15:20:35 -07001458 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001459 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001460 if (event != AudioTrack::EVENT_MORE_DATA) {
1461 return;
1462 }
1463
1464 AudioOutput *me = (AudioOutput *)cookie;
1465 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1466
Andreas Huber6ed937e2010-02-09 16:59:18 -08001467 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001468 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001469
Andreas Huberc6e3b272011-04-04 11:43:40 -07001470 if (actualSize == 0 && buffer->size > 0) {
1471 // We've reached EOS but the audio track is not stopped yet,
1472 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001473
Andreas Huberc6e3b272011-04-04 11:43:40 -07001474 memset(buffer->raw, 0, buffer->size);
1475 actualSize = buffer->size;
1476 }
1477
1478 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001479}
1480
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001481int MediaPlayerService::AudioOutput::getSessionId()
1482{
1483 return mSessionId;
1484}
1485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486#undef LOG_TAG
1487#define LOG_TAG "AudioCache"
1488MediaPlayerService::AudioCache::AudioCache(const char* name) :
1489 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1490 mError(NO_ERROR), mCommandComplete(false)
1491{
1492 // create ashmem heap
1493 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1494}
1495
1496uint32_t MediaPlayerService::AudioCache::latency () const
1497{
1498 return 0;
1499}
1500
1501float MediaPlayerService::AudioCache::msecsPerFrame() const
1502{
1503 return mMsecsPerFrame;
1504}
1505
Eric Laurent0986e792010-01-19 17:37:09 -08001506status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1507{
1508 if (position == 0) return BAD_VALUE;
1509 *position = mSize;
1510 return NO_ERROR;
1511}
1512
Andreas Huber6ed937e2010-02-09 16:59:18 -08001513////////////////////////////////////////////////////////////////////////////////
1514
1515struct CallbackThread : public Thread {
1516 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1517 MediaPlayerBase::AudioSink::AudioCallback cb,
1518 void *cookie);
1519
1520protected:
1521 virtual ~CallbackThread();
1522
1523 virtual bool threadLoop();
1524
1525private:
1526 wp<MediaPlayerBase::AudioSink> mSink;
1527 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1528 void *mCookie;
1529 void *mBuffer;
1530 size_t mBufferSize;
1531
1532 CallbackThread(const CallbackThread &);
1533 CallbackThread &operator=(const CallbackThread &);
1534};
1535
1536CallbackThread::CallbackThread(
1537 const wp<MediaPlayerBase::AudioSink> &sink,
1538 MediaPlayerBase::AudioSink::AudioCallback cb,
1539 void *cookie)
1540 : mSink(sink),
1541 mCallback(cb),
1542 mCookie(cookie),
1543 mBuffer(NULL),
1544 mBufferSize(0) {
1545}
1546
1547CallbackThread::~CallbackThread() {
1548 if (mBuffer) {
1549 free(mBuffer);
1550 mBuffer = NULL;
1551 }
1552}
1553
1554bool CallbackThread::threadLoop() {
1555 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1556 if (sink == NULL) {
1557 return false;
1558 }
1559
1560 if (mBuffer == NULL) {
1561 mBufferSize = sink->bufferSize();
1562 mBuffer = malloc(mBufferSize);
1563 }
1564
1565 size_t actualSize =
1566 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1567
1568 if (actualSize > 0) {
1569 sink->write(mBuffer, actualSize);
1570 }
1571
1572 return true;
1573}
1574
1575////////////////////////////////////////////////////////////////////////////////
1576
Andreas Hubere46b7be2009-07-14 16:56:47 -07001577status_t MediaPlayerService::AudioCache::open(
1578 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1579 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580{
Dave Sparks14f89402009-12-09 20:20:26 -08001581 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001582 if (mHeap->getHeapID() < 0) {
1583 return NO_INIT;
1584 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 mSampleRate = sampleRate;
1587 mChannelCount = (uint16_t)channelCount;
1588 mFormat = (uint16_t)format;
1589 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001590
1591 if (cb != NULL) {
1592 mCallbackThread = new CallbackThread(this, cb, cookie);
1593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 return NO_ERROR;
1595}
1596
Andreas Huber6ed937e2010-02-09 16:59:18 -08001597void MediaPlayerService::AudioCache::start() {
1598 if (mCallbackThread != NULL) {
1599 mCallbackThread->run("AudioCache callback");
1600 }
1601}
1602
1603void MediaPlayerService::AudioCache::stop() {
1604 if (mCallbackThread != NULL) {
1605 mCallbackThread->requestExitAndWait();
1606 }
1607}
1608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1610{
1611 LOGV("write(%p, %u)", buffer, size);
1612 if ((buffer == 0) || (size == 0)) return size;
1613
1614 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1615 if (p == NULL) return NO_INIT;
1616 p += mSize;
1617 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1618 if (mSize + size > mHeap->getSize()) {
1619 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1620 size = mHeap->getSize() - mSize;
1621 }
1622 memcpy(p, buffer, size);
1623 mSize += size;
1624 return size;
1625}
1626
1627// call with lock held
1628status_t MediaPlayerService::AudioCache::wait()
1629{
1630 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001631 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 mSignal.wait(mLock);
1633 }
1634 mCommandComplete = false;
1635
1636 if (mError == NO_ERROR) {
1637 LOGV("wait - success");
1638 } else {
1639 LOGV("wait - error");
1640 }
1641 return mError;
1642}
1643
Gloria Wang162ee492011-04-11 17:23:27 -07001644void MediaPlayerService::AudioCache::notify(
1645 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646{
1647 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1648 AudioCache* p = static_cast<AudioCache*>(cookie);
1649
1650 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001651 switch (msg)
1652 {
1653 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 LOGE("Error %d, %d occurred", ext1, ext2);
1655 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001656 break;
1657 case MEDIA_PREPARED:
1658 LOGV("prepared");
1659 break;
1660 case MEDIA_PLAYBACK_COMPLETE:
1661 LOGV("playback complete");
1662 break;
1663 default:
1664 LOGV("ignored");
1665 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667
1668 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001669 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 p->mCommandComplete = true;
1671 p->mSignal.signal();
1672}
1673
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001674int MediaPlayerService::AudioCache::getSessionId()
1675{
1676 return 0;
1677}
1678
Gloria Wangd211f412011-02-19 18:37:57 -08001679void MediaPlayerService::addBatteryData(uint32_t params)
1680{
1681 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001682
1683 int32_t time = systemTime() / 1000000L;
1684
1685 // change audio output devices. This notification comes from AudioFlinger
1686 if ((params & kBatteryDataSpeakerOn)
1687 || (params & kBatteryDataOtherAudioDeviceOn)) {
1688
1689 int deviceOn[NUM_AUDIO_DEVICES];
1690 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1691 deviceOn[i] = 0;
1692 }
1693
1694 if ((params & kBatteryDataSpeakerOn)
1695 && (params & kBatteryDataOtherAudioDeviceOn)) {
1696 deviceOn[SPEAKER_AND_OTHER] = 1;
1697 } else if (params & kBatteryDataSpeakerOn) {
1698 deviceOn[SPEAKER] = 1;
1699 } else {
1700 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1701 }
1702
1703 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1704 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1705
1706 if (mBatteryAudio.refCount > 0) { // if playing audio
1707 if (!deviceOn[i]) {
1708 mBatteryAudio.lastTime[i] += time;
1709 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1710 mBatteryAudio.lastTime[i] = 0;
1711 } else {
1712 mBatteryAudio.lastTime[i] = 0 - time;
1713 }
1714 }
1715
1716 mBatteryAudio.deviceOn[i] = deviceOn[i];
1717 }
1718 }
1719 return;
1720 }
1721
1722 // an sudio stream is started
1723 if (params & kBatteryDataAudioFlingerStart) {
1724 // record the start time only if currently no other audio
1725 // is being played
1726 if (mBatteryAudio.refCount == 0) {
1727 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1728 if (mBatteryAudio.deviceOn[i]) {
1729 mBatteryAudio.lastTime[i] -= time;
1730 }
1731 }
1732 }
1733
1734 mBatteryAudio.refCount ++;
1735 return;
1736
1737 } else if (params & kBatteryDataAudioFlingerStop) {
1738 if (mBatteryAudio.refCount <= 0) {
1739 LOGW("Battery track warning: refCount is <= 0");
1740 return;
1741 }
1742
1743 // record the stop time only if currently this is the only
1744 // audio being played
1745 if (mBatteryAudio.refCount == 1) {
1746 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1747 if (mBatteryAudio.deviceOn[i]) {
1748 mBatteryAudio.lastTime[i] += time;
1749 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1750 mBatteryAudio.lastTime[i] = 0;
1751 }
1752 }
1753 }
1754
1755 mBatteryAudio.refCount --;
1756 return;
1757 }
1758
Gloria Wangd211f412011-02-19 18:37:57 -08001759 int uid = IPCThreadState::self()->getCallingUid();
1760 if (uid == AID_MEDIA) {
1761 return;
1762 }
1763 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001764
1765 if (index < 0) { // create a new entry for this UID
1766 BatteryUsageInfo info;
1767 info.audioTotalTime = 0;
1768 info.videoTotalTime = 0;
1769 info.audioLastTime = 0;
1770 info.videoLastTime = 0;
1771 info.refCount = 0;
1772
Gloria Wang9b3f1522011-02-24 14:51:45 -08001773 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1774 LOGE("Battery track error: no memory for new app");
1775 return;
1776 }
Gloria Wangd211f412011-02-19 18:37:57 -08001777 }
1778
1779 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1780
1781 if (params & kBatteryDataCodecStarted) {
1782 if (params & kBatteryDataTrackAudio) {
1783 info.audioLastTime -= time;
1784 info.refCount ++;
1785 }
1786 if (params & kBatteryDataTrackVideo) {
1787 info.videoLastTime -= time;
1788 info.refCount ++;
1789 }
1790 } else {
1791 if (info.refCount == 0) {
1792 LOGW("Battery track warning: refCount is already 0");
1793 return;
1794 } else if (info.refCount < 0) {
1795 LOGE("Battery track error: refCount < 0");
1796 mBatteryData.removeItem(uid);
1797 return;
1798 }
1799
1800 if (params & kBatteryDataTrackAudio) {
1801 info.audioLastTime += time;
1802 info.refCount --;
1803 }
1804 if (params & kBatteryDataTrackVideo) {
1805 info.videoLastTime += time;
1806 info.refCount --;
1807 }
1808
1809 // no stream is being played by this UID
1810 if (info.refCount == 0) {
1811 info.audioTotalTime += info.audioLastTime;
1812 info.audioLastTime = 0;
1813 info.videoTotalTime += info.videoLastTime;
1814 info.videoLastTime = 0;
1815 }
1816 }
1817}
1818
1819status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1820 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001821
1822 // audio output devices usage
1823 int32_t time = systemTime() / 1000000L; //in ms
1824 int32_t totalTime;
1825
1826 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1827 totalTime = mBatteryAudio.totalTime[i];
1828
1829 if (mBatteryAudio.deviceOn[i]
1830 && (mBatteryAudio.lastTime[i] != 0)) {
1831 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1832 totalTime += tmpTime;
1833 }
1834
1835 reply->writeInt32(totalTime);
1836 // reset the total time
1837 mBatteryAudio.totalTime[i] = 0;
1838 }
1839
1840 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001841 BatteryUsageInfo info;
1842 int size = mBatteryData.size();
1843
1844 reply->writeInt32(size);
1845 int i = 0;
1846
1847 while (i < size) {
1848 info = mBatteryData.valueAt(i);
1849
1850 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1851 reply->writeInt32(info.audioTotalTime);
1852 reply->writeInt32(info.videoTotalTime);
1853
1854 info.audioTotalTime = 0;
1855 info.videoTotalTime = 0;
1856
1857 // remove the UID entry where no stream is being played
1858 if (info.refCount <= 0) {
1859 mBatteryData.removeItemsAt(i);
1860 size --;
1861 i --;
1862 }
1863 i++;
1864 }
1865 return NO_ERROR;
1866}
nikobc726922009-07-20 15:07:26 -07001867} // namespace android