blob: a77dff1615d4983caabb97454e43c168a18d7d8d [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);
Eric Laurent619346f2010-06-21 09:27:30 -0700253 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
254 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
255 connId, pid, url, connId, audioSessionId);
Andreas Huber25643002010-01-28 11:19:57 -0800256 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 {
258 c.clear();
259 return c;
260 }
261 wp<Client> w = c;
262 Mutex::Autolock lock(mLock);
263 mClients.add(w);
264 return c;
265}
266
267sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Eric Laurent619346f2010-06-21 09:27:30 -0700268 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269{
270 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurent619346f2010-06-21 09:27:30 -0700271 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
272 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
273 connId, pid, fd, offset, length, audioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
275 c.clear();
276 } else {
277 wp<Client> w = c;
278 Mutex::Autolock lock(mLock);
279 mClients.add(w);
280 }
281 ::close(fd);
282 return c;
283}
284
Andreas Huber52b52cd2010-11-23 11:41:34 -0800285sp<IMediaPlayer> MediaPlayerService::create(
286 pid_t pid, const sp<IMediaPlayerClient> &client,
287 const sp<IStreamSource> &source, int audioSessionId) {
288 int32_t connId = android_atomic_inc(&mNextConnId);
289 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
290
291 LOGV("Create new client(%d) from pid %d, audioSessionId=%d",
292 connId, pid, audioSessionId);
293
294 if (OK != c->setDataSource(source)) {
295 c.clear();
296 } else {
297 wp<Client> w = c;
298 Mutex::Autolock lock(mLock);
299 mClients.add(w);
300 }
301
302 return c;
303}
304
Andreas Huber784202e2009-10-15 13:46:54 -0700305sp<IOMX> MediaPlayerService::getOMX() {
306 Mutex::Autolock autoLock(mLock);
307
308 if (mOMX.get() == NULL) {
309 mOMX = new OMX;
310 }
311
312 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700313}
314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
316{
317 const size_t SIZE = 256;
318 char buffer[SIZE];
319 String8 result;
320
321 result.append(" AudioCache\n");
322 if (mHeap != 0) {
323 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
324 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
325 result.append(buffer);
326 }
327 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
328 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
329 result.append(buffer);
330 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
331 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
332 result.append(buffer);
333 ::write(fd, result.string(), result.size());
334 return NO_ERROR;
335}
336
337status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
338{
339 const size_t SIZE = 256;
340 char buffer[SIZE];
341 String8 result;
342
343 result.append(" AudioOutput\n");
344 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
345 mStreamType, mLeftVolume, mRightVolume);
346 result.append(buffer);
347 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
348 mMsecsPerFrame, mLatency);
349 result.append(buffer);
Eric Laurent7070b362010-07-16 07:43:46 -0700350 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
351 mAuxEffectId, mSendLevel);
352 result.append(buffer);
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 ::write(fd, result.string(), result.size());
355 if (mTrack != 0) {
356 mTrack->dump(fd, args);
357 }
358 return NO_ERROR;
359}
360
361status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
362{
363 const size_t SIZE = 256;
364 char buffer[SIZE];
365 String8 result;
366 result.append(" Client\n");
367 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
368 mPid, mConnId, mStatus, mLoop?"true": "false");
369 result.append(buffer);
370 write(fd, result.string(), result.size());
Andreas Huberfddf5d92011-06-07 15:52:25 -0700371 if (mPlayer != NULL) {
372 mPlayer->dump(fd, args);
373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 if (mAudioOutput != 0) {
375 mAudioOutput->dump(fd, args);
376 }
377 write(fd, "\n", 1);
378 return NO_ERROR;
379}
380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
382{
383 const size_t SIZE = 256;
384 char buffer[SIZE];
385 String8 result;
386 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
387 snprintf(buffer, SIZE, "Permission Denial: "
388 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
389 IPCThreadState::self()->getCallingPid(),
390 IPCThreadState::self()->getCallingUid());
391 result.append(buffer);
392 } else {
393 Mutex::Autolock lock(mLock);
394 for (int i = 0, n = mClients.size(); i < n; ++i) {
395 sp<Client> c = mClients[i].promote();
396 if (c != 0) c->dump(fd, args);
397 }
James Dong929642e2010-07-08 11:16:11 -0700398 if (mMediaRecorderClients.size() == 0) {
399 result.append(" No media recorder client\n\n");
400 } else {
401 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
402 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
403 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
404 result.append(buffer);
405 write(fd, result.string(), result.size());
406 result = "\n";
407 c->dump(fd, args);
408 }
Gloria Wang608a2632009-10-29 15:46:37 -0700409 }
410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 result.append(" Files opened and/or mapped:\n");
Glenn Kasten6af763b2011-05-04 17:58:57 -0700412 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 FILE *f = fopen(buffer, "r");
414 if (f) {
415 while (!feof(f)) {
416 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700417 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700419 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 strstr(buffer, " /system/media/")) {
421 result.append(" ");
422 result.append(buffer);
423 }
424 }
425 fclose(f);
426 } else {
427 result.append("couldn't open ");
428 result.append(buffer);
429 result.append("\n");
430 }
431
Glenn Kasten6af763b2011-05-04 17:58:57 -0700432 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 DIR *d = opendir(buffer);
434 if (d) {
435 struct dirent *ent;
436 while((ent = readdir(d)) != NULL) {
437 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten6af763b2011-05-04 17:58:57 -0700438 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 struct stat s;
440 if (lstat(buffer, &s) == 0) {
441 if ((s.st_mode & S_IFMT) == S_IFLNK) {
442 char linkto[256];
443 int len = readlink(buffer, linkto, sizeof(linkto));
444 if(len > 0) {
445 if(len > 255) {
446 linkto[252] = '.';
447 linkto[253] = '.';
448 linkto[254] = '.';
449 linkto[255] = 0;
450 } else {
451 linkto[len] = 0;
452 }
Dave Sparks124a3462010-09-27 16:55:18 -0700453 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700455 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 strstr(linkto, "/system/media/") == linkto) {
457 result.append(" ");
458 result.append(buffer);
459 result.append(" -> ");
460 result.append(linkto);
461 result.append("\n");
462 }
463 }
464 } else {
465 result.append(" unexpected type for ");
466 result.append(buffer);
467 result.append("\n");
468 }
469 }
470 }
471 }
472 closedir(d);
473 } else {
474 result.append("couldn't open ");
475 result.append(buffer);
476 result.append("\n");
477 }
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 bool dumpMem = false;
480 for (size_t i = 0; i < args.size(); i++) {
481 if (args[i] == String16("-m")) {
482 dumpMem = true;
483 }
484 }
485 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700486 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 }
489 write(fd, result.string(), result.size());
490 return NO_ERROR;
491}
492
493void MediaPlayerService::removeClient(wp<Client> client)
494{
495 Mutex::Autolock lock(mLock);
496 mClients.remove(client);
497}
498
499MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
Eric Laurent619346f2010-06-21 09:27:30 -0700500 int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501{
502 LOGV("Client(%d) constructor", connId);
503 mPid = pid;
504 mConnId = connId;
505 mService = service;
506 mClient = client;
507 mLoop = false;
508 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700509 mAudioSessionId = audioSessionId;
510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511#if CALLBACK_ANTAGONIZER
512 LOGD("create Antagonizer");
513 mAntagonizer = new Antagonizer(notify, this);
514#endif
515}
516
517MediaPlayerService::Client::~Client()
518{
519 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
520 mAudioOutput.clear();
521 wp<Client> client(this);
522 disconnect();
523 mService->removeClient(client);
524}
525
526void MediaPlayerService::Client::disconnect()
527{
528 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
529 // grab local reference and clear main reference to prevent future
530 // access to object
531 sp<MediaPlayerBase> p;
532 {
533 Mutex::Autolock l(mLock);
534 p = mPlayer;
535 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700536 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 mPlayer.clear();
539
540 // clear the notification to prevent callbacks to dead client
541 // and reset the player. We assume the player will serialize
542 // access to itself if necessary.
543 if (p != 0) {
544 p->setNotifyCallback(0, 0);
545#if CALLBACK_ANTAGONIZER
546 LOGD("kill Antagonizer");
547 mAntagonizer->kill();
548#endif
549 p->reset();
550 }
551
552 IPCThreadState::self()->flushCommands();
553}
554
Andreas Huber0d596d42009-08-07 09:30:32 -0700555static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700556 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700557}
558
James Dong392ff3b2009-09-06 14:29:45 -0700559player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560{
561 char buf[20];
562 lseek(fd, offset, SEEK_SET);
563 read(fd, buf, sizeof(buf));
564 lseek(fd, offset, SEEK_SET);
565
566 long ident = *((long*)buf);
567
568 // Ogg vorbis?
569 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700570 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571
572 // Some kind of MIDI?
573 EAS_DATA_HANDLE easdata;
574 if (EAS_Init(&easdata) == EAS_SUCCESS) {
575 EAS_FILE locator;
576 locator.path = NULL;
577 locator.fd = fd;
578 locator.offset = offset;
579 locator.length = length;
580 EAS_HANDLE eashandle;
581 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
582 EAS_CloseFile(easdata, eashandle);
583 EAS_Shutdown(easdata);
584 return SONIVOX_PLAYER;
585 }
586 EAS_Shutdown(easdata);
587 }
588
Andreas Huber0d596d42009-08-07 09:30:32 -0700589 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590}
591
James Dong392ff3b2009-09-06 14:29:45 -0700592player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700594 if (TestPlayerStub::canBeUsed(url)) {
595 return TEST_PLAYER;
596 }
597
Andreas Huber554d0ea2011-03-21 16:28:04 -0700598 if (!strncasecmp("http://", url, 7)
599 || !strncasecmp("https://", url, 8)) {
Andreas Huberd6c421f2011-02-16 09:05:38 -0800600 size_t len = strlen(url);
601 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
602 return NU_PLAYER;
603 }
Andreas Huber54e66492010-12-23 10:27:40 -0800604
Andreas Huberd6c421f2011-02-16 09:05:38 -0800605 if (strstr(url,"m3u8")) {
606 return NU_PLAYER;
Andreas Huber54e66492010-12-23 10:27:40 -0800607 }
608 }
609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 // use MidiFile for MIDI extensions
611 int lenURL = strlen(url);
612 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
613 int len = strlen(FILE_EXTS[i].extension);
614 int start = lenURL - len;
615 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900616 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700617 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 }
619 }
620 }
621
Andreas Huber0d596d42009-08-07 09:30:32 -0700622 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623}
624
625static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
626 notify_callback_f notifyFunc)
627{
628 sp<MediaPlayerBase> p;
629 switch (playerType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 case SONIVOX_PLAYER:
631 LOGV(" create MidiFile");
632 p = new MidiFile();
633 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700634 case STAGEFRIGHT_PLAYER:
635 LOGV(" create StagefrightPlayer");
636 p = new StagefrightPlayer;
637 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800638 case NU_PLAYER:
639 LOGV(" create NuPlayer");
640 p = new NuPlayerDriver;
641 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700642 case TEST_PLAYER:
643 LOGV("Create Test Player stub");
644 p = new TestPlayerStub();
645 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800646 default:
647 LOGE("Unknown player type: %d", playerType);
648 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 }
650 if (p != NULL) {
651 if (p->initCheck() == NO_ERROR) {
652 p->setNotifyCallback(cookie, notifyFunc);
653 } else {
654 p.clear();
655 }
656 }
657 if (p == NULL) {
658 LOGE("Failed to create player object");
659 }
660 return p;
661}
662
663sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
664{
665 // determine if we have the right player type
666 sp<MediaPlayerBase> p = mPlayer;
667 if ((p != NULL) && (p->playerType() != playerType)) {
668 LOGV("delete player");
669 p.clear();
670 }
671 if (p == NULL) {
672 p = android::createPlayer(playerType, this, notify);
673 }
674 return p;
675}
676
Andreas Huber25643002010-01-28 11:19:57 -0800677status_t MediaPlayerService::Client::setDataSource(
678 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679{
680 LOGV("setDataSource(%s)", url);
681 if (url == NULL)
682 return UNKNOWN_ERROR;
683
684 if (strncmp(url, "content://", 10) == 0) {
685 // get a filedescriptor for the content Uri and
686 // pass it to the setDataSource(fd) method
687
688 String16 url16(url);
689 int fd = android::openContentProviderFile(url16);
690 if (fd < 0)
691 {
692 LOGE("Couldn't open fd for %s", url);
693 return UNKNOWN_ERROR;
694 }
695 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
696 close(fd);
697 return mStatus;
698 } else {
699 player_type playerType = getPlayerType(url);
700 LOGV("player type = %d", playerType);
701
702 // create the right type of player
703 sp<MediaPlayerBase> p = createPlayer(playerType);
704 if (p == NULL) return NO_INIT;
705
706 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700707 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
709 }
710
711 // now set data source
712 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800713 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700714 if (mStatus == NO_ERROR) {
715 mPlayer = p;
716 } else {
717 LOGE(" error: %d", mStatus);
718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 return mStatus;
720 }
721}
722
723status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
724{
725 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
726 struct stat sb;
727 int ret = fstat(fd, &sb);
728 if (ret != 0) {
729 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
730 return UNKNOWN_ERROR;
731 }
732
733 LOGV("st_dev = %llu", sb.st_dev);
734 LOGV("st_mode = %u", sb.st_mode);
735 LOGV("st_uid = %lu", sb.st_uid);
736 LOGV("st_gid = %lu", sb.st_gid);
737 LOGV("st_size = %llu", sb.st_size);
738
739 if (offset >= sb.st_size) {
740 LOGE("offset error");
741 ::close(fd);
742 return UNKNOWN_ERROR;
743 }
744 if (offset + length > sb.st_size) {
745 length = sb.st_size - offset;
746 LOGV("calculated length = %lld", length);
747 }
748
749 player_type playerType = getPlayerType(fd, offset, length);
750 LOGV("player type = %d", playerType);
751
752 // create the right type of player
753 sp<MediaPlayerBase> p = createPlayer(playerType);
754 if (p == NULL) return NO_INIT;
755
756 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700757 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
759 }
760
761 // now set data source
762 mStatus = p->setDataSource(fd, offset, length);
763 if (mStatus == NO_ERROR) mPlayer = p;
764 return mStatus;
765}
766
Andreas Huber52b52cd2010-11-23 11:41:34 -0800767status_t MediaPlayerService::Client::setDataSource(
768 const sp<IStreamSource> &source) {
769 // create the right type of player
Andreas Hubera1587462010-12-15 15:17:42 -0800770 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Huber52b52cd2010-11-23 11:41:34 -0800771
772 if (p == NULL) {
773 return NO_INIT;
774 }
775
776 if (!p->hardwareOutput()) {
777 mAudioOutput = new AudioOutput(mAudioSessionId);
778 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
779 }
780
781 // now set data source
782 mStatus = p->setDataSource(source);
783
784 if (mStatus == OK) {
785 mPlayer = p;
786 }
787
788 return mStatus;
789}
790
Andreas Hubere3c01832010-08-16 08:49:37 -0700791status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792{
793 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
794 sp<MediaPlayerBase> p = getPlayer();
795 if (p == 0) return UNKNOWN_ERROR;
796 return p->setVideoSurface(surface);
797}
798
Glenn Kastencc562a32011-02-08 17:26:17 -0800799status_t MediaPlayerService::Client::setVideoSurfaceTexture(
800 const sp<ISurfaceTexture>& surfaceTexture)
801{
802 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
803 sp<MediaPlayerBase> p = getPlayer();
804 if (p == 0) return UNKNOWN_ERROR;
805 return p->setVideoSurfaceTexture(surfaceTexture);
806}
807
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700808status_t MediaPlayerService::Client::invoke(const Parcel& request,
809 Parcel *reply)
810{
811 sp<MediaPlayerBase> p = getPlayer();
812 if (p == NULL) return UNKNOWN_ERROR;
813 return p->invoke(request, reply);
814}
815
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700816// This call doesn't need to access the native player.
817status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
818{
819 status_t status;
nikobc726922009-07-20 15:07:26 -0700820 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700821
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700822 if (unmarshallFilter(filter, &allow, &status) &&
823 unmarshallFilter(filter, &drop, &status)) {
824 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700825
826 mMetadataAllow = allow;
827 mMetadataDrop = drop;
828 }
829 return status;
830}
831
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700832status_t MediaPlayerService::Client::getMetadata(
833 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700834{
nikobc726922009-07-20 15:07:26 -0700835 sp<MediaPlayerBase> player = getPlayer();
836 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700837
niko89948372009-07-16 16:39:53 -0700838 status_t status;
839 // Placeholder for the return code, updated by the caller.
840 reply->writeInt32(-1);
841
nikobc726922009-07-20 15:07:26 -0700842 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700843
844 // We don't block notifications while we fetch the data. We clear
845 // mMetadataUpdated first so we don't lose notifications happening
846 // during the rest of this call.
847 {
848 Mutex::Autolock lock(mLock);
849 if (update_only) {
niko89948372009-07-16 16:39:53 -0700850 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700851 }
852 mMetadataUpdated.clear();
853 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700854
nikobc726922009-07-20 15:07:26 -0700855 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700856
nikobc726922009-07-20 15:07:26 -0700857 metadata.appendHeader();
858 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700859
860 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700861 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700862 LOGE("getMetadata failed %d", status);
863 return status;
864 }
865
866 // FIXME: Implement filtering on the result. Not critical since
867 // filtering takes place on the update notifications already. This
868 // would be when all the metadata are fetch and a filter is set.
869
niko89948372009-07-16 16:39:53 -0700870 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700871 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700872 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700873}
874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875status_t MediaPlayerService::Client::prepareAsync()
876{
877 LOGV("[%d] prepareAsync", mConnId);
878 sp<MediaPlayerBase> p = getPlayer();
879 if (p == 0) return UNKNOWN_ERROR;
880 status_t ret = p->prepareAsync();
881#if CALLBACK_ANTAGONIZER
882 LOGD("start Antagonizer");
883 if (ret == NO_ERROR) mAntagonizer->start();
884#endif
885 return ret;
886}
887
888status_t MediaPlayerService::Client::start()
889{
890 LOGV("[%d] start", mConnId);
891 sp<MediaPlayerBase> p = getPlayer();
892 if (p == 0) return UNKNOWN_ERROR;
893 p->setLooping(mLoop);
894 return p->start();
895}
896
897status_t MediaPlayerService::Client::stop()
898{
899 LOGV("[%d] stop", mConnId);
900 sp<MediaPlayerBase> p = getPlayer();
901 if (p == 0) return UNKNOWN_ERROR;
902 return p->stop();
903}
904
905status_t MediaPlayerService::Client::pause()
906{
907 LOGV("[%d] pause", mConnId);
908 sp<MediaPlayerBase> p = getPlayer();
909 if (p == 0) return UNKNOWN_ERROR;
910 return p->pause();
911}
912
913status_t MediaPlayerService::Client::isPlaying(bool* state)
914{
915 *state = false;
916 sp<MediaPlayerBase> p = getPlayer();
917 if (p == 0) return UNKNOWN_ERROR;
918 *state = p->isPlaying();
919 LOGV("[%d] isPlaying: %d", mConnId, *state);
920 return NO_ERROR;
921}
922
923status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
924{
925 LOGV("getCurrentPosition");
926 sp<MediaPlayerBase> p = getPlayer();
927 if (p == 0) return UNKNOWN_ERROR;
928 status_t ret = p->getCurrentPosition(msec);
929 if (ret == NO_ERROR) {
930 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
931 } else {
932 LOGE("getCurrentPosition returned %d", ret);
933 }
934 return ret;
935}
936
937status_t MediaPlayerService::Client::getDuration(int *msec)
938{
939 LOGV("getDuration");
940 sp<MediaPlayerBase> p = getPlayer();
941 if (p == 0) return UNKNOWN_ERROR;
942 status_t ret = p->getDuration(msec);
943 if (ret == NO_ERROR) {
944 LOGV("[%d] getDuration = %d", mConnId, *msec);
945 } else {
946 LOGE("getDuration returned %d", ret);
947 }
948 return ret;
949}
950
951status_t MediaPlayerService::Client::seekTo(int msec)
952{
953 LOGV("[%d] seekTo(%d)", mConnId, msec);
954 sp<MediaPlayerBase> p = getPlayer();
955 if (p == 0) return UNKNOWN_ERROR;
956 return p->seekTo(msec);
957}
958
959status_t MediaPlayerService::Client::reset()
960{
961 LOGV("[%d] reset", mConnId);
962 sp<MediaPlayerBase> p = getPlayer();
963 if (p == 0) return UNKNOWN_ERROR;
964 return p->reset();
965}
966
967status_t MediaPlayerService::Client::setAudioStreamType(int type)
968{
969 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
970 // TODO: for hardware output, call player instead
971 Mutex::Autolock l(mLock);
972 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
973 return NO_ERROR;
974}
975
976status_t MediaPlayerService::Client::setLooping(int loop)
977{
978 LOGV("[%d] setLooping(%d)", mConnId, loop);
979 mLoop = loop;
980 sp<MediaPlayerBase> p = getPlayer();
981 if (p != 0) return p->setLooping(loop);
982 return NO_ERROR;
983}
984
985status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
986{
987 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
988 // TODO: for hardware output, call player instead
989 Mutex::Autolock l(mLock);
990 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
991 return NO_ERROR;
992}
993
Eric Laurent7070b362010-07-16 07:43:46 -0700994status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
995{
996 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
997 Mutex::Autolock l(mLock);
998 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
999 return NO_ERROR;
1000}
1001
1002status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1003{
1004 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1005 Mutex::Autolock l(mLock);
1006 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1007 return NO_ERROR;
1008}
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001009
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001010status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1011 LOGV("[%d] setParameter(%d)", mConnId, key);
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 return p->setParameter(key, request);
1015}
1016
1017status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1018 LOGV("[%d] getParameter(%d)", mConnId, key);
1019 sp<MediaPlayerBase> p = getPlayer();
1020 if (p == 0) return UNKNOWN_ERROR;
1021 return p->getParameter(key, reply);
1022}
1023
Gloria Wang162ee492011-04-11 17:23:27 -07001024void MediaPlayerService::Client::notify(
1025 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026{
1027 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001028
1029 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001030 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001031 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001032
1033 if(client->shouldDropMetadata(metadata_type)) {
1034 return;
1035 }
1036
1037 // Update the list of metadata that have changed. getMetadata
1038 // also access mMetadataUpdated and clears it.
1039 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001042 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043}
1044
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001045
nikobc726922009-07-20 15:07:26 -07001046bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001047{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001048 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001049
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001050 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001051 return true;
1052 }
1053
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001054 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001055 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001056 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001057 return true;
1058 }
1059}
1060
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001061
nikobc726922009-07-20 15:07:26 -07001062void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001063 Mutex::Autolock lock(mLock);
1064 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1065 mMetadataUpdated.add(metadata_type);
1066 }
1067}
1068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069#if CALLBACK_ANTAGONIZER
1070const int Antagonizer::interval = 10000; // 10 msecs
1071
1072Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1073 mExit(false), mActive(false), mClient(client), mCb(cb)
1074{
1075 createThread(callbackThread, this);
1076}
1077
1078void Antagonizer::kill()
1079{
1080 Mutex::Autolock _l(mLock);
1081 mActive = false;
1082 mExit = true;
1083 mCondition.wait(mLock);
1084}
1085
1086int Antagonizer::callbackThread(void* user)
1087{
1088 LOGD("Antagonizer started");
1089 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1090 while (!p->mExit) {
1091 if (p->mActive) {
1092 LOGV("send event");
1093 p->mCb(p->mClient, 0, 0, 0);
1094 }
1095 usleep(interval);
1096 }
1097 Mutex::Autolock _l(p->mLock);
1098 p->mCondition.signal();
1099 LOGD("Antagonizer stopped");
1100 return 0;
1101}
1102#endif
1103
1104static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1105
1106sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1107{
1108 LOGV("decode(%s)", url);
1109 sp<MemoryBase> mem;
1110 sp<MediaPlayerBase> player;
1111
1112 // Protect our precious, precious DRMd ringtones by only allowing
1113 // decoding of http, but not filesystem paths or content Uris.
1114 // If the application wants to decode those, it should open a
1115 // filedescriptor for them and use that.
1116 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1117 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1118 return mem;
1119 }
1120
1121 player_type playerType = getPlayerType(url);
1122 LOGV("player type = %d", playerType);
1123
1124 // create the right type of player
1125 sp<AudioCache> cache = new AudioCache(url);
1126 player = android::createPlayer(playerType, cache.get(), cache->notify);
1127 if (player == NULL) goto Exit;
1128 if (player->hardwareOutput()) goto Exit;
1129
1130 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1131
1132 // set data source
1133 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1134
1135 LOGV("prepare");
1136 player->prepareAsync();
1137
1138 LOGV("wait for prepare");
1139 if (cache->wait() != NO_ERROR) goto Exit;
1140
1141 LOGV("start");
1142 player->start();
1143
1144 LOGV("wait for playback complete");
1145 if (cache->wait() != NO_ERROR) goto Exit;
1146
1147 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1148 *pSampleRate = cache->sampleRate();
1149 *pNumChannels = cache->channelCount();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001150 *pFormat = (int)cache->format();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1152
1153Exit:
1154 if (player != 0) player->reset();
1155 return mem;
1156}
1157
1158sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1159{
1160 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1161 sp<MemoryBase> mem;
1162 sp<MediaPlayerBase> player;
1163
1164 player_type playerType = getPlayerType(fd, offset, length);
1165 LOGV("player type = %d", playerType);
1166
1167 // create the right type of player
1168 sp<AudioCache> cache = new AudioCache("decode_fd");
1169 player = android::createPlayer(playerType, cache.get(), cache->notify);
1170 if (player == NULL) goto Exit;
1171 if (player->hardwareOutput()) goto Exit;
1172
1173 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1174
1175 // set data source
1176 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1177
1178 LOGV("prepare");
1179 player->prepareAsync();
1180
1181 LOGV("wait for prepare");
1182 if (cache->wait() != NO_ERROR) goto Exit;
1183
1184 LOGV("start");
1185 player->start();
1186
1187 LOGV("wait for playback complete");
1188 if (cache->wait() != NO_ERROR) goto Exit;
1189
1190 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1191 *pSampleRate = cache->sampleRate();
1192 *pNumChannels = cache->channelCount();
1193 *pFormat = cache->format();
1194 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1195
1196Exit:
1197 if (player != 0) player->reset();
1198 ::close(fd);
1199 return mem;
1200}
1201
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203#undef LOG_TAG
1204#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001205MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001206 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001207 mCallbackCookie(NULL),
1208 mSessionId(sessionId) {
1209 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001211 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 mLeftVolume = 1.0;
1213 mRightVolume = 1.0;
1214 mLatency = 0;
1215 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001216 mAuxEffectId = 0;
1217 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 setMinBufferCount();
1219}
1220
1221MediaPlayerService::AudioOutput::~AudioOutput()
1222{
1223 close();
1224}
1225
1226void MediaPlayerService::AudioOutput::setMinBufferCount()
1227{
1228 char value[PROPERTY_VALUE_MAX];
1229 if (property_get("ro.kernel.qemu", value, 0)) {
1230 mIsOnEmulator = true;
1231 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1232 }
1233}
1234
1235bool MediaPlayerService::AudioOutput::isOnEmulator()
1236{
1237 setMinBufferCount();
1238 return mIsOnEmulator;
1239}
1240
1241int MediaPlayerService::AudioOutput::getMinBufferCount()
1242{
1243 setMinBufferCount();
1244 return mMinBufferCount;
1245}
1246
1247ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1248{
1249 if (mTrack == 0) return NO_INIT;
1250 return mTrack->frameCount() * frameSize();
1251}
1252
1253ssize_t MediaPlayerService::AudioOutput::frameCount() const
1254{
1255 if (mTrack == 0) return NO_INIT;
1256 return mTrack->frameCount();
1257}
1258
1259ssize_t MediaPlayerService::AudioOutput::channelCount() const
1260{
1261 if (mTrack == 0) return NO_INIT;
1262 return mTrack->channelCount();
1263}
1264
1265ssize_t MediaPlayerService::AudioOutput::frameSize() const
1266{
1267 if (mTrack == 0) return NO_INIT;
1268 return mTrack->frameSize();
1269}
1270
1271uint32_t MediaPlayerService::AudioOutput::latency () const
1272{
1273 return mLatency;
1274}
1275
1276float MediaPlayerService::AudioOutput::msecsPerFrame() const
1277{
1278 return mMsecsPerFrame;
1279}
1280
Eric Laurent0986e792010-01-19 17:37:09 -08001281status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1282{
1283 if (mTrack == 0) return NO_INIT;
1284 return mTrack->getPosition(position);
1285}
1286
Andreas Hubere46b7be2009-07-14 16:56:47 -07001287status_t MediaPlayerService::AudioOutput::open(
1288 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1289 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001291 mCallback = cb;
1292 mCallbackCookie = cookie;
1293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 // Check argument "bufferCount" against the mininum buffer count
1295 if (bufferCount < mMinBufferCount) {
1296 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1297 bufferCount = mMinBufferCount;
1298
1299 }
Eric Laurent619346f2010-06-21 09:27:30 -07001300 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 if (mTrack) close();
1302 int afSampleRate;
1303 int afFrameCount;
1304 int frameCount;
1305
1306 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1307 return NO_INIT;
1308 }
1309 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1310 return NO_INIT;
1311 }
1312
1313 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001314
1315 AudioTrack *t;
1316 if (mCallback != NULL) {
1317 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001318 mStreamType,
1319 sampleRate,
1320 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001321 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001322 frameCount,
1323 0 /* flags */,
1324 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001325 this,
1326 0,
1327 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001328 } else {
1329 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001330 mStreamType,
1331 sampleRate,
1332 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001333 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001334 frameCount,
1335 0,
1336 NULL,
1337 NULL,
1338 0,
1339 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001340 }
1341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1343 LOGE("Unable to create audio track");
1344 delete t;
1345 return NO_INIT;
1346 }
1347
1348 LOGV("setVolume");
1349 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001352 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001354
1355 t->setAuxEffectSendLevel(mSendLevel);
1356 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357}
1358
1359void MediaPlayerService::AudioOutput::start()
1360{
1361 LOGV("start");
1362 if (mTrack) {
1363 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001364 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 mTrack->start();
1366 }
1367}
1368
Marco Nelissene274db12010-01-12 09:23:54 -08001369
1370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1372{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001373 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001376 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001377 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001378 return ret;
1379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 return NO_INIT;
1381}
1382
1383void MediaPlayerService::AudioOutput::stop()
1384{
1385 LOGV("stop");
1386 if (mTrack) mTrack->stop();
1387}
1388
1389void MediaPlayerService::AudioOutput::flush()
1390{
1391 LOGV("flush");
1392 if (mTrack) mTrack->flush();
1393}
1394
1395void MediaPlayerService::AudioOutput::pause()
1396{
1397 LOGV("pause");
1398 if (mTrack) mTrack->pause();
1399}
1400
1401void MediaPlayerService::AudioOutput::close()
1402{
1403 LOGV("close");
1404 delete mTrack;
1405 mTrack = 0;
1406}
1407
1408void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1409{
1410 LOGV("setVolume(%f, %f)", left, right);
1411 mLeftVolume = left;
1412 mRightVolume = right;
1413 if (mTrack) {
1414 mTrack->setVolume(left, right);
1415 }
1416}
1417
Eric Laurent7070b362010-07-16 07:43:46 -07001418status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1419{
1420 LOGV("setAuxEffectSendLevel(%f)", level);
1421 mSendLevel = level;
1422 if (mTrack) {
1423 return mTrack->setAuxEffectSendLevel(level);
1424 }
1425 return NO_ERROR;
1426}
1427
1428status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1429{
1430 LOGV("attachAuxEffect(%d)", effectId);
1431 mAuxEffectId = effectId;
1432 if (mTrack) {
1433 return mTrack->attachAuxEffect(effectId);
1434 }
1435 return NO_ERROR;
1436}
1437
Andreas Hubere46b7be2009-07-14 16:56:47 -07001438// static
1439void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastene46a86f2011-06-01 15:20:35 -07001440 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001441 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001442 if (event != AudioTrack::EVENT_MORE_DATA) {
1443 return;
1444 }
1445
1446 AudioOutput *me = (AudioOutput *)cookie;
1447 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1448
Andreas Huber6ed937e2010-02-09 16:59:18 -08001449 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001450 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001451
Andreas Huberc6e3b272011-04-04 11:43:40 -07001452 if (actualSize == 0 && buffer->size > 0) {
1453 // We've reached EOS but the audio track is not stopped yet,
1454 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001455
Andreas Huberc6e3b272011-04-04 11:43:40 -07001456 memset(buffer->raw, 0, buffer->size);
1457 actualSize = buffer->size;
1458 }
1459
1460 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001461}
1462
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001463int MediaPlayerService::AudioOutput::getSessionId()
1464{
1465 return mSessionId;
1466}
1467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468#undef LOG_TAG
1469#define LOG_TAG "AudioCache"
1470MediaPlayerService::AudioCache::AudioCache(const char* name) :
1471 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1472 mError(NO_ERROR), mCommandComplete(false)
1473{
1474 // create ashmem heap
1475 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1476}
1477
1478uint32_t MediaPlayerService::AudioCache::latency () const
1479{
1480 return 0;
1481}
1482
1483float MediaPlayerService::AudioCache::msecsPerFrame() const
1484{
1485 return mMsecsPerFrame;
1486}
1487
Eric Laurent0986e792010-01-19 17:37:09 -08001488status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1489{
1490 if (position == 0) return BAD_VALUE;
1491 *position = mSize;
1492 return NO_ERROR;
1493}
1494
Andreas Huber6ed937e2010-02-09 16:59:18 -08001495////////////////////////////////////////////////////////////////////////////////
1496
1497struct CallbackThread : public Thread {
1498 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1499 MediaPlayerBase::AudioSink::AudioCallback cb,
1500 void *cookie);
1501
1502protected:
1503 virtual ~CallbackThread();
1504
1505 virtual bool threadLoop();
1506
1507private:
1508 wp<MediaPlayerBase::AudioSink> mSink;
1509 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1510 void *mCookie;
1511 void *mBuffer;
1512 size_t mBufferSize;
1513
1514 CallbackThread(const CallbackThread &);
1515 CallbackThread &operator=(const CallbackThread &);
1516};
1517
1518CallbackThread::CallbackThread(
1519 const wp<MediaPlayerBase::AudioSink> &sink,
1520 MediaPlayerBase::AudioSink::AudioCallback cb,
1521 void *cookie)
1522 : mSink(sink),
1523 mCallback(cb),
1524 mCookie(cookie),
1525 mBuffer(NULL),
1526 mBufferSize(0) {
1527}
1528
1529CallbackThread::~CallbackThread() {
1530 if (mBuffer) {
1531 free(mBuffer);
1532 mBuffer = NULL;
1533 }
1534}
1535
1536bool CallbackThread::threadLoop() {
1537 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1538 if (sink == NULL) {
1539 return false;
1540 }
1541
1542 if (mBuffer == NULL) {
1543 mBufferSize = sink->bufferSize();
1544 mBuffer = malloc(mBufferSize);
1545 }
1546
1547 size_t actualSize =
1548 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1549
1550 if (actualSize > 0) {
1551 sink->write(mBuffer, actualSize);
1552 }
1553
1554 return true;
1555}
1556
1557////////////////////////////////////////////////////////////////////////////////
1558
Andreas Hubere46b7be2009-07-14 16:56:47 -07001559status_t MediaPlayerService::AudioCache::open(
1560 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1561 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562{
Dave Sparks14f89402009-12-09 20:20:26 -08001563 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001564 if (mHeap->getHeapID() < 0) {
1565 return NO_INIT;
1566 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 mSampleRate = sampleRate;
1569 mChannelCount = (uint16_t)channelCount;
1570 mFormat = (uint16_t)format;
1571 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001572
1573 if (cb != NULL) {
1574 mCallbackThread = new CallbackThread(this, cb, cookie);
1575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 return NO_ERROR;
1577}
1578
Andreas Huber6ed937e2010-02-09 16:59:18 -08001579void MediaPlayerService::AudioCache::start() {
1580 if (mCallbackThread != NULL) {
1581 mCallbackThread->run("AudioCache callback");
1582 }
1583}
1584
1585void MediaPlayerService::AudioCache::stop() {
1586 if (mCallbackThread != NULL) {
1587 mCallbackThread->requestExitAndWait();
1588 }
1589}
1590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1592{
1593 LOGV("write(%p, %u)", buffer, size);
1594 if ((buffer == 0) || (size == 0)) return size;
1595
1596 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1597 if (p == NULL) return NO_INIT;
1598 p += mSize;
1599 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1600 if (mSize + size > mHeap->getSize()) {
1601 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1602 size = mHeap->getSize() - mSize;
1603 }
1604 memcpy(p, buffer, size);
1605 mSize += size;
1606 return size;
1607}
1608
1609// call with lock held
1610status_t MediaPlayerService::AudioCache::wait()
1611{
1612 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001613 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 mSignal.wait(mLock);
1615 }
1616 mCommandComplete = false;
1617
1618 if (mError == NO_ERROR) {
1619 LOGV("wait - success");
1620 } else {
1621 LOGV("wait - error");
1622 }
1623 return mError;
1624}
1625
Gloria Wang162ee492011-04-11 17:23:27 -07001626void MediaPlayerService::AudioCache::notify(
1627 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628{
1629 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1630 AudioCache* p = static_cast<AudioCache*>(cookie);
1631
1632 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001633 switch (msg)
1634 {
1635 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 LOGE("Error %d, %d occurred", ext1, ext2);
1637 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001638 break;
1639 case MEDIA_PREPARED:
1640 LOGV("prepared");
1641 break;
1642 case MEDIA_PLAYBACK_COMPLETE:
1643 LOGV("playback complete");
1644 break;
1645 default:
1646 LOGV("ignored");
1647 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649
1650 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001651 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 p->mCommandComplete = true;
1653 p->mSignal.signal();
1654}
1655
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001656int MediaPlayerService::AudioCache::getSessionId()
1657{
1658 return 0;
1659}
1660
Gloria Wangd211f412011-02-19 18:37:57 -08001661void MediaPlayerService::addBatteryData(uint32_t params)
1662{
1663 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001664
1665 int32_t time = systemTime() / 1000000L;
1666
1667 // change audio output devices. This notification comes from AudioFlinger
1668 if ((params & kBatteryDataSpeakerOn)
1669 || (params & kBatteryDataOtherAudioDeviceOn)) {
1670
1671 int deviceOn[NUM_AUDIO_DEVICES];
1672 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1673 deviceOn[i] = 0;
1674 }
1675
1676 if ((params & kBatteryDataSpeakerOn)
1677 && (params & kBatteryDataOtherAudioDeviceOn)) {
1678 deviceOn[SPEAKER_AND_OTHER] = 1;
1679 } else if (params & kBatteryDataSpeakerOn) {
1680 deviceOn[SPEAKER] = 1;
1681 } else {
1682 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1683 }
1684
1685 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1686 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1687
1688 if (mBatteryAudio.refCount > 0) { // if playing audio
1689 if (!deviceOn[i]) {
1690 mBatteryAudio.lastTime[i] += time;
1691 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1692 mBatteryAudio.lastTime[i] = 0;
1693 } else {
1694 mBatteryAudio.lastTime[i] = 0 - time;
1695 }
1696 }
1697
1698 mBatteryAudio.deviceOn[i] = deviceOn[i];
1699 }
1700 }
1701 return;
1702 }
1703
1704 // an sudio stream is started
1705 if (params & kBatteryDataAudioFlingerStart) {
1706 // record the start time only if currently no other audio
1707 // is being played
1708 if (mBatteryAudio.refCount == 0) {
1709 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1710 if (mBatteryAudio.deviceOn[i]) {
1711 mBatteryAudio.lastTime[i] -= time;
1712 }
1713 }
1714 }
1715
1716 mBatteryAudio.refCount ++;
1717 return;
1718
1719 } else if (params & kBatteryDataAudioFlingerStop) {
1720 if (mBatteryAudio.refCount <= 0) {
1721 LOGW("Battery track warning: refCount is <= 0");
1722 return;
1723 }
1724
1725 // record the stop time only if currently this is the only
1726 // audio being played
1727 if (mBatteryAudio.refCount == 1) {
1728 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1729 if (mBatteryAudio.deviceOn[i]) {
1730 mBatteryAudio.lastTime[i] += time;
1731 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1732 mBatteryAudio.lastTime[i] = 0;
1733 }
1734 }
1735 }
1736
1737 mBatteryAudio.refCount --;
1738 return;
1739 }
1740
Gloria Wangd211f412011-02-19 18:37:57 -08001741 int uid = IPCThreadState::self()->getCallingUid();
1742 if (uid == AID_MEDIA) {
1743 return;
1744 }
1745 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001746
1747 if (index < 0) { // create a new entry for this UID
1748 BatteryUsageInfo info;
1749 info.audioTotalTime = 0;
1750 info.videoTotalTime = 0;
1751 info.audioLastTime = 0;
1752 info.videoLastTime = 0;
1753 info.refCount = 0;
1754
Gloria Wang9b3f1522011-02-24 14:51:45 -08001755 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1756 LOGE("Battery track error: no memory for new app");
1757 return;
1758 }
Gloria Wangd211f412011-02-19 18:37:57 -08001759 }
1760
1761 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1762
1763 if (params & kBatteryDataCodecStarted) {
1764 if (params & kBatteryDataTrackAudio) {
1765 info.audioLastTime -= time;
1766 info.refCount ++;
1767 }
1768 if (params & kBatteryDataTrackVideo) {
1769 info.videoLastTime -= time;
1770 info.refCount ++;
1771 }
1772 } else {
1773 if (info.refCount == 0) {
1774 LOGW("Battery track warning: refCount is already 0");
1775 return;
1776 } else if (info.refCount < 0) {
1777 LOGE("Battery track error: refCount < 0");
1778 mBatteryData.removeItem(uid);
1779 return;
1780 }
1781
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
1791 // no stream is being played by this UID
1792 if (info.refCount == 0) {
1793 info.audioTotalTime += info.audioLastTime;
1794 info.audioLastTime = 0;
1795 info.videoTotalTime += info.videoLastTime;
1796 info.videoLastTime = 0;
1797 }
1798 }
1799}
1800
1801status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1802 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001803
1804 // audio output devices usage
1805 int32_t time = systemTime() / 1000000L; //in ms
1806 int32_t totalTime;
1807
1808 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1809 totalTime = mBatteryAudio.totalTime[i];
1810
1811 if (mBatteryAudio.deviceOn[i]
1812 && (mBatteryAudio.lastTime[i] != 0)) {
1813 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1814 totalTime += tmpTime;
1815 }
1816
1817 reply->writeInt32(totalTime);
1818 // reset the total time
1819 mBatteryAudio.totalTime[i] = 0;
1820 }
1821
1822 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001823 BatteryUsageInfo info;
1824 int size = mBatteryData.size();
1825
1826 reply->writeInt32(size);
1827 int i = 0;
1828
1829 while (i < size) {
1830 info = mBatteryData.valueAt(i);
1831
1832 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1833 reply->writeInt32(info.audioTotalTime);
1834 reply->writeInt32(info.videoTotalTime);
1835
1836 info.audioTotalTime = 0;
1837 info.videoTotalTime = 0;
1838
1839 // remove the UID entry where no stream is being played
1840 if (info.refCount <= 0) {
1841 mBatteryData.removeItemsAt(i);
1842 size --;
1843 i --;
1844 }
1845 i++;
1846 }
1847 return NO_ERROR;
1848}
nikobc726922009-07-20 15:07:26 -07001849} // namespace android