blob: 2051b3ba49febb1e30c4df945a27b09282345800 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
37#include <android_runtime/ActivityManager.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070038
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070043#include <utils/Errors.h> // for status_t
44#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070045#include <utils/SystemClock.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047#include <cutils/properties.h>
48
49#include <media/MediaPlayerInterface.h>
50#include <media/mediarecorder.h>
51#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070052#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080053#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070054#include <media/MemoryLeakTrackUtil.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055
Dima Zavin64760242011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070057
Gloria Wang7cf180c2011-02-19 18:37:57 -080058#include <private/android_filesystem_config.h>
59
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080060#include "MediaRecorderClient.h"
61#include "MediaPlayerService.h"
62#include "MetadataRetrieverClient.h"
63
64#include "MidiFile.h"
Nicolas Catania14d27472009-07-13 14:37:49 -070065#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070066#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080067#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070068
Andreas Huber20111aa2009-07-14 16:56:47 -070069#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070070
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070071namespace {
nikoa64c8c72009-07-20 15:07:26 -070072using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-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 Cataniaa7e0e8b2009-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
nikoa64c8c72009-07-20 15:07:26 -070082// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070083
Nicolas Cataniaa7e0e8b2009-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,
nikoa64c8c72009-07-20 15:07:26 -0700107 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700108 status_t *status)
109{
Nicolas Catania48290382009-07-10 13:53:06 -0700110 int32_t val;
111 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-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 Catania48290382009-07-10 13:53:06 -0700118 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700119 {
Nicolas Catania48290382009-07-10 13:53:06 -0700120 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700121 *status = BAD_VALUE;
122 return false;
123 }
124
Nicolas Catania48290382009-07-10 13:53:06 -0700125 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700126
127 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700128 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129
nikoa64c8c72009-07-20 15:07:26 -0700130 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131
Nicolas Catania48290382009-07-10 13:53:06 -0700132
133 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134 {
Nicolas Catania48290382009-07-10 13:53:06 -0700135 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 *status = NOT_ENOUGH_DATA;
137 return false;
138 }
139
nikoa64c8c72009-07-20 15:07:26 -0700140 const Metadata::Type *data =
141 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142
Nicolas Catania48290382009-07-10 13:53:06 -0700143 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-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 Catania48290382009-07-10 13:53:06 -0700153 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 {
Nicolas Catania48290382009-07-10 13:53:06 -0700155 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700156 ++data;
157 }
158 *status = OK;
159 return true;
160}
161
Nicolas Catania48290382009-07-10 13:53:06 -0700162// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163// @param val To be searched.
164// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700165bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700166{
167 // Deal with empty and ANY right away
168 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700169 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170
Nicolas Catania48290382009-07-10 13:53:06 -0700171 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172}
173
174} // anonymous namespace
175
176
The Android Open Source Project89fa4ad2009-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 Project89fa4ad2009-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 Project89fa4ad2009-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 Wang9ee159b2011-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 Project89fa4ad2009-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 Wangdac6a312009-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 Project89fa4ad2009-03-03 19:31:44 -0800230 LOGV("Create new media recorder client from pid %d", pid);
231 return recorder;
232}
233
Gloria Wangdac6a312009-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 Project89fa4ad2009-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 Huber2db84552010-01-28 11:19:57 -0800248sp<IMediaPlayer> MediaPlayerService::create(
249 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700250 const KeyedVector<String8, String8> *headers, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251{
252 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700253
254 sp<Client> c = new Client(
255 this, pid, connId, client, audioSessionId,
256 IPCThreadState::self()->getCallingUid());
257
Ashish Sharmaa23456b2011-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 Huber2db84552010-01-28 11:19:57 -0800260 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project89fa4ad2009-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 Laurenta514bdb2010-06-21 09:27:30 -0700272 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800273{
274 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700275
276 sp<Client> c = new Client(
277 this, pid, connId, client, audioSessionId,
278 IPCThreadState::self()->getCallingUid());
279
Ashish Sharmaa23456b2011-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 Project89fa4ad2009-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 Hubere2b10282010-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 Huber9b80c2b2011-06-30 15:47:02 -0700298
299 sp<Client> c = new Client(
300 this, pid, connId, client, audioSessionId,
301 IPCThreadState::self()->getCallingUid());
Andreas Hubere2b10282010-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 Huber318ad9c2009-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 Huber20111aa2009-07-14 16:56:47 -0700325}
326
The Android Open Source Project89fa4ad2009-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 Laurent2beeb502010-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 Project89fa4ad2009-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 Hubera0b1d4b2011-06-07 15:52:25 -0700383 if (mPlayer != NULL) {
384 mPlayer->dump(fd, args);
385 }
The Android Open Source Project89fa4ad2009-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 Project89fa4ad2009-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 Dongb9141222010-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 Wangdac6a312009-10-29 15:46:37 -0700421 }
422
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 result.append(" Files opened and/or mapped:\n");
Glenn Kasten0512ab52011-05-04 17:58:57 -0700424 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800425 FILE *f = fopen(buffer, "r");
426 if (f) {
427 while (!feof(f)) {
428 fgets(buffer, SIZE, f);
Dave Sparks02fa8342010-09-27 16:55:18 -0700429 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700431 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-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 Kasten0512ab52011-05-04 17:58:57 -0700444 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project89fa4ad2009-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 Kasten0512ab52011-05-04 17:58:57 -0700450 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project89fa4ad2009-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 Sparks02fa8342010-09-27 16:55:18 -0700465 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700467 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-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 Project89fa4ad2009-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 Dong8635b7b2011-03-14 17:01:38 -0700498 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800499 }
The Android Open Source Project89fa4ad2009-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 Huber9b80c2b2011-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 Project89fa4ad2009-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 Laurenta514bdb2010-06-21 09:27:30 -0700523 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700524 mUID = uid;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700525
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800526#if CALLBACK_ANTAGONIZER
527 LOGD("create Antagonizer");
528 mAntagonizer = new Antagonizer(notify, this);
529#endif
530}
531
532MediaPlayerService::Client::~Client()
533{
534 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
535 mAudioOutput.clear();
536 wp<Client> client(this);
537 disconnect();
538 mService->removeClient(client);
539}
540
541void MediaPlayerService::Client::disconnect()
542{
543 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
544 // grab local reference and clear main reference to prevent future
545 // access to object
546 sp<MediaPlayerBase> p;
547 {
548 Mutex::Autolock l(mLock);
549 p = mPlayer;
550 }
Dave Sparks795fa582009-03-24 17:57:12 -0700551 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700552
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 mPlayer.clear();
554
555 // clear the notification to prevent callbacks to dead client
556 // and reset the player. We assume the player will serialize
557 // access to itself if necessary.
558 if (p != 0) {
559 p->setNotifyCallback(0, 0);
560#if CALLBACK_ANTAGONIZER
561 LOGD("kill Antagonizer");
562 mAntagonizer->kill();
563#endif
564 p->reset();
565 }
566
567 IPCThreadState::self()->flushCommands();
568}
569
Andreas Huber47f59cf2009-08-07 09:30:32 -0700570static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700571 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700572}
573
James Dong148c1a22009-09-06 14:29:45 -0700574player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575{
576 char buf[20];
577 lseek(fd, offset, SEEK_SET);
578 read(fd, buf, sizeof(buf));
579 lseek(fd, offset, SEEK_SET);
580
581 long ident = *((long*)buf);
582
583 // Ogg vorbis?
584 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700585 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586
587 // Some kind of MIDI?
588 EAS_DATA_HANDLE easdata;
589 if (EAS_Init(&easdata) == EAS_SUCCESS) {
590 EAS_FILE locator;
591 locator.path = NULL;
592 locator.fd = fd;
593 locator.offset = offset;
594 locator.length = length;
595 EAS_HANDLE eashandle;
596 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
597 EAS_CloseFile(easdata, eashandle);
598 EAS_Shutdown(easdata);
599 return SONIVOX_PLAYER;
600 }
601 EAS_Shutdown(easdata);
602 }
603
Andreas Huber47f59cf2009-08-07 09:30:32 -0700604 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605}
606
James Dong148c1a22009-09-06 14:29:45 -0700607player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608{
Nicolas Catania14d27472009-07-13 14:37:49 -0700609 if (TestPlayerStub::canBeUsed(url)) {
610 return TEST_PLAYER;
611 }
612
Andreas Huber0a73d812011-03-21 16:28:04 -0700613 if (!strncasecmp("http://", url, 7)
614 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-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 Huber5bc087c2010-12-23 10:27:40 -0800619
Andreas Hubered8d14f2011-02-16 09:05:38 -0800620 if (strstr(url,"m3u8")) {
621 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800622 }
623 }
624
The Android Open Source Project89fa4ad2009-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 Enofc1c7b92010-03-19 23:18:02 +0900631 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700632 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 }
634 }
635 }
636
Andreas Huber47f59cf2009-08-07 09:30:32 -0700637 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-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 Project89fa4ad2009-03-03 19:31:44 -0800645 case SONIVOX_PLAYER:
646 LOGV(" create MidiFile");
647 p = new MidiFile();
648 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700649 case STAGEFRIGHT_PLAYER:
650 LOGV(" create StagefrightPlayer");
651 p = new StagefrightPlayer;
652 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800653 case NU_PLAYER:
654 LOGV(" create NuPlayer");
655 p = new NuPlayerDriver;
656 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700657 case TEST_PLAYER:
658 LOGV("Create Test Player stub");
659 p = new TestPlayerStub();
660 break;
James Dong30d713a2010-11-10 18:42:40 -0800661 default:
662 LOGE("Unknown player type: %d", playerType);
663 return NULL;
The Android Open Source Project89fa4ad2009-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 Huber9b80c2b2011-06-30 15:47:02 -0700689
Jason Simmonsdb29e522011-08-12 13:46:55 -0700690 if (p != NULL) {
691 p->setUID(mUID);
692 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700693
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694 return p;
695}
696
Andreas Huber2db84552010-01-28 11:19:57 -0800697status_t MediaPlayerService::Client::setDataSource(
698 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800699{
700 LOGV("setDataSource(%s)", url);
701 if (url == NULL)
702 return UNKNOWN_ERROR;
703
704 if (strncmp(url, "content://", 10) == 0) {
705 // get a filedescriptor for the content Uri and
706 // pass it to the setDataSource(fd) method
707
708 String16 url16(url);
709 int fd = android::openContentProviderFile(url16);
710 if (fd < 0)
711 {
712 LOGE("Couldn't open fd for %s", url);
713 return UNKNOWN_ERROR;
714 }
715 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
716 close(fd);
717 return mStatus;
718 } else {
719 player_type playerType = getPlayerType(url);
720 LOGV("player type = %d", playerType);
721
722 // create the right type of player
723 sp<MediaPlayerBase> p = createPlayer(playerType);
724 if (p == NULL) return NO_INIT;
725
726 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700727 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
729 }
730
731 // now set data source
732 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800733 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700734 if (mStatus == NO_ERROR) {
735 mPlayer = p;
736 } else {
737 LOGE(" error: %d", mStatus);
738 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739 return mStatus;
740 }
741}
742
743status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
744{
745 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
746 struct stat sb;
747 int ret = fstat(fd, &sb);
748 if (ret != 0) {
749 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
750 return UNKNOWN_ERROR;
751 }
752
753 LOGV("st_dev = %llu", sb.st_dev);
754 LOGV("st_mode = %u", sb.st_mode);
755 LOGV("st_uid = %lu", sb.st_uid);
756 LOGV("st_gid = %lu", sb.st_gid);
757 LOGV("st_size = %llu", sb.st_size);
758
759 if (offset >= sb.st_size) {
760 LOGE("offset error");
761 ::close(fd);
762 return UNKNOWN_ERROR;
763 }
764 if (offset + length > sb.st_size) {
765 length = sb.st_size - offset;
766 LOGV("calculated length = %lld", length);
767 }
768
769 player_type playerType = getPlayerType(fd, offset, length);
770 LOGV("player type = %d", playerType);
771
772 // create the right type of player
773 sp<MediaPlayerBase> p = createPlayer(playerType);
774 if (p == NULL) return NO_INIT;
775
776 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700777 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
779 }
780
781 // now set data source
782 mStatus = p->setDataSource(fd, offset, length);
783 if (mStatus == NO_ERROR) mPlayer = p;
784 return mStatus;
785}
786
Andreas Hubere2b10282010-11-23 11:41:34 -0800787status_t MediaPlayerService::Client::setDataSource(
788 const sp<IStreamSource> &source) {
789 // create the right type of player
Andreas Huberf9334412010-12-15 15:17:42 -0800790 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Hubere2b10282010-11-23 11:41:34 -0800791
792 if (p == NULL) {
793 return NO_INIT;
794 }
795
796 if (!p->hardwareOutput()) {
797 mAudioOutput = new AudioOutput(mAudioSessionId);
798 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
799 }
800
801 // now set data source
802 mStatus = p->setDataSource(source);
803
804 if (mStatus == OK) {
805 mPlayer = p;
806 }
807
808 return mStatus;
809}
810
Andreas Huber5daeb122010-08-16 08:49:37 -0700811status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812{
813 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
814 sp<MediaPlayerBase> p = getPlayer();
815 if (p == 0) return UNKNOWN_ERROR;
816 return p->setVideoSurface(surface);
817}
818
Glenn Kasten11731182011-02-08 17:26:17 -0800819status_t MediaPlayerService::Client::setVideoSurfaceTexture(
820 const sp<ISurfaceTexture>& surfaceTexture)
821{
822 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
823 sp<MediaPlayerBase> p = getPlayer();
824 if (p == 0) return UNKNOWN_ERROR;
825 return p->setVideoSurfaceTexture(surfaceTexture);
826}
827
Nicolas Catania1d187f12009-05-12 23:25:55 -0700828status_t MediaPlayerService::Client::invoke(const Parcel& request,
829 Parcel *reply)
830{
831 sp<MediaPlayerBase> p = getPlayer();
832 if (p == NULL) return UNKNOWN_ERROR;
833 return p->invoke(request, reply);
834}
835
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700836// This call doesn't need to access the native player.
837status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
838{
839 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700840 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700841
Nicolas Catania48290382009-07-10 13:53:06 -0700842 if (unmarshallFilter(filter, &allow, &status) &&
843 unmarshallFilter(filter, &drop, &status)) {
844 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700845
846 mMetadataAllow = allow;
847 mMetadataDrop = drop;
848 }
849 return status;
850}
851
Nicolas Catania48290382009-07-10 13:53:06 -0700852status_t MediaPlayerService::Client::getMetadata(
853 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700854{
nikoa64c8c72009-07-20 15:07:26 -0700855 sp<MediaPlayerBase> player = getPlayer();
856 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700857
nikod608a812009-07-16 16:39:53 -0700858 status_t status;
859 // Placeholder for the return code, updated by the caller.
860 reply->writeInt32(-1);
861
nikoa64c8c72009-07-20 15:07:26 -0700862 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700863
864 // We don't block notifications while we fetch the data. We clear
865 // mMetadataUpdated first so we don't lose notifications happening
866 // during the rest of this call.
867 {
868 Mutex::Autolock lock(mLock);
869 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700870 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700871 }
872 mMetadataUpdated.clear();
873 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700874
nikoa64c8c72009-07-20 15:07:26 -0700875 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700876
nikoa64c8c72009-07-20 15:07:26 -0700877 metadata.appendHeader();
878 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700879
880 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700881 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700882 LOGE("getMetadata failed %d", status);
883 return status;
884 }
885
886 // FIXME: Implement filtering on the result. Not critical since
887 // filtering takes place on the update notifications already. This
888 // would be when all the metadata are fetch and a filter is set.
889
nikod608a812009-07-16 16:39:53 -0700890 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700891 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700892 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700893}
894
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800895status_t MediaPlayerService::Client::prepareAsync()
896{
897 LOGV("[%d] prepareAsync", mConnId);
898 sp<MediaPlayerBase> p = getPlayer();
899 if (p == 0) return UNKNOWN_ERROR;
900 status_t ret = p->prepareAsync();
901#if CALLBACK_ANTAGONIZER
902 LOGD("start Antagonizer");
903 if (ret == NO_ERROR) mAntagonizer->start();
904#endif
905 return ret;
906}
907
908status_t MediaPlayerService::Client::start()
909{
910 LOGV("[%d] start", mConnId);
911 sp<MediaPlayerBase> p = getPlayer();
912 if (p == 0) return UNKNOWN_ERROR;
913 p->setLooping(mLoop);
914 return p->start();
915}
916
917status_t MediaPlayerService::Client::stop()
918{
919 LOGV("[%d] stop", mConnId);
920 sp<MediaPlayerBase> p = getPlayer();
921 if (p == 0) return UNKNOWN_ERROR;
922 return p->stop();
923}
924
925status_t MediaPlayerService::Client::pause()
926{
927 LOGV("[%d] pause", mConnId);
928 sp<MediaPlayerBase> p = getPlayer();
929 if (p == 0) return UNKNOWN_ERROR;
930 return p->pause();
931}
932
933status_t MediaPlayerService::Client::isPlaying(bool* state)
934{
935 *state = false;
936 sp<MediaPlayerBase> p = getPlayer();
937 if (p == 0) return UNKNOWN_ERROR;
938 *state = p->isPlaying();
939 LOGV("[%d] isPlaying: %d", mConnId, *state);
940 return NO_ERROR;
941}
942
943status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
944{
945 LOGV("getCurrentPosition");
946 sp<MediaPlayerBase> p = getPlayer();
947 if (p == 0) return UNKNOWN_ERROR;
948 status_t ret = p->getCurrentPosition(msec);
949 if (ret == NO_ERROR) {
950 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
951 } else {
952 LOGE("getCurrentPosition returned %d", ret);
953 }
954 return ret;
955}
956
957status_t MediaPlayerService::Client::getDuration(int *msec)
958{
959 LOGV("getDuration");
960 sp<MediaPlayerBase> p = getPlayer();
961 if (p == 0) return UNKNOWN_ERROR;
962 status_t ret = p->getDuration(msec);
963 if (ret == NO_ERROR) {
964 LOGV("[%d] getDuration = %d", mConnId, *msec);
965 } else {
966 LOGE("getDuration returned %d", ret);
967 }
968 return ret;
969}
970
971status_t MediaPlayerService::Client::seekTo(int msec)
972{
973 LOGV("[%d] seekTo(%d)", mConnId, msec);
974 sp<MediaPlayerBase> p = getPlayer();
975 if (p == 0) return UNKNOWN_ERROR;
976 return p->seekTo(msec);
977}
978
979status_t MediaPlayerService::Client::reset()
980{
981 LOGV("[%d] reset", mConnId);
982 sp<MediaPlayerBase> p = getPlayer();
983 if (p == 0) return UNKNOWN_ERROR;
984 return p->reset();
985}
986
987status_t MediaPlayerService::Client::setAudioStreamType(int type)
988{
989 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
990 // TODO: for hardware output, call player instead
991 Mutex::Autolock l(mLock);
992 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
993 return NO_ERROR;
994}
995
996status_t MediaPlayerService::Client::setLooping(int loop)
997{
998 LOGV("[%d] setLooping(%d)", mConnId, loop);
999 mLoop = loop;
1000 sp<MediaPlayerBase> p = getPlayer();
1001 if (p != 0) return p->setLooping(loop);
1002 return NO_ERROR;
1003}
1004
1005status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1006{
1007 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1008 // TODO: for hardware output, call player instead
1009 Mutex::Autolock l(mLock);
1010 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1011 return NO_ERROR;
1012}
1013
Eric Laurent2beeb502010-07-16 07:43:46 -07001014status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1015{
1016 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1017 Mutex::Autolock l(mLock);
1018 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1019 return NO_ERROR;
1020}
1021
1022status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1023{
1024 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1025 Mutex::Autolock l(mLock);
1026 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1027 return NO_ERROR;
1028}
Nicolas Catania48290382009-07-10 13:53:06 -07001029
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001030status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1031 LOGV("[%d] setParameter(%d)", mConnId, key);
1032 sp<MediaPlayerBase> p = getPlayer();
1033 if (p == 0) return UNKNOWN_ERROR;
1034 return p->setParameter(key, request);
1035}
1036
1037status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1038 LOGV("[%d] getParameter(%d)", mConnId, key);
1039 sp<MediaPlayerBase> p = getPlayer();
1040 if (p == 0) return UNKNOWN_ERROR;
1041 return p->getParameter(key, reply);
1042}
1043
Gloria Wangb483c472011-04-11 17:23:27 -07001044void MediaPlayerService::Client::notify(
1045 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046{
1047 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001048
1049 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001050 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001051 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001052
1053 if(client->shouldDropMetadata(metadata_type)) {
1054 return;
1055 }
1056
1057 // Update the list of metadata that have changed. getMetadata
1058 // also access mMetadataUpdated and clears it.
1059 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001060 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001061 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001062 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001063}
1064
Nicolas Catania48290382009-07-10 13:53:06 -07001065
nikoa64c8c72009-07-20 15:07:26 -07001066bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001067{
Nicolas Catania48290382009-07-10 13:53:06 -07001068 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001069
Nicolas Catania48290382009-07-10 13:53:06 -07001070 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001071 return true;
1072 }
1073
Nicolas Catania48290382009-07-10 13:53:06 -07001074 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001075 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001076 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001077 return true;
1078 }
1079}
1080
Nicolas Catania48290382009-07-10 13:53:06 -07001081
nikoa64c8c72009-07-20 15:07:26 -07001082void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001083 Mutex::Autolock lock(mLock);
1084 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1085 mMetadataUpdated.add(metadata_type);
1086 }
1087}
1088
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089#if CALLBACK_ANTAGONIZER
1090const int Antagonizer::interval = 10000; // 10 msecs
1091
1092Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1093 mExit(false), mActive(false), mClient(client), mCb(cb)
1094{
1095 createThread(callbackThread, this);
1096}
1097
1098void Antagonizer::kill()
1099{
1100 Mutex::Autolock _l(mLock);
1101 mActive = false;
1102 mExit = true;
1103 mCondition.wait(mLock);
1104}
1105
1106int Antagonizer::callbackThread(void* user)
1107{
1108 LOGD("Antagonizer started");
1109 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1110 while (!p->mExit) {
1111 if (p->mActive) {
1112 LOGV("send event");
1113 p->mCb(p->mClient, 0, 0, 0);
1114 }
1115 usleep(interval);
1116 }
1117 Mutex::Autolock _l(p->mLock);
1118 p->mCondition.signal();
1119 LOGD("Antagonizer stopped");
1120 return 0;
1121}
1122#endif
1123
1124static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1125
1126sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1127{
1128 LOGV("decode(%s)", url);
1129 sp<MemoryBase> mem;
1130 sp<MediaPlayerBase> player;
1131
1132 // Protect our precious, precious DRMd ringtones by only allowing
1133 // decoding of http, but not filesystem paths or content Uris.
1134 // If the application wants to decode those, it should open a
1135 // filedescriptor for them and use that.
1136 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1137 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1138 return mem;
1139 }
1140
1141 player_type playerType = getPlayerType(url);
1142 LOGV("player type = %d", playerType);
1143
1144 // create the right type of player
1145 sp<AudioCache> cache = new AudioCache(url);
1146 player = android::createPlayer(playerType, cache.get(), cache->notify);
1147 if (player == NULL) goto Exit;
1148 if (player->hardwareOutput()) goto Exit;
1149
1150 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1151
1152 // set data source
1153 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1154
1155 LOGV("prepare");
1156 player->prepareAsync();
1157
1158 LOGV("wait for prepare");
1159 if (cache->wait() != NO_ERROR) goto Exit;
1160
1161 LOGV("start");
1162 player->start();
1163
1164 LOGV("wait for playback complete");
1165 if (cache->wait() != NO_ERROR) goto Exit;
1166
1167 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1168 *pSampleRate = cache->sampleRate();
1169 *pNumChannels = cache->channelCount();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001170 *pFormat = (int)cache->format();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001171 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1172
1173Exit:
1174 if (player != 0) player->reset();
1175 return mem;
1176}
1177
1178sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1179{
1180 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1181 sp<MemoryBase> mem;
1182 sp<MediaPlayerBase> player;
1183
1184 player_type playerType = getPlayerType(fd, offset, length);
1185 LOGV("player type = %d", playerType);
1186
1187 // create the right type of player
1188 sp<AudioCache> cache = new AudioCache("decode_fd");
1189 player = android::createPlayer(playerType, cache.get(), cache->notify);
1190 if (player == NULL) goto Exit;
1191 if (player->hardwareOutput()) goto Exit;
1192
1193 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1194
1195 // set data source
1196 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1197
1198 LOGV("prepare");
1199 player->prepareAsync();
1200
1201 LOGV("wait for prepare");
1202 if (cache->wait() != NO_ERROR) goto Exit;
1203
1204 LOGV("start");
1205 player->start();
1206
1207 LOGV("wait for playback complete");
1208 if (cache->wait() != NO_ERROR) goto Exit;
1209
1210 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1211 *pSampleRate = cache->sampleRate();
1212 *pNumChannels = cache->channelCount();
1213 *pFormat = cache->format();
1214 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1215
1216Exit:
1217 if (player != 0) player->reset();
1218 ::close(fd);
1219 return mem;
1220}
1221
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001222
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001223#undef LOG_TAG
1224#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001225MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001226 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001227 mCallbackCookie(NULL),
1228 mSessionId(sessionId) {
1229 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001230 mTrack = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -07001231 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001232 mLeftVolume = 1.0;
1233 mRightVolume = 1.0;
1234 mLatency = 0;
1235 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001236 mAuxEffectId = 0;
1237 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001238 setMinBufferCount();
1239}
1240
1241MediaPlayerService::AudioOutput::~AudioOutput()
1242{
1243 close();
1244}
1245
1246void MediaPlayerService::AudioOutput::setMinBufferCount()
1247{
1248 char value[PROPERTY_VALUE_MAX];
1249 if (property_get("ro.kernel.qemu", value, 0)) {
1250 mIsOnEmulator = true;
1251 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1252 }
1253}
1254
1255bool MediaPlayerService::AudioOutput::isOnEmulator()
1256{
1257 setMinBufferCount();
1258 return mIsOnEmulator;
1259}
1260
1261int MediaPlayerService::AudioOutput::getMinBufferCount()
1262{
1263 setMinBufferCount();
1264 return mMinBufferCount;
1265}
1266
1267ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1268{
1269 if (mTrack == 0) return NO_INIT;
1270 return mTrack->frameCount() * frameSize();
1271}
1272
1273ssize_t MediaPlayerService::AudioOutput::frameCount() const
1274{
1275 if (mTrack == 0) return NO_INIT;
1276 return mTrack->frameCount();
1277}
1278
1279ssize_t MediaPlayerService::AudioOutput::channelCount() const
1280{
1281 if (mTrack == 0) return NO_INIT;
1282 return mTrack->channelCount();
1283}
1284
1285ssize_t MediaPlayerService::AudioOutput::frameSize() const
1286{
1287 if (mTrack == 0) return NO_INIT;
1288 return mTrack->frameSize();
1289}
1290
1291uint32_t MediaPlayerService::AudioOutput::latency () const
1292{
1293 return mLatency;
1294}
1295
1296float MediaPlayerService::AudioOutput::msecsPerFrame() const
1297{
1298 return mMsecsPerFrame;
1299}
1300
Eric Laurent342e9cf2010-01-19 17:37:09 -08001301status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1302{
1303 if (mTrack == 0) return NO_INIT;
1304 return mTrack->getPosition(position);
1305}
1306
Andreas Huber20111aa2009-07-14 16:56:47 -07001307status_t MediaPlayerService::AudioOutput::open(
1308 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1309 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001310{
Andreas Huber20111aa2009-07-14 16:56:47 -07001311 mCallback = cb;
1312 mCallbackCookie = cookie;
1313
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001314 // Check argument "bufferCount" against the mininum buffer count
1315 if (bufferCount < mMinBufferCount) {
1316 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1317 bufferCount = mMinBufferCount;
1318
1319 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001320 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001321 if (mTrack) close();
1322 int afSampleRate;
1323 int afFrameCount;
1324 int frameCount;
1325
1326 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1327 return NO_INIT;
1328 }
1329 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1330 return NO_INIT;
1331 }
1332
1333 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001334
1335 AudioTrack *t;
1336 if (mCallback != NULL) {
1337 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001338 mStreamType,
1339 sampleRate,
1340 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001341 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001342 frameCount,
1343 0 /* flags */,
1344 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001345 this,
1346 0,
1347 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001348 } else {
1349 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001350 mStreamType,
1351 sampleRate,
1352 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001353 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001354 frameCount,
1355 0,
1356 NULL,
1357 NULL,
1358 0,
1359 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001360 }
1361
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001362 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1363 LOGE("Unable to create audio track");
1364 delete t;
1365 return NO_INIT;
1366 }
1367
1368 LOGV("setVolume");
1369 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001370
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001371 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001372 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001374
1375 t->setAuxEffectSendLevel(mSendLevel);
1376 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001377}
1378
1379void MediaPlayerService::AudioOutput::start()
1380{
1381 LOGV("start");
1382 if (mTrack) {
1383 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001384 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385 mTrack->start();
1386 }
1387}
1388
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001389
1390
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1392{
Andreas Huber20111aa2009-07-14 16:56:47 -07001393 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1394
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001395 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001396 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001397 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001398 return ret;
1399 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 return NO_INIT;
1401}
1402
1403void MediaPlayerService::AudioOutput::stop()
1404{
1405 LOGV("stop");
1406 if (mTrack) mTrack->stop();
1407}
1408
1409void MediaPlayerService::AudioOutput::flush()
1410{
1411 LOGV("flush");
1412 if (mTrack) mTrack->flush();
1413}
1414
1415void MediaPlayerService::AudioOutput::pause()
1416{
1417 LOGV("pause");
1418 if (mTrack) mTrack->pause();
1419}
1420
1421void MediaPlayerService::AudioOutput::close()
1422{
1423 LOGV("close");
1424 delete mTrack;
1425 mTrack = 0;
1426}
1427
1428void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1429{
1430 LOGV("setVolume(%f, %f)", left, right);
1431 mLeftVolume = left;
1432 mRightVolume = right;
1433 if (mTrack) {
1434 mTrack->setVolume(left, right);
1435 }
1436}
1437
Eric Laurent2beeb502010-07-16 07:43:46 -07001438status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1439{
1440 LOGV("setAuxEffectSendLevel(%f)", level);
1441 mSendLevel = level;
1442 if (mTrack) {
1443 return mTrack->setAuxEffectSendLevel(level);
1444 }
1445 return NO_ERROR;
1446}
1447
1448status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1449{
1450 LOGV("attachAuxEffect(%d)", effectId);
1451 mAuxEffectId = effectId;
1452 if (mTrack) {
1453 return mTrack->attachAuxEffect(effectId);
1454 }
1455 return NO_ERROR;
1456}
1457
Andreas Huber20111aa2009-07-14 16:56:47 -07001458// static
1459void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001460 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001461 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001462 if (event != AudioTrack::EVENT_MORE_DATA) {
1463 return;
1464 }
1465
1466 AudioOutput *me = (AudioOutput *)cookie;
1467 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1468
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001469 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001470 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001471
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001472 if (actualSize == 0 && buffer->size > 0) {
1473 // We've reached EOS but the audio track is not stopped yet,
1474 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001475
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001476 memset(buffer->raw, 0, buffer->size);
1477 actualSize = buffer->size;
1478 }
1479
1480 buffer->size = actualSize;
Andreas Huber20111aa2009-07-14 16:56:47 -07001481}
1482
Eric Laurent8c563ed2010-10-07 18:23:03 -07001483int MediaPlayerService::AudioOutput::getSessionId()
1484{
1485 return mSessionId;
1486}
1487
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001488#undef LOG_TAG
1489#define LOG_TAG "AudioCache"
1490MediaPlayerService::AudioCache::AudioCache(const char* name) :
1491 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1492 mError(NO_ERROR), mCommandComplete(false)
1493{
1494 // create ashmem heap
1495 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1496}
1497
1498uint32_t MediaPlayerService::AudioCache::latency () const
1499{
1500 return 0;
1501}
1502
1503float MediaPlayerService::AudioCache::msecsPerFrame() const
1504{
1505 return mMsecsPerFrame;
1506}
1507
Eric Laurent342e9cf2010-01-19 17:37:09 -08001508status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1509{
1510 if (position == 0) return BAD_VALUE;
1511 *position = mSize;
1512 return NO_ERROR;
1513}
1514
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001515////////////////////////////////////////////////////////////////////////////////
1516
1517struct CallbackThread : public Thread {
1518 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1519 MediaPlayerBase::AudioSink::AudioCallback cb,
1520 void *cookie);
1521
1522protected:
1523 virtual ~CallbackThread();
1524
1525 virtual bool threadLoop();
1526
1527private:
1528 wp<MediaPlayerBase::AudioSink> mSink;
1529 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1530 void *mCookie;
1531 void *mBuffer;
1532 size_t mBufferSize;
1533
1534 CallbackThread(const CallbackThread &);
1535 CallbackThread &operator=(const CallbackThread &);
1536};
1537
1538CallbackThread::CallbackThread(
1539 const wp<MediaPlayerBase::AudioSink> &sink,
1540 MediaPlayerBase::AudioSink::AudioCallback cb,
1541 void *cookie)
1542 : mSink(sink),
1543 mCallback(cb),
1544 mCookie(cookie),
1545 mBuffer(NULL),
1546 mBufferSize(0) {
1547}
1548
1549CallbackThread::~CallbackThread() {
1550 if (mBuffer) {
1551 free(mBuffer);
1552 mBuffer = NULL;
1553 }
1554}
1555
1556bool CallbackThread::threadLoop() {
1557 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1558 if (sink == NULL) {
1559 return false;
1560 }
1561
1562 if (mBuffer == NULL) {
1563 mBufferSize = sink->bufferSize();
1564 mBuffer = malloc(mBufferSize);
1565 }
1566
1567 size_t actualSize =
1568 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1569
1570 if (actualSize > 0) {
1571 sink->write(mBuffer, actualSize);
1572 }
1573
1574 return true;
1575}
1576
1577////////////////////////////////////////////////////////////////////////////////
1578
Andreas Huber20111aa2009-07-14 16:56:47 -07001579status_t MediaPlayerService::AudioCache::open(
1580 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1581 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001582{
Dave Sparks8eb80112009-12-09 20:20:26 -08001583 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001584 if (mHeap->getHeapID() < 0) {
1585 return NO_INIT;
1586 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001587
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001588 mSampleRate = sampleRate;
1589 mChannelCount = (uint16_t)channelCount;
1590 mFormat = (uint16_t)format;
1591 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001592
1593 if (cb != NULL) {
1594 mCallbackThread = new CallbackThread(this, cb, cookie);
1595 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001596 return NO_ERROR;
1597}
1598
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001599void MediaPlayerService::AudioCache::start() {
1600 if (mCallbackThread != NULL) {
1601 mCallbackThread->run("AudioCache callback");
1602 }
1603}
1604
1605void MediaPlayerService::AudioCache::stop() {
1606 if (mCallbackThread != NULL) {
1607 mCallbackThread->requestExitAndWait();
1608 }
1609}
1610
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001611ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1612{
1613 LOGV("write(%p, %u)", buffer, size);
1614 if ((buffer == 0) || (size == 0)) return size;
1615
1616 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1617 if (p == NULL) return NO_INIT;
1618 p += mSize;
1619 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1620 if (mSize + size > mHeap->getSize()) {
1621 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1622 size = mHeap->getSize() - mSize;
1623 }
1624 memcpy(p, buffer, size);
1625 mSize += size;
1626 return size;
1627}
1628
1629// call with lock held
1630status_t MediaPlayerService::AudioCache::wait()
1631{
1632 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001633 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634 mSignal.wait(mLock);
1635 }
1636 mCommandComplete = false;
1637
1638 if (mError == NO_ERROR) {
1639 LOGV("wait - success");
1640 } else {
1641 LOGV("wait - error");
1642 }
1643 return mError;
1644}
1645
Gloria Wangb483c472011-04-11 17:23:27 -07001646void MediaPlayerService::AudioCache::notify(
1647 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001648{
1649 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1650 AudioCache* p = static_cast<AudioCache*>(cookie);
1651
1652 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001653 switch (msg)
1654 {
1655 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001656 LOGE("Error %d, %d occurred", ext1, ext2);
1657 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001658 break;
1659 case MEDIA_PREPARED:
1660 LOGV("prepared");
1661 break;
1662 case MEDIA_PLAYBACK_COMPLETE:
1663 LOGV("playback complete");
1664 break;
1665 default:
1666 LOGV("ignored");
1667 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001668 }
1669
1670 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001671 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672 p->mCommandComplete = true;
1673 p->mSignal.signal();
1674}
1675
Eric Laurent8c563ed2010-10-07 18:23:03 -07001676int MediaPlayerService::AudioCache::getSessionId()
1677{
1678 return 0;
1679}
1680
Gloria Wang7cf180c2011-02-19 18:37:57 -08001681void MediaPlayerService::addBatteryData(uint32_t params)
1682{
1683 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001684
1685 int32_t time = systemTime() / 1000000L;
1686
1687 // change audio output devices. This notification comes from AudioFlinger
1688 if ((params & kBatteryDataSpeakerOn)
1689 || (params & kBatteryDataOtherAudioDeviceOn)) {
1690
1691 int deviceOn[NUM_AUDIO_DEVICES];
1692 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1693 deviceOn[i] = 0;
1694 }
1695
1696 if ((params & kBatteryDataSpeakerOn)
1697 && (params & kBatteryDataOtherAudioDeviceOn)) {
1698 deviceOn[SPEAKER_AND_OTHER] = 1;
1699 } else if (params & kBatteryDataSpeakerOn) {
1700 deviceOn[SPEAKER] = 1;
1701 } else {
1702 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1703 }
1704
1705 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1706 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1707
1708 if (mBatteryAudio.refCount > 0) { // if playing audio
1709 if (!deviceOn[i]) {
1710 mBatteryAudio.lastTime[i] += time;
1711 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1712 mBatteryAudio.lastTime[i] = 0;
1713 } else {
1714 mBatteryAudio.lastTime[i] = 0 - time;
1715 }
1716 }
1717
1718 mBatteryAudio.deviceOn[i] = deviceOn[i];
1719 }
1720 }
1721 return;
1722 }
1723
1724 // an sudio stream is started
1725 if (params & kBatteryDataAudioFlingerStart) {
1726 // record the start time only if currently no other audio
1727 // is being played
1728 if (mBatteryAudio.refCount == 0) {
1729 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1730 if (mBatteryAudio.deviceOn[i]) {
1731 mBatteryAudio.lastTime[i] -= time;
1732 }
1733 }
1734 }
1735
1736 mBatteryAudio.refCount ++;
1737 return;
1738
1739 } else if (params & kBatteryDataAudioFlingerStop) {
1740 if (mBatteryAudio.refCount <= 0) {
1741 LOGW("Battery track warning: refCount is <= 0");
1742 return;
1743 }
1744
1745 // record the stop time only if currently this is the only
1746 // audio being played
1747 if (mBatteryAudio.refCount == 1) {
1748 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1749 if (mBatteryAudio.deviceOn[i]) {
1750 mBatteryAudio.lastTime[i] += time;
1751 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1752 mBatteryAudio.lastTime[i] = 0;
1753 }
1754 }
1755 }
1756
1757 mBatteryAudio.refCount --;
1758 return;
1759 }
1760
Gloria Wang7cf180c2011-02-19 18:37:57 -08001761 int uid = IPCThreadState::self()->getCallingUid();
1762 if (uid == AID_MEDIA) {
1763 return;
1764 }
1765 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001766
1767 if (index < 0) { // create a new entry for this UID
1768 BatteryUsageInfo info;
1769 info.audioTotalTime = 0;
1770 info.videoTotalTime = 0;
1771 info.audioLastTime = 0;
1772 info.videoLastTime = 0;
1773 info.refCount = 0;
1774
Gloria Wang9ee159b2011-02-24 14:51:45 -08001775 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1776 LOGE("Battery track error: no memory for new app");
1777 return;
1778 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001779 }
1780
1781 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1782
1783 if (params & kBatteryDataCodecStarted) {
1784 if (params & kBatteryDataTrackAudio) {
1785 info.audioLastTime -= time;
1786 info.refCount ++;
1787 }
1788 if (params & kBatteryDataTrackVideo) {
1789 info.videoLastTime -= time;
1790 info.refCount ++;
1791 }
1792 } else {
1793 if (info.refCount == 0) {
1794 LOGW("Battery track warning: refCount is already 0");
1795 return;
1796 } else if (info.refCount < 0) {
1797 LOGE("Battery track error: refCount < 0");
1798 mBatteryData.removeItem(uid);
1799 return;
1800 }
1801
1802 if (params & kBatteryDataTrackAudio) {
1803 info.audioLastTime += time;
1804 info.refCount --;
1805 }
1806 if (params & kBatteryDataTrackVideo) {
1807 info.videoLastTime += time;
1808 info.refCount --;
1809 }
1810
1811 // no stream is being played by this UID
1812 if (info.refCount == 0) {
1813 info.audioTotalTime += info.audioLastTime;
1814 info.audioLastTime = 0;
1815 info.videoTotalTime += info.videoLastTime;
1816 info.videoLastTime = 0;
1817 }
1818 }
1819}
1820
1821status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1822 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001823
1824 // audio output devices usage
1825 int32_t time = systemTime() / 1000000L; //in ms
1826 int32_t totalTime;
1827
1828 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1829 totalTime = mBatteryAudio.totalTime[i];
1830
1831 if (mBatteryAudio.deviceOn[i]
1832 && (mBatteryAudio.lastTime[i] != 0)) {
1833 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1834 totalTime += tmpTime;
1835 }
1836
1837 reply->writeInt32(totalTime);
1838 // reset the total time
1839 mBatteryAudio.totalTime[i] = 0;
1840 }
1841
1842 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001843 BatteryUsageInfo info;
1844 int size = mBatteryData.size();
1845
1846 reply->writeInt32(size);
1847 int i = 0;
1848
1849 while (i < size) {
1850 info = mBatteryData.valueAt(i);
1851
1852 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1853 reply->writeInt32(info.audioTotalTime);
1854 reply->writeInt32(info.videoTotalTime);
1855
1856 info.audioTotalTime = 0;
1857 info.videoTotalTime = 0;
1858
1859 // remove the UID entry where no stream is being played
1860 if (info.refCount <= 0) {
1861 mBatteryData.removeItemsAt(i);
1862 size --;
1863 i --;
1864 }
1865 i++;
1866 }
1867 return NO_ERROR;
1868}
nikoa64c8c72009-07-20 15:07:26 -07001869} // namespace android