blob: 0386d4b65987702b8062c4f750b6dbebda5b1f56 [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
Dave Burkefc301b02011-08-30 14:39:17 +0100179static bool checkPermission(const char* permissionString) {
180#ifndef HAVE_ANDROID_OS
181 return true;
182#endif
183 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
184 bool ok = checkCallingPermission(String16(permissionString));
185 if (!ok) LOGE("Request requires %s", permissionString);
186 return ok;
187}
188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189// TODO: Temp hack until we can register players
190typedef struct {
191 const char *extension;
192 const player_type playertype;
193} extmap;
194extmap FILE_EXTS [] = {
195 {".mid", SONIVOX_PLAYER},
196 {".midi", SONIVOX_PLAYER},
197 {".smf", SONIVOX_PLAYER},
198 {".xmf", SONIVOX_PLAYER},
199 {".imy", SONIVOX_PLAYER},
200 {".rtttl", SONIVOX_PLAYER},
201 {".rtx", SONIVOX_PLAYER},
202 {".ota", SONIVOX_PLAYER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203};
204
205// 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 -0800206/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
207/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
208
209void MediaPlayerService::instantiate() {
210 defaultServiceManager()->addService(
211 String16("media.player"), new MediaPlayerService());
212}
213
214MediaPlayerService::MediaPlayerService()
215{
216 LOGV("MediaPlayerService created");
217 mNextConnId = 1;
Gloria Wang9b3f1522011-02-24 14:51:45 -0800218
219 mBatteryAudio.refCount = 0;
220 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
221 mBatteryAudio.deviceOn[i] = 0;
222 mBatteryAudio.lastTime[i] = 0;
223 mBatteryAudio.totalTime[i] = 0;
224 }
225 // speaker is on by default
226 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227}
228
229MediaPlayerService::~MediaPlayerService()
230{
231 LOGV("MediaPlayerService destroyed");
232}
233
234sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
235{
Gloria Wang608a2632009-10-29 15:46:37 -0700236 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
237 wp<MediaRecorderClient> w = recorder;
238 Mutex::Autolock lock(mLock);
239 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 LOGV("Create new media recorder client from pid %d", pid);
241 return recorder;
242}
243
Gloria Wang608a2632009-10-29 15:46:37 -0700244void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
245{
246 Mutex::Autolock lock(mLock);
247 mMediaRecorderClients.remove(client);
248 LOGV("Delete media recorder client");
249}
250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
252{
253 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
254 LOGV("Create new media retriever from pid %d", pid);
255 return retriever;
256}
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burkefc301b02011-08-30 14:39:17 +0100259 int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260{
261 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700262
263 sp<Client> c = new Client(
264 this, pid, connId, client, audioSessionId,
265 IPCThreadState::self()->getCallingUid());
266
Dave Burkefc301b02011-08-30 14:39:17 +0100267 LOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
268 IPCThreadState::self()->getCallingUid());
269
270 wp<Client> w = c;
271 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 Mutex::Autolock lock(mLock);
273 mClients.add(w);
274 }
Andreas Huber52b52cd2010-11-23 11:41:34 -0800275 return c;
276}
277
Andreas Huber784202e2009-10-15 13:46:54 -0700278sp<IOMX> MediaPlayerService::getOMX() {
279 Mutex::Autolock autoLock(mLock);
280
281 if (mOMX.get() == NULL) {
282 mOMX = new OMX;
283 }
284
285 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700286}
287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
293
294 result.append(" AudioCache\n");
295 if (mHeap != 0) {
296 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
297 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
298 result.append(buffer);
299 }
300 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
301 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
302 result.append(buffer);
303 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
304 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
305 result.append(buffer);
306 ::write(fd, result.string(), result.size());
307 return NO_ERROR;
308}
309
310status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
311{
312 const size_t SIZE = 256;
313 char buffer[SIZE];
314 String8 result;
315
316 result.append(" AudioOutput\n");
317 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
318 mStreamType, mLeftVolume, mRightVolume);
319 result.append(buffer);
320 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
321 mMsecsPerFrame, mLatency);
322 result.append(buffer);
Eric Laurent7070b362010-07-16 07:43:46 -0700323 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
324 mAuxEffectId, mSendLevel);
325 result.append(buffer);
326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 ::write(fd, result.string(), result.size());
328 if (mTrack != 0) {
329 mTrack->dump(fd, args);
330 }
331 return NO_ERROR;
332}
333
334status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
335{
336 const size_t SIZE = 256;
337 char buffer[SIZE];
338 String8 result;
339 result.append(" Client\n");
340 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
341 mPid, mConnId, mStatus, mLoop?"true": "false");
342 result.append(buffer);
343 write(fd, result.string(), result.size());
Andreas Huberfddf5d92011-06-07 15:52:25 -0700344 if (mPlayer != NULL) {
345 mPlayer->dump(fd, args);
346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 if (mAudioOutput != 0) {
348 mAudioOutput->dump(fd, args);
349 }
350 write(fd, "\n", 1);
351 return NO_ERROR;
352}
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
355{
356 const size_t SIZE = 256;
357 char buffer[SIZE];
358 String8 result;
359 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
360 snprintf(buffer, SIZE, "Permission Denial: "
361 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
362 IPCThreadState::self()->getCallingPid(),
363 IPCThreadState::self()->getCallingUid());
364 result.append(buffer);
365 } else {
366 Mutex::Autolock lock(mLock);
367 for (int i = 0, n = mClients.size(); i < n; ++i) {
368 sp<Client> c = mClients[i].promote();
369 if (c != 0) c->dump(fd, args);
370 }
James Dong929642e2010-07-08 11:16:11 -0700371 if (mMediaRecorderClients.size() == 0) {
372 result.append(" No media recorder client\n\n");
373 } else {
374 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
375 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
376 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
377 result.append(buffer);
378 write(fd, result.string(), result.size());
379 result = "\n";
380 c->dump(fd, args);
381 }
Gloria Wang608a2632009-10-29 15:46:37 -0700382 }
383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 result.append(" Files opened and/or mapped:\n");
Glenn Kasten6af763b2011-05-04 17:58:57 -0700385 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 FILE *f = fopen(buffer, "r");
387 if (f) {
388 while (!feof(f)) {
389 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700390 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700392 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 strstr(buffer, " /system/media/")) {
394 result.append(" ");
395 result.append(buffer);
396 }
397 }
398 fclose(f);
399 } else {
400 result.append("couldn't open ");
401 result.append(buffer);
402 result.append("\n");
403 }
404
Glenn Kasten6af763b2011-05-04 17:58:57 -0700405 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 DIR *d = opendir(buffer);
407 if (d) {
408 struct dirent *ent;
409 while((ent = readdir(d)) != NULL) {
410 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten6af763b2011-05-04 17:58:57 -0700411 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 struct stat s;
413 if (lstat(buffer, &s) == 0) {
414 if ((s.st_mode & S_IFMT) == S_IFLNK) {
415 char linkto[256];
416 int len = readlink(buffer, linkto, sizeof(linkto));
417 if(len > 0) {
418 if(len > 255) {
419 linkto[252] = '.';
420 linkto[253] = '.';
421 linkto[254] = '.';
422 linkto[255] = 0;
423 } else {
424 linkto[len] = 0;
425 }
Dave Sparks124a3462010-09-27 16:55:18 -0700426 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700428 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 strstr(linkto, "/system/media/") == linkto) {
430 result.append(" ");
431 result.append(buffer);
432 result.append(" -> ");
433 result.append(linkto);
434 result.append("\n");
435 }
436 }
437 } else {
438 result.append(" unexpected type for ");
439 result.append(buffer);
440 result.append("\n");
441 }
442 }
443 }
444 }
445 closedir(d);
446 } else {
447 result.append("couldn't open ");
448 result.append(buffer);
449 result.append("\n");
450 }
451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 bool dumpMem = false;
453 for (size_t i = 0; i < args.size(); i++) {
454 if (args[i] == String16("-m")) {
455 dumpMem = true;
456 }
457 }
458 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700459 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 }
462 write(fd, result.string(), result.size());
463 return NO_ERROR;
464}
465
466void MediaPlayerService::removeClient(wp<Client> client)
467{
468 Mutex::Autolock lock(mLock);
469 mClients.remove(client);
470}
471
Andreas Huber603d7392011-06-30 15:47:02 -0700472MediaPlayerService::Client::Client(
473 const sp<MediaPlayerService>& service, pid_t pid,
474 int32_t connId, const sp<IMediaPlayerClient>& client,
475 int audioSessionId, uid_t uid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476{
477 LOGV("Client(%d) constructor", connId);
478 mPid = pid;
479 mConnId = connId;
480 mService = service;
481 mClient = client;
482 mLoop = false;
483 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700484 mAudioSessionId = audioSessionId;
Andreas Huber603d7392011-06-30 15:47:02 -0700485 mUID = uid;
Eric Laurent619346f2010-06-21 09:27:30 -0700486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487#if CALLBACK_ANTAGONIZER
488 LOGD("create Antagonizer");
489 mAntagonizer = new Antagonizer(notify, this);
490#endif
491}
492
493MediaPlayerService::Client::~Client()
494{
495 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
496 mAudioOutput.clear();
497 wp<Client> client(this);
498 disconnect();
499 mService->removeClient(client);
500}
501
502void MediaPlayerService::Client::disconnect()
503{
504 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
505 // grab local reference and clear main reference to prevent future
506 // access to object
507 sp<MediaPlayerBase> p;
508 {
509 Mutex::Autolock l(mLock);
510 p = mPlayer;
511 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700512 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 mPlayer.clear();
515
516 // clear the notification to prevent callbacks to dead client
517 // and reset the player. We assume the player will serialize
518 // access to itself if necessary.
519 if (p != 0) {
520 p->setNotifyCallback(0, 0);
521#if CALLBACK_ANTAGONIZER
522 LOGD("kill Antagonizer");
523 mAntagonizer->kill();
524#endif
525 p->reset();
526 }
527
528 IPCThreadState::self()->flushCommands();
529}
530
Andreas Huber0d596d42009-08-07 09:30:32 -0700531static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700532 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700533}
534
James Dong392ff3b2009-09-06 14:29:45 -0700535player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536{
537 char buf[20];
538 lseek(fd, offset, SEEK_SET);
539 read(fd, buf, sizeof(buf));
540 lseek(fd, offset, SEEK_SET);
541
542 long ident = *((long*)buf);
543
544 // Ogg vorbis?
545 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700546 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547
548 // Some kind of MIDI?
549 EAS_DATA_HANDLE easdata;
550 if (EAS_Init(&easdata) == EAS_SUCCESS) {
551 EAS_FILE locator;
552 locator.path = NULL;
553 locator.fd = fd;
554 locator.offset = offset;
555 locator.length = length;
556 EAS_HANDLE eashandle;
557 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
558 EAS_CloseFile(easdata, eashandle);
559 EAS_Shutdown(easdata);
560 return SONIVOX_PLAYER;
561 }
562 EAS_Shutdown(easdata);
563 }
564
Andreas Huber0d596d42009-08-07 09:30:32 -0700565 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566}
567
James Dong392ff3b2009-09-06 14:29:45 -0700568player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700570 if (TestPlayerStub::canBeUsed(url)) {
571 return TEST_PLAYER;
572 }
573
Andreas Huber554d0ea2011-03-21 16:28:04 -0700574 if (!strncasecmp("http://", url, 7)
575 || !strncasecmp("https://", url, 8)) {
Andreas Huberd6c421f2011-02-16 09:05:38 -0800576 size_t len = strlen(url);
577 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
578 return NU_PLAYER;
579 }
Andreas Huber54e66492010-12-23 10:27:40 -0800580
Andreas Huberd6c421f2011-02-16 09:05:38 -0800581 if (strstr(url,"m3u8")) {
582 return NU_PLAYER;
Andreas Huber54e66492010-12-23 10:27:40 -0800583 }
584 }
585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 // use MidiFile for MIDI extensions
587 int lenURL = strlen(url);
588 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
589 int len = strlen(FILE_EXTS[i].extension);
590 int start = lenURL - len;
591 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900592 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700593 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
595 }
596 }
597
Andreas Huber0d596d42009-08-07 09:30:32 -0700598 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599}
600
601static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
602 notify_callback_f notifyFunc)
603{
604 sp<MediaPlayerBase> p;
605 switch (playerType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 case SONIVOX_PLAYER:
607 LOGV(" create MidiFile");
608 p = new MidiFile();
609 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700610 case STAGEFRIGHT_PLAYER:
611 LOGV(" create StagefrightPlayer");
612 p = new StagefrightPlayer;
613 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800614 case NU_PLAYER:
615 LOGV(" create NuPlayer");
616 p = new NuPlayerDriver;
617 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700618 case TEST_PLAYER:
619 LOGV("Create Test Player stub");
620 p = new TestPlayerStub();
621 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800622 default:
623 LOGE("Unknown player type: %d", playerType);
624 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626 if (p != NULL) {
627 if (p->initCheck() == NO_ERROR) {
628 p->setNotifyCallback(cookie, notifyFunc);
629 } else {
630 p.clear();
631 }
632 }
633 if (p == NULL) {
634 LOGE("Failed to create player object");
635 }
636 return p;
637}
638
639sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
640{
641 // determine if we have the right player type
642 sp<MediaPlayerBase> p = mPlayer;
643 if ((p != NULL) && (p->playerType() != playerType)) {
644 LOGV("delete player");
645 p.clear();
646 }
647 if (p == NULL) {
648 p = android::createPlayer(playerType, this, notify);
649 }
Andreas Huber603d7392011-06-30 15:47:02 -0700650
Jason Simmonsd9792ac2011-08-12 13:46:55 -0700651 if (p != NULL) {
652 p->setUID(mUID);
653 }
Andreas Huber603d7392011-06-30 15:47:02 -0700654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 return p;
656}
657
Andreas Huber25643002010-01-28 11:19:57 -0800658status_t MediaPlayerService::Client::setDataSource(
659 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660{
661 LOGV("setDataSource(%s)", url);
662 if (url == NULL)
663 return UNKNOWN_ERROR;
664
Dave Burkefc301b02011-08-30 14:39:17 +0100665 if ((strncmp(url, "http://", 7) == 0) ||
666 (strncmp(url, "https://", 8) == 0) ||
667 (strncmp(url, "rtsp://", 7) == 0)) {
668 if (!checkPermission("android.permission.INTERNET")) {
669 return PERMISSION_DENIED;
670 }
671 }
672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 if (strncmp(url, "content://", 10) == 0) {
674 // get a filedescriptor for the content Uri and
675 // pass it to the setDataSource(fd) method
676
677 String16 url16(url);
678 int fd = android::openContentProviderFile(url16);
679 if (fd < 0)
680 {
681 LOGE("Couldn't open fd for %s", url);
682 return UNKNOWN_ERROR;
683 }
684 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
685 close(fd);
686 return mStatus;
687 } else {
688 player_type playerType = getPlayerType(url);
689 LOGV("player type = %d", playerType);
690
691 // create the right type of player
692 sp<MediaPlayerBase> p = createPlayer(playerType);
693 if (p == NULL) return NO_INIT;
694
695 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700696 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
698 }
699
700 // now set data source
701 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800702 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700703 if (mStatus == NO_ERROR) {
704 mPlayer = p;
705 } else {
706 LOGE(" error: %d", mStatus);
707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 return mStatus;
709 }
710}
711
712status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
713{
714 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
715 struct stat sb;
716 int ret = fstat(fd, &sb);
717 if (ret != 0) {
718 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
719 return UNKNOWN_ERROR;
720 }
721
722 LOGV("st_dev = %llu", sb.st_dev);
723 LOGV("st_mode = %u", sb.st_mode);
724 LOGV("st_uid = %lu", sb.st_uid);
725 LOGV("st_gid = %lu", sb.st_gid);
726 LOGV("st_size = %llu", sb.st_size);
727
728 if (offset >= sb.st_size) {
729 LOGE("offset error");
730 ::close(fd);
731 return UNKNOWN_ERROR;
732 }
733 if (offset + length > sb.st_size) {
734 length = sb.st_size - offset;
735 LOGV("calculated length = %lld", length);
736 }
737
738 player_type playerType = getPlayerType(fd, offset, length);
739 LOGV("player type = %d", playerType);
740
741 // create the right type of player
742 sp<MediaPlayerBase> p = createPlayer(playerType);
743 if (p == NULL) return NO_INIT;
744
745 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700746 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
748 }
749
750 // now set data source
751 mStatus = p->setDataSource(fd, offset, length);
752 if (mStatus == NO_ERROR) mPlayer = p;
Dave Burkefc301b02011-08-30 14:39:17 +0100753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 return mStatus;
755}
756
Andreas Huber52b52cd2010-11-23 11:41:34 -0800757status_t MediaPlayerService::Client::setDataSource(
758 const sp<IStreamSource> &source) {
759 // create the right type of player
Andreas Hubera1587462010-12-15 15:17:42 -0800760 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Huber52b52cd2010-11-23 11:41:34 -0800761
762 if (p == NULL) {
763 return NO_INIT;
764 }
765
766 if (!p->hardwareOutput()) {
767 mAudioOutput = new AudioOutput(mAudioSessionId);
768 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
769 }
770
771 // now set data source
772 mStatus = p->setDataSource(source);
773
774 if (mStatus == OK) {
775 mPlayer = p;
776 }
777
778 return mStatus;
779}
780
Andreas Hubere3c01832010-08-16 08:49:37 -0700781status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782{
783 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
784 sp<MediaPlayerBase> p = getPlayer();
785 if (p == 0) return UNKNOWN_ERROR;
786 return p->setVideoSurface(surface);
787}
788
Glenn Kastencc562a32011-02-08 17:26:17 -0800789status_t MediaPlayerService::Client::setVideoSurfaceTexture(
790 const sp<ISurfaceTexture>& surfaceTexture)
791{
792 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
793 sp<MediaPlayerBase> p = getPlayer();
794 if (p == 0) return UNKNOWN_ERROR;
795 return p->setVideoSurfaceTexture(surfaceTexture);
796}
797
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700798status_t MediaPlayerService::Client::invoke(const Parcel& request,
799 Parcel *reply)
800{
801 sp<MediaPlayerBase> p = getPlayer();
802 if (p == NULL) return UNKNOWN_ERROR;
803 return p->invoke(request, reply);
804}
805
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700806// This call doesn't need to access the native player.
807status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
808{
809 status_t status;
nikobc726922009-07-20 15:07:26 -0700810 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700811
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700812 if (unmarshallFilter(filter, &allow, &status) &&
813 unmarshallFilter(filter, &drop, &status)) {
814 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700815
816 mMetadataAllow = allow;
817 mMetadataDrop = drop;
818 }
819 return status;
820}
821
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700822status_t MediaPlayerService::Client::getMetadata(
823 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700824{
nikobc726922009-07-20 15:07:26 -0700825 sp<MediaPlayerBase> player = getPlayer();
826 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700827
niko89948372009-07-16 16:39:53 -0700828 status_t status;
829 // Placeholder for the return code, updated by the caller.
830 reply->writeInt32(-1);
831
nikobc726922009-07-20 15:07:26 -0700832 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700833
834 // We don't block notifications while we fetch the data. We clear
835 // mMetadataUpdated first so we don't lose notifications happening
836 // during the rest of this call.
837 {
838 Mutex::Autolock lock(mLock);
839 if (update_only) {
niko89948372009-07-16 16:39:53 -0700840 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700841 }
842 mMetadataUpdated.clear();
843 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700844
nikobc726922009-07-20 15:07:26 -0700845 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700846
nikobc726922009-07-20 15:07:26 -0700847 metadata.appendHeader();
848 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700849
850 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700851 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700852 LOGE("getMetadata failed %d", status);
853 return status;
854 }
855
856 // FIXME: Implement filtering on the result. Not critical since
857 // filtering takes place on the update notifications already. This
858 // would be when all the metadata are fetch and a filter is set.
859
niko89948372009-07-16 16:39:53 -0700860 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700861 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700862 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700863}
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865status_t MediaPlayerService::Client::prepareAsync()
866{
867 LOGV("[%d] prepareAsync", mConnId);
868 sp<MediaPlayerBase> p = getPlayer();
869 if (p == 0) return UNKNOWN_ERROR;
870 status_t ret = p->prepareAsync();
871#if CALLBACK_ANTAGONIZER
872 LOGD("start Antagonizer");
873 if (ret == NO_ERROR) mAntagonizer->start();
874#endif
875 return ret;
876}
877
878status_t MediaPlayerService::Client::start()
879{
880 LOGV("[%d] start", mConnId);
881 sp<MediaPlayerBase> p = getPlayer();
882 if (p == 0) return UNKNOWN_ERROR;
883 p->setLooping(mLoop);
884 return p->start();
885}
886
887status_t MediaPlayerService::Client::stop()
888{
889 LOGV("[%d] stop", mConnId);
890 sp<MediaPlayerBase> p = getPlayer();
891 if (p == 0) return UNKNOWN_ERROR;
892 return p->stop();
893}
894
895status_t MediaPlayerService::Client::pause()
896{
897 LOGV("[%d] pause", mConnId);
898 sp<MediaPlayerBase> p = getPlayer();
899 if (p == 0) return UNKNOWN_ERROR;
900 return p->pause();
901}
902
903status_t MediaPlayerService::Client::isPlaying(bool* state)
904{
905 *state = false;
906 sp<MediaPlayerBase> p = getPlayer();
907 if (p == 0) return UNKNOWN_ERROR;
908 *state = p->isPlaying();
909 LOGV("[%d] isPlaying: %d", mConnId, *state);
910 return NO_ERROR;
911}
912
913status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
914{
915 LOGV("getCurrentPosition");
916 sp<MediaPlayerBase> p = getPlayer();
917 if (p == 0) return UNKNOWN_ERROR;
918 status_t ret = p->getCurrentPosition(msec);
919 if (ret == NO_ERROR) {
920 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
921 } else {
922 LOGE("getCurrentPosition returned %d", ret);
923 }
924 return ret;
925}
926
927status_t MediaPlayerService::Client::getDuration(int *msec)
928{
929 LOGV("getDuration");
930 sp<MediaPlayerBase> p = getPlayer();
931 if (p == 0) return UNKNOWN_ERROR;
932 status_t ret = p->getDuration(msec);
933 if (ret == NO_ERROR) {
934 LOGV("[%d] getDuration = %d", mConnId, *msec);
935 } else {
936 LOGE("getDuration returned %d", ret);
937 }
938 return ret;
939}
940
941status_t MediaPlayerService::Client::seekTo(int msec)
942{
943 LOGV("[%d] seekTo(%d)", mConnId, msec);
944 sp<MediaPlayerBase> p = getPlayer();
945 if (p == 0) return UNKNOWN_ERROR;
946 return p->seekTo(msec);
947}
948
949status_t MediaPlayerService::Client::reset()
950{
951 LOGV("[%d] reset", mConnId);
952 sp<MediaPlayerBase> p = getPlayer();
953 if (p == 0) return UNKNOWN_ERROR;
954 return p->reset();
955}
956
957status_t MediaPlayerService::Client::setAudioStreamType(int type)
958{
959 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
960 // TODO: for hardware output, call player instead
961 Mutex::Autolock l(mLock);
962 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
963 return NO_ERROR;
964}
965
966status_t MediaPlayerService::Client::setLooping(int loop)
967{
968 LOGV("[%d] setLooping(%d)", mConnId, loop);
969 mLoop = loop;
970 sp<MediaPlayerBase> p = getPlayer();
971 if (p != 0) return p->setLooping(loop);
972 return NO_ERROR;
973}
974
975status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
976{
977 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
978 // TODO: for hardware output, call player instead
979 Mutex::Autolock l(mLock);
980 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
981 return NO_ERROR;
982}
983
Eric Laurent7070b362010-07-16 07:43:46 -0700984status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
985{
986 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
987 Mutex::Autolock l(mLock);
988 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
989 return NO_ERROR;
990}
991
992status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
993{
994 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
995 Mutex::Autolock l(mLock);
996 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
997 return NO_ERROR;
998}
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700999
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001000status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1001 LOGV("[%d] setParameter(%d)", mConnId, key);
1002 sp<MediaPlayerBase> p = getPlayer();
1003 if (p == 0) return UNKNOWN_ERROR;
1004 return p->setParameter(key, request);
1005}
1006
1007status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1008 LOGV("[%d] getParameter(%d)", mConnId, key);
1009 sp<MediaPlayerBase> p = getPlayer();
1010 if (p == 0) return UNKNOWN_ERROR;
1011 return p->getParameter(key, reply);
1012}
1013
Gloria Wang162ee492011-04-11 17:23:27 -07001014void MediaPlayerService::Client::notify(
1015 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016{
1017 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001018
1019 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001020 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001021 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001022
1023 if(client->shouldDropMetadata(metadata_type)) {
1024 return;
1025 }
1026
1027 // Update the list of metadata that have changed. getMetadata
1028 // also access mMetadataUpdated and clears it.
1029 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001032 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033}
1034
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001035
nikobc726922009-07-20 15:07:26 -07001036bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001037{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001038 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001039
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001040 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001041 return true;
1042 }
1043
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001044 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001045 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001046 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001047 return true;
1048 }
1049}
1050
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001051
nikobc726922009-07-20 15:07:26 -07001052void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001053 Mutex::Autolock lock(mLock);
1054 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1055 mMetadataUpdated.add(metadata_type);
1056 }
1057}
1058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059#if CALLBACK_ANTAGONIZER
1060const int Antagonizer::interval = 10000; // 10 msecs
1061
1062Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1063 mExit(false), mActive(false), mClient(client), mCb(cb)
1064{
1065 createThread(callbackThread, this);
1066}
1067
1068void Antagonizer::kill()
1069{
1070 Mutex::Autolock _l(mLock);
1071 mActive = false;
1072 mExit = true;
1073 mCondition.wait(mLock);
1074}
1075
1076int Antagonizer::callbackThread(void* user)
1077{
1078 LOGD("Antagonizer started");
1079 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1080 while (!p->mExit) {
1081 if (p->mActive) {
1082 LOGV("send event");
1083 p->mCb(p->mClient, 0, 0, 0);
1084 }
1085 usleep(interval);
1086 }
1087 Mutex::Autolock _l(p->mLock);
1088 p->mCondition.signal();
1089 LOGD("Antagonizer stopped");
1090 return 0;
1091}
1092#endif
1093
1094static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1095
1096sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1097{
1098 LOGV("decode(%s)", url);
1099 sp<MemoryBase> mem;
1100 sp<MediaPlayerBase> player;
1101
1102 // Protect our precious, precious DRMd ringtones by only allowing
1103 // decoding of http, but not filesystem paths or content Uris.
1104 // If the application wants to decode those, it should open a
1105 // filedescriptor for them and use that.
1106 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1107 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1108 return mem;
1109 }
1110
1111 player_type playerType = getPlayerType(url);
1112 LOGV("player type = %d", playerType);
1113
1114 // create the right type of player
1115 sp<AudioCache> cache = new AudioCache(url);
1116 player = android::createPlayer(playerType, cache.get(), cache->notify);
1117 if (player == NULL) goto Exit;
1118 if (player->hardwareOutput()) goto Exit;
1119
1120 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1121
1122 // set data source
1123 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1124
1125 LOGV("prepare");
1126 player->prepareAsync();
1127
1128 LOGV("wait for prepare");
1129 if (cache->wait() != NO_ERROR) goto Exit;
1130
1131 LOGV("start");
1132 player->start();
1133
1134 LOGV("wait for playback complete");
1135 if (cache->wait() != NO_ERROR) goto Exit;
1136
1137 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1138 *pSampleRate = cache->sampleRate();
1139 *pNumChannels = cache->channelCount();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001140 *pFormat = (int)cache->format();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1142
1143Exit:
1144 if (player != 0) player->reset();
1145 return mem;
1146}
1147
1148sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1149{
1150 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1151 sp<MemoryBase> mem;
1152 sp<MediaPlayerBase> player;
1153
1154 player_type playerType = getPlayerType(fd, offset, length);
1155 LOGV("player type = %d", playerType);
1156
1157 // create the right type of player
1158 sp<AudioCache> cache = new AudioCache("decode_fd");
1159 player = android::createPlayer(playerType, cache.get(), cache->notify);
1160 if (player == NULL) goto Exit;
1161 if (player->hardwareOutput()) goto Exit;
1162
1163 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1164
1165 // set data source
1166 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1167
1168 LOGV("prepare");
1169 player->prepareAsync();
1170
1171 LOGV("wait for prepare");
1172 if (cache->wait() != NO_ERROR) goto Exit;
1173
1174 LOGV("start");
1175 player->start();
1176
1177 LOGV("wait for playback complete");
1178 if (cache->wait() != NO_ERROR) goto Exit;
1179
1180 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1181 *pSampleRate = cache->sampleRate();
1182 *pNumChannels = cache->channelCount();
1183 *pFormat = cache->format();
1184 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1185
1186Exit:
1187 if (player != 0) player->reset();
1188 ::close(fd);
1189 return mem;
1190}
1191
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193#undef LOG_TAG
1194#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001195MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001196 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001197 mCallbackCookie(NULL),
1198 mSessionId(sessionId) {
1199 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001201 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 mLeftVolume = 1.0;
1203 mRightVolume = 1.0;
1204 mLatency = 0;
1205 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001206 mAuxEffectId = 0;
1207 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 setMinBufferCount();
1209}
1210
1211MediaPlayerService::AudioOutput::~AudioOutput()
1212{
1213 close();
1214}
1215
1216void MediaPlayerService::AudioOutput::setMinBufferCount()
1217{
1218 char value[PROPERTY_VALUE_MAX];
1219 if (property_get("ro.kernel.qemu", value, 0)) {
1220 mIsOnEmulator = true;
1221 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1222 }
1223}
1224
1225bool MediaPlayerService::AudioOutput::isOnEmulator()
1226{
1227 setMinBufferCount();
1228 return mIsOnEmulator;
1229}
1230
1231int MediaPlayerService::AudioOutput::getMinBufferCount()
1232{
1233 setMinBufferCount();
1234 return mMinBufferCount;
1235}
1236
1237ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1238{
1239 if (mTrack == 0) return NO_INIT;
1240 return mTrack->frameCount() * frameSize();
1241}
1242
1243ssize_t MediaPlayerService::AudioOutput::frameCount() const
1244{
1245 if (mTrack == 0) return NO_INIT;
1246 return mTrack->frameCount();
1247}
1248
1249ssize_t MediaPlayerService::AudioOutput::channelCount() const
1250{
1251 if (mTrack == 0) return NO_INIT;
1252 return mTrack->channelCount();
1253}
1254
1255ssize_t MediaPlayerService::AudioOutput::frameSize() const
1256{
1257 if (mTrack == 0) return NO_INIT;
1258 return mTrack->frameSize();
1259}
1260
1261uint32_t MediaPlayerService::AudioOutput::latency () const
1262{
1263 return mLatency;
1264}
1265
1266float MediaPlayerService::AudioOutput::msecsPerFrame() const
1267{
1268 return mMsecsPerFrame;
1269}
1270
Eric Laurent0986e792010-01-19 17:37:09 -08001271status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1272{
1273 if (mTrack == 0) return NO_INIT;
1274 return mTrack->getPosition(position);
1275}
1276
Andreas Hubere46b7be2009-07-14 16:56:47 -07001277status_t MediaPlayerService::AudioOutput::open(
1278 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1279 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001281 mCallback = cb;
1282 mCallbackCookie = cookie;
1283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 // Check argument "bufferCount" against the mininum buffer count
1285 if (bufferCount < mMinBufferCount) {
1286 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1287 bufferCount = mMinBufferCount;
1288
1289 }
Eric Laurent619346f2010-06-21 09:27:30 -07001290 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 if (mTrack) close();
1292 int afSampleRate;
1293 int afFrameCount;
1294 int frameCount;
1295
1296 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1297 return NO_INIT;
1298 }
1299 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1300 return NO_INIT;
1301 }
1302
1303 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001304
1305 AudioTrack *t;
1306 if (mCallback != NULL) {
1307 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001308 mStreamType,
1309 sampleRate,
1310 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001311 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001312 frameCount,
1313 0 /* flags */,
1314 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001315 this,
1316 0,
1317 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001318 } else {
1319 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001320 mStreamType,
1321 sampleRate,
1322 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001323 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001324 frameCount,
1325 0,
1326 NULL,
1327 NULL,
1328 0,
1329 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001330 }
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1333 LOGE("Unable to create audio track");
1334 delete t;
1335 return NO_INIT;
1336 }
1337
1338 LOGV("setVolume");
1339 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001342 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001344
1345 t->setAuxEffectSendLevel(mSendLevel);
1346 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347}
1348
1349void MediaPlayerService::AudioOutput::start()
1350{
1351 LOGV("start");
1352 if (mTrack) {
1353 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001354 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 mTrack->start();
1356 }
1357}
1358
Marco Nelissene274db12010-01-12 09:23:54 -08001359
1360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1362{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001363 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001366 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001367 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001368 return ret;
1369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 return NO_INIT;
1371}
1372
1373void MediaPlayerService::AudioOutput::stop()
1374{
1375 LOGV("stop");
1376 if (mTrack) mTrack->stop();
1377}
1378
1379void MediaPlayerService::AudioOutput::flush()
1380{
1381 LOGV("flush");
1382 if (mTrack) mTrack->flush();
1383}
1384
1385void MediaPlayerService::AudioOutput::pause()
1386{
1387 LOGV("pause");
1388 if (mTrack) mTrack->pause();
1389}
1390
1391void MediaPlayerService::AudioOutput::close()
1392{
1393 LOGV("close");
1394 delete mTrack;
1395 mTrack = 0;
1396}
1397
1398void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1399{
1400 LOGV("setVolume(%f, %f)", left, right);
1401 mLeftVolume = left;
1402 mRightVolume = right;
1403 if (mTrack) {
1404 mTrack->setVolume(left, right);
1405 }
1406}
1407
Eric Laurent7070b362010-07-16 07:43:46 -07001408status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1409{
1410 LOGV("setAuxEffectSendLevel(%f)", level);
1411 mSendLevel = level;
1412 if (mTrack) {
1413 return mTrack->setAuxEffectSendLevel(level);
1414 }
1415 return NO_ERROR;
1416}
1417
1418status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1419{
1420 LOGV("attachAuxEffect(%d)", effectId);
1421 mAuxEffectId = effectId;
1422 if (mTrack) {
1423 return mTrack->attachAuxEffect(effectId);
1424 }
1425 return NO_ERROR;
1426}
1427
Andreas Hubere46b7be2009-07-14 16:56:47 -07001428// static
1429void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastene46a86f2011-06-01 15:20:35 -07001430 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001431 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001432 if (event != AudioTrack::EVENT_MORE_DATA) {
1433 return;
1434 }
1435
1436 AudioOutput *me = (AudioOutput *)cookie;
1437 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1438
Andreas Huber6ed937e2010-02-09 16:59:18 -08001439 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001440 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001441
Andreas Huberc6e3b272011-04-04 11:43:40 -07001442 if (actualSize == 0 && buffer->size > 0) {
1443 // We've reached EOS but the audio track is not stopped yet,
1444 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001445
Andreas Huberc6e3b272011-04-04 11:43:40 -07001446 memset(buffer->raw, 0, buffer->size);
1447 actualSize = buffer->size;
1448 }
1449
1450 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001451}
1452
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001453int MediaPlayerService::AudioOutput::getSessionId()
1454{
1455 return mSessionId;
1456}
1457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458#undef LOG_TAG
1459#define LOG_TAG "AudioCache"
1460MediaPlayerService::AudioCache::AudioCache(const char* name) :
1461 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1462 mError(NO_ERROR), mCommandComplete(false)
1463{
1464 // create ashmem heap
1465 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1466}
1467
1468uint32_t MediaPlayerService::AudioCache::latency () const
1469{
1470 return 0;
1471}
1472
1473float MediaPlayerService::AudioCache::msecsPerFrame() const
1474{
1475 return mMsecsPerFrame;
1476}
1477
Eric Laurent0986e792010-01-19 17:37:09 -08001478status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1479{
1480 if (position == 0) return BAD_VALUE;
1481 *position = mSize;
1482 return NO_ERROR;
1483}
1484
Andreas Huber6ed937e2010-02-09 16:59:18 -08001485////////////////////////////////////////////////////////////////////////////////
1486
1487struct CallbackThread : public Thread {
1488 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1489 MediaPlayerBase::AudioSink::AudioCallback cb,
1490 void *cookie);
1491
1492protected:
1493 virtual ~CallbackThread();
1494
1495 virtual bool threadLoop();
1496
1497private:
1498 wp<MediaPlayerBase::AudioSink> mSink;
1499 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1500 void *mCookie;
1501 void *mBuffer;
1502 size_t mBufferSize;
1503
1504 CallbackThread(const CallbackThread &);
1505 CallbackThread &operator=(const CallbackThread &);
1506};
1507
1508CallbackThread::CallbackThread(
1509 const wp<MediaPlayerBase::AudioSink> &sink,
1510 MediaPlayerBase::AudioSink::AudioCallback cb,
1511 void *cookie)
1512 : mSink(sink),
1513 mCallback(cb),
1514 mCookie(cookie),
1515 mBuffer(NULL),
1516 mBufferSize(0) {
1517}
1518
1519CallbackThread::~CallbackThread() {
1520 if (mBuffer) {
1521 free(mBuffer);
1522 mBuffer = NULL;
1523 }
1524}
1525
1526bool CallbackThread::threadLoop() {
1527 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1528 if (sink == NULL) {
1529 return false;
1530 }
1531
1532 if (mBuffer == NULL) {
1533 mBufferSize = sink->bufferSize();
1534 mBuffer = malloc(mBufferSize);
1535 }
1536
1537 size_t actualSize =
1538 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1539
1540 if (actualSize > 0) {
1541 sink->write(mBuffer, actualSize);
1542 }
1543
1544 return true;
1545}
1546
1547////////////////////////////////////////////////////////////////////////////////
1548
Andreas Hubere46b7be2009-07-14 16:56:47 -07001549status_t MediaPlayerService::AudioCache::open(
1550 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1551 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552{
Dave Sparks14f89402009-12-09 20:20:26 -08001553 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001554 if (mHeap->getHeapID() < 0) {
1555 return NO_INIT;
1556 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 mSampleRate = sampleRate;
1559 mChannelCount = (uint16_t)channelCount;
1560 mFormat = (uint16_t)format;
1561 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001562
1563 if (cb != NULL) {
1564 mCallbackThread = new CallbackThread(this, cb, cookie);
1565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 return NO_ERROR;
1567}
1568
Andreas Huber6ed937e2010-02-09 16:59:18 -08001569void MediaPlayerService::AudioCache::start() {
1570 if (mCallbackThread != NULL) {
1571 mCallbackThread->run("AudioCache callback");
1572 }
1573}
1574
1575void MediaPlayerService::AudioCache::stop() {
1576 if (mCallbackThread != NULL) {
1577 mCallbackThread->requestExitAndWait();
1578 }
1579}
1580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1582{
1583 LOGV("write(%p, %u)", buffer, size);
1584 if ((buffer == 0) || (size == 0)) return size;
1585
1586 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1587 if (p == NULL) return NO_INIT;
1588 p += mSize;
1589 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1590 if (mSize + size > mHeap->getSize()) {
1591 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1592 size = mHeap->getSize() - mSize;
1593 }
1594 memcpy(p, buffer, size);
1595 mSize += size;
1596 return size;
1597}
1598
1599// call with lock held
1600status_t MediaPlayerService::AudioCache::wait()
1601{
1602 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001603 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 mSignal.wait(mLock);
1605 }
1606 mCommandComplete = false;
1607
1608 if (mError == NO_ERROR) {
1609 LOGV("wait - success");
1610 } else {
1611 LOGV("wait - error");
1612 }
1613 return mError;
1614}
1615
Gloria Wang162ee492011-04-11 17:23:27 -07001616void MediaPlayerService::AudioCache::notify(
1617 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618{
1619 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1620 AudioCache* p = static_cast<AudioCache*>(cookie);
1621
1622 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001623 switch (msg)
1624 {
1625 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 LOGE("Error %d, %d occurred", ext1, ext2);
1627 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001628 break;
1629 case MEDIA_PREPARED:
1630 LOGV("prepared");
1631 break;
1632 case MEDIA_PLAYBACK_COMPLETE:
1633 LOGV("playback complete");
1634 break;
1635 default:
1636 LOGV("ignored");
1637 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639
1640 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001641 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 p->mCommandComplete = true;
1643 p->mSignal.signal();
1644}
1645
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001646int MediaPlayerService::AudioCache::getSessionId()
1647{
1648 return 0;
1649}
1650
Gloria Wangd211f412011-02-19 18:37:57 -08001651void MediaPlayerService::addBatteryData(uint32_t params)
1652{
1653 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001654
1655 int32_t time = systemTime() / 1000000L;
1656
1657 // change audio output devices. This notification comes from AudioFlinger
1658 if ((params & kBatteryDataSpeakerOn)
1659 || (params & kBatteryDataOtherAudioDeviceOn)) {
1660
1661 int deviceOn[NUM_AUDIO_DEVICES];
1662 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1663 deviceOn[i] = 0;
1664 }
1665
1666 if ((params & kBatteryDataSpeakerOn)
1667 && (params & kBatteryDataOtherAudioDeviceOn)) {
1668 deviceOn[SPEAKER_AND_OTHER] = 1;
1669 } else if (params & kBatteryDataSpeakerOn) {
1670 deviceOn[SPEAKER] = 1;
1671 } else {
1672 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1673 }
1674
1675 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1676 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1677
1678 if (mBatteryAudio.refCount > 0) { // if playing audio
1679 if (!deviceOn[i]) {
1680 mBatteryAudio.lastTime[i] += time;
1681 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1682 mBatteryAudio.lastTime[i] = 0;
1683 } else {
1684 mBatteryAudio.lastTime[i] = 0 - time;
1685 }
1686 }
1687
1688 mBatteryAudio.deviceOn[i] = deviceOn[i];
1689 }
1690 }
1691 return;
1692 }
1693
1694 // an sudio stream is started
1695 if (params & kBatteryDataAudioFlingerStart) {
1696 // record the start time only if currently no other audio
1697 // is being played
1698 if (mBatteryAudio.refCount == 0) {
1699 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1700 if (mBatteryAudio.deviceOn[i]) {
1701 mBatteryAudio.lastTime[i] -= time;
1702 }
1703 }
1704 }
1705
1706 mBatteryAudio.refCount ++;
1707 return;
1708
1709 } else if (params & kBatteryDataAudioFlingerStop) {
1710 if (mBatteryAudio.refCount <= 0) {
1711 LOGW("Battery track warning: refCount is <= 0");
1712 return;
1713 }
1714
1715 // record the stop time only if currently this is the only
1716 // audio being played
1717 if (mBatteryAudio.refCount == 1) {
1718 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1719 if (mBatteryAudio.deviceOn[i]) {
1720 mBatteryAudio.lastTime[i] += time;
1721 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1722 mBatteryAudio.lastTime[i] = 0;
1723 }
1724 }
1725 }
1726
1727 mBatteryAudio.refCount --;
1728 return;
1729 }
1730
Gloria Wangd211f412011-02-19 18:37:57 -08001731 int uid = IPCThreadState::self()->getCallingUid();
1732 if (uid == AID_MEDIA) {
1733 return;
1734 }
1735 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001736
1737 if (index < 0) { // create a new entry for this UID
1738 BatteryUsageInfo info;
1739 info.audioTotalTime = 0;
1740 info.videoTotalTime = 0;
1741 info.audioLastTime = 0;
1742 info.videoLastTime = 0;
1743 info.refCount = 0;
1744
Gloria Wang9b3f1522011-02-24 14:51:45 -08001745 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1746 LOGE("Battery track error: no memory for new app");
1747 return;
1748 }
Gloria Wangd211f412011-02-19 18:37:57 -08001749 }
1750
1751 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1752
1753 if (params & kBatteryDataCodecStarted) {
1754 if (params & kBatteryDataTrackAudio) {
1755 info.audioLastTime -= time;
1756 info.refCount ++;
1757 }
1758 if (params & kBatteryDataTrackVideo) {
1759 info.videoLastTime -= time;
1760 info.refCount ++;
1761 }
1762 } else {
1763 if (info.refCount == 0) {
1764 LOGW("Battery track warning: refCount is already 0");
1765 return;
1766 } else if (info.refCount < 0) {
1767 LOGE("Battery track error: refCount < 0");
1768 mBatteryData.removeItem(uid);
1769 return;
1770 }
1771
1772 if (params & kBatteryDataTrackAudio) {
1773 info.audioLastTime += time;
1774 info.refCount --;
1775 }
1776 if (params & kBatteryDataTrackVideo) {
1777 info.videoLastTime += time;
1778 info.refCount --;
1779 }
1780
1781 // no stream is being played by this UID
1782 if (info.refCount == 0) {
1783 info.audioTotalTime += info.audioLastTime;
1784 info.audioLastTime = 0;
1785 info.videoTotalTime += info.videoLastTime;
1786 info.videoLastTime = 0;
1787 }
1788 }
1789}
1790
1791status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1792 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001793
1794 // audio output devices usage
1795 int32_t time = systemTime() / 1000000L; //in ms
1796 int32_t totalTime;
1797
1798 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1799 totalTime = mBatteryAudio.totalTime[i];
1800
1801 if (mBatteryAudio.deviceOn[i]
1802 && (mBatteryAudio.lastTime[i] != 0)) {
1803 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1804 totalTime += tmpTime;
1805 }
1806
1807 reply->writeInt32(totalTime);
1808 // reset the total time
1809 mBatteryAudio.totalTime[i] = 0;
1810 }
1811
1812 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001813 BatteryUsageInfo info;
1814 int size = mBatteryData.size();
1815
1816 reply->writeInt32(size);
1817 int i = 0;
1818
1819 while (i < size) {
1820 info = mBatteryData.valueAt(i);
1821
1822 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1823 reply->writeInt32(info.audioTotalTime);
1824 reply->writeInt32(info.videoTotalTime);
1825
1826 info.audioTotalTime = 0;
1827 info.videoTotalTime = 0;
1828
1829 // remove the UID entry where no stream is being played
1830 if (info.refCount <= 0) {
1831 mBatteryData.removeItemsAt(i);
1832 size --;
1833 i --;
1834 }
1835 i++;
1836 }
1837 return NO_ERROR;
1838}
nikobc726922009-07-20 15:07:26 -07001839} // namespace android