blob: b5eef94a4c00d101f9027eac20a129e06e09d2c7 [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>
Eric Laurent9cb839a2011-09-27 09:48:56 -070055#include <media/stagefright/MediaErrors.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056
Dima Zavin64760242011-05-11 14:15:23 -070057#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070058
Gloria Wang7cf180c2011-02-19 18:37:57 -080059#include <private/android_filesystem_config.h>
60
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080061#include "MediaRecorderClient.h"
62#include "MediaPlayerService.h"
63#include "MetadataRetrieverClient.h"
64
65#include "MidiFile.h"
Nicolas Catania14d27472009-07-13 14:37:49 -070066#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070067#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080068#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070069
Andreas Huber20111aa2009-07-14 16:56:47 -070070#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070071
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070072namespace {
nikoa64c8c72009-07-20 15:07:26 -070073using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070074using android::status_t;
75using android::OK;
76using android::BAD_VALUE;
77using android::NOT_ENOUGH_DATA;
78using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070079
80// Max number of entries in the filter.
81const int kMaxFilterSize = 64; // I pulled that out of thin air.
82
nikoa64c8c72009-07-20 15:07:26 -070083// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070084
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070085
86// Unmarshall a filter from a Parcel.
87// Filter format in a parcel:
88//
89// 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
90// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
91// | number of entries (n) |
92// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
93// | metadata type 1 |
94// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
95// | metadata type 2 |
96// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
97// ....
98// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99// | metadata type n |
100// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101//
102// @param p Parcel that should start with a filter.
103// @param[out] filter On exit contains the list of metadata type to be
104// filtered.
105// @param[out] status On exit contains the status code to be returned.
106// @return true if the parcel starts with a valid filter.
107bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700108 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700109 status_t *status)
110{
Nicolas Catania48290382009-07-10 13:53:06 -0700111 int32_t val;
112 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700113 {
114 LOGE("Failed to read filter's length");
115 *status = NOT_ENOUGH_DATA;
116 return false;
117 }
118
Nicolas Catania48290382009-07-10 13:53:06 -0700119 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700120 {
Nicolas Catania48290382009-07-10 13:53:06 -0700121 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700122 *status = BAD_VALUE;
123 return false;
124 }
125
Nicolas Catania48290382009-07-10 13:53:06 -0700126 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127
128 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700129 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130
nikoa64c8c72009-07-20 15:07:26 -0700131 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132
Nicolas Catania48290382009-07-10 13:53:06 -0700133
134 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 {
Nicolas Catania48290382009-07-10 13:53:06 -0700136 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 *status = NOT_ENOUGH_DATA;
138 return false;
139 }
140
nikoa64c8c72009-07-20 15:07:26 -0700141 const Metadata::Type *data =
142 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143
Nicolas Catania48290382009-07-10 13:53:06 -0700144 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145 {
146 LOGE("Filter had no data");
147 *status = BAD_VALUE;
148 return false;
149 }
150
151 // TODO: The stl impl of vector would be more efficient here
152 // because it degenerates into a memcpy on pod types. Try to
153 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700154 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 {
Nicolas Catania48290382009-07-10 13:53:06 -0700156 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157 ++data;
158 }
159 *status = OK;
160 return true;
161}
162
Nicolas Catania48290382009-07-10 13:53:06 -0700163// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164// @param val To be searched.
165// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700166bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700167{
168 // Deal with empty and ANY right away
169 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700170 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171
Nicolas Catania48290382009-07-10 13:53:06 -0700172 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173}
174
175} // anonymous namespace
176
177
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800178namespace android {
179
Dave Burked681bbb2011-08-30 14:39:17 +0100180static bool checkPermission(const char* permissionString) {
181#ifndef HAVE_ANDROID_OS
182 return true;
183#endif
184 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
185 bool ok = checkCallingPermission(String16(permissionString));
186 if (!ok) LOGE("Request requires %s", permissionString);
187 return ok;
188}
189
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800190// TODO: Temp hack until we can register players
191typedef struct {
192 const char *extension;
193 const player_type playertype;
194} extmap;
195extmap FILE_EXTS [] = {
196 {".mid", SONIVOX_PLAYER},
197 {".midi", SONIVOX_PLAYER},
198 {".smf", SONIVOX_PLAYER},
199 {".xmf", SONIVOX_PLAYER},
200 {".imy", SONIVOX_PLAYER},
201 {".rtttl", SONIVOX_PLAYER},
202 {".rtx", SONIVOX_PLAYER},
203 {".ota", SONIVOX_PLAYER},
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204};
205
206// 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 -0800207/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
208/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
209
210void MediaPlayerService::instantiate() {
211 defaultServiceManager()->addService(
212 String16("media.player"), new MediaPlayerService());
213}
214
215MediaPlayerService::MediaPlayerService()
216{
217 LOGV("MediaPlayerService created");
218 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800219
220 mBatteryAudio.refCount = 0;
221 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
222 mBatteryAudio.deviceOn[i] = 0;
223 mBatteryAudio.lastTime[i] = 0;
224 mBatteryAudio.totalTime[i] = 0;
225 }
226 // speaker is on by default
227 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800228}
229
230MediaPlayerService::~MediaPlayerService()
231{
232 LOGV("MediaPlayerService destroyed");
233}
234
235sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
236{
Gloria Wangdac6a312009-10-29 15:46:37 -0700237 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
238 wp<MediaRecorderClient> w = recorder;
239 Mutex::Autolock lock(mLock);
240 mMediaRecorderClients.add(w);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800241 LOGV("Create new media recorder client from pid %d", pid);
242 return recorder;
243}
244
Gloria Wangdac6a312009-10-29 15:46:37 -0700245void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
246{
247 Mutex::Autolock lock(mLock);
248 mMediaRecorderClients.remove(client);
249 LOGV("Delete media recorder client");
250}
251
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
253{
254 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
255 LOGV("Create new media retriever from pid %d", pid);
256 return retriever;
257}
258
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100260 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800261{
262 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700263
264 sp<Client> c = new Client(
265 this, pid, connId, client, audioSessionId,
266 IPCThreadState::self()->getCallingUid());
267
Dave Burked681bbb2011-08-30 14:39:17 +0100268 LOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
269 IPCThreadState::self()->getCallingUid());
270
271 wp<Client> w = c;
272 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800273 Mutex::Autolock lock(mLock);
274 mClients.add(w);
275 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800276 return c;
277}
278
Andreas Huber318ad9c2009-10-15 13:46:54 -0700279sp<IOMX> MediaPlayerService::getOMX() {
280 Mutex::Autolock autoLock(mLock);
281
282 if (mOMX.get() == NULL) {
283 mOMX = new OMX;
284 }
285
286 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700287}
288
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800289status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
290{
291 const size_t SIZE = 256;
292 char buffer[SIZE];
293 String8 result;
294
295 result.append(" AudioCache\n");
296 if (mHeap != 0) {
297 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
298 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
299 result.append(buffer);
300 }
301 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
302 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
303 result.append(buffer);
304 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
305 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
306 result.append(buffer);
307 ::write(fd, result.string(), result.size());
308 return NO_ERROR;
309}
310
311status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
312{
313 const size_t SIZE = 256;
314 char buffer[SIZE];
315 String8 result;
316
317 result.append(" AudioOutput\n");
318 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
319 mStreamType, mLeftVolume, mRightVolume);
320 result.append(buffer);
321 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
322 mMsecsPerFrame, mLatency);
323 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700324 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
325 mAuxEffectId, mSendLevel);
326 result.append(buffer);
327
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328 ::write(fd, result.string(), result.size());
329 if (mTrack != 0) {
330 mTrack->dump(fd, args);
331 }
332 return NO_ERROR;
333}
334
335status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
336{
337 const size_t SIZE = 256;
338 char buffer[SIZE];
339 String8 result;
340 result.append(" Client\n");
341 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
342 mPid, mConnId, mStatus, mLoop?"true": "false");
343 result.append(buffer);
344 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700345 if (mPlayer != NULL) {
346 mPlayer->dump(fd, args);
347 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800348 if (mAudioOutput != 0) {
349 mAudioOutput->dump(fd, args);
350 }
351 write(fd, "\n", 1);
352 return NO_ERROR;
353}
354
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800355status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
356{
357 const size_t SIZE = 256;
358 char buffer[SIZE];
359 String8 result;
360 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
361 snprintf(buffer, SIZE, "Permission Denial: "
362 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
363 IPCThreadState::self()->getCallingPid(),
364 IPCThreadState::self()->getCallingUid());
365 result.append(buffer);
366 } else {
367 Mutex::Autolock lock(mLock);
368 for (int i = 0, n = mClients.size(); i < n; ++i) {
369 sp<Client> c = mClients[i].promote();
370 if (c != 0) c->dump(fd, args);
371 }
James Dongb9141222010-07-08 11:16:11 -0700372 if (mMediaRecorderClients.size() == 0) {
373 result.append(" No media recorder client\n\n");
374 } else {
375 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
376 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
377 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
378 result.append(buffer);
379 write(fd, result.string(), result.size());
380 result = "\n";
381 c->dump(fd, args);
382 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700383 }
384
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800385 result.append(" Files opened and/or mapped:\n");
Glenn Kasten0512ab52011-05-04 17:58:57 -0700386 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800387 FILE *f = fopen(buffer, "r");
388 if (f) {
389 while (!feof(f)) {
390 fgets(buffer, SIZE, f);
Dave Sparks02fa8342010-09-27 16:55:18 -0700391 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800392 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700393 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800394 strstr(buffer, " /system/media/")) {
395 result.append(" ");
396 result.append(buffer);
397 }
398 }
399 fclose(f);
400 } else {
401 result.append("couldn't open ");
402 result.append(buffer);
403 result.append("\n");
404 }
405
Glenn Kasten0512ab52011-05-04 17:58:57 -0700406 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407 DIR *d = opendir(buffer);
408 if (d) {
409 struct dirent *ent;
410 while((ent = readdir(d)) != NULL) {
411 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten0512ab52011-05-04 17:58:57 -0700412 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800413 struct stat s;
414 if (lstat(buffer, &s) == 0) {
415 if ((s.st_mode & S_IFMT) == S_IFLNK) {
416 char linkto[256];
417 int len = readlink(buffer, linkto, sizeof(linkto));
418 if(len > 0) {
419 if(len > 255) {
420 linkto[252] = '.';
421 linkto[253] = '.';
422 linkto[254] = '.';
423 linkto[255] = 0;
424 } else {
425 linkto[len] = 0;
426 }
Dave Sparks02fa8342010-09-27 16:55:18 -0700427 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700429 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430 strstr(linkto, "/system/media/") == linkto) {
431 result.append(" ");
432 result.append(buffer);
433 result.append(" -> ");
434 result.append(linkto);
435 result.append("\n");
436 }
437 }
438 } else {
439 result.append(" unexpected type for ");
440 result.append(buffer);
441 result.append("\n");
442 }
443 }
444 }
445 }
446 closedir(d);
447 } else {
448 result.append("couldn't open ");
449 result.append(buffer);
450 result.append("\n");
451 }
452
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 bool dumpMem = false;
454 for (size_t i = 0; i < args.size(); i++) {
455 if (args[i] == String16("-m")) {
456 dumpMem = true;
457 }
458 }
459 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700460 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 }
463 write(fd, result.string(), result.size());
464 return NO_ERROR;
465}
466
467void MediaPlayerService::removeClient(wp<Client> client)
468{
469 Mutex::Autolock lock(mLock);
470 mClients.remove(client);
471}
472
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700473MediaPlayerService::Client::Client(
474 const sp<MediaPlayerService>& service, pid_t pid,
475 int32_t connId, const sp<IMediaPlayerClient>& client,
476 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477{
478 LOGV("Client(%d) constructor", connId);
479 mPid = pid;
480 mConnId = connId;
481 mService = service;
482 mClient = client;
483 mLoop = false;
484 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700485 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700486 mUID = uid;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700487
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488#if CALLBACK_ANTAGONIZER
489 LOGD("create Antagonizer");
490 mAntagonizer = new Antagonizer(notify, this);
491#endif
492}
493
494MediaPlayerService::Client::~Client()
495{
496 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
497 mAudioOutput.clear();
498 wp<Client> client(this);
499 disconnect();
500 mService->removeClient(client);
501}
502
503void MediaPlayerService::Client::disconnect()
504{
505 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
506 // grab local reference and clear main reference to prevent future
507 // access to object
508 sp<MediaPlayerBase> p;
509 {
510 Mutex::Autolock l(mLock);
511 p = mPlayer;
512 }
Dave Sparks795fa582009-03-24 17:57:12 -0700513 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700514
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800515 mPlayer.clear();
516
517 // clear the notification to prevent callbacks to dead client
518 // and reset the player. We assume the player will serialize
519 // access to itself if necessary.
520 if (p != 0) {
521 p->setNotifyCallback(0, 0);
522#if CALLBACK_ANTAGONIZER
523 LOGD("kill Antagonizer");
524 mAntagonizer->kill();
525#endif
526 p->reset();
527 }
528
529 IPCThreadState::self()->flushCommands();
530}
531
Andreas Huber47f59cf2009-08-07 09:30:32 -0700532static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700533 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700534}
535
James Dong148c1a22009-09-06 14:29:45 -0700536player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537{
538 char buf[20];
539 lseek(fd, offset, SEEK_SET);
540 read(fd, buf, sizeof(buf));
541 lseek(fd, offset, SEEK_SET);
542
543 long ident = *((long*)buf);
544
545 // Ogg vorbis?
546 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700547 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548
549 // Some kind of MIDI?
550 EAS_DATA_HANDLE easdata;
551 if (EAS_Init(&easdata) == EAS_SUCCESS) {
552 EAS_FILE locator;
553 locator.path = NULL;
554 locator.fd = fd;
555 locator.offset = offset;
556 locator.length = length;
557 EAS_HANDLE eashandle;
558 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
559 EAS_CloseFile(easdata, eashandle);
560 EAS_Shutdown(easdata);
561 return SONIVOX_PLAYER;
562 }
563 EAS_Shutdown(easdata);
564 }
565
Andreas Huber47f59cf2009-08-07 09:30:32 -0700566 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567}
568
James Dong148c1a22009-09-06 14:29:45 -0700569player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800570{
Nicolas Catania14d27472009-07-13 14:37:49 -0700571 if (TestPlayerStub::canBeUsed(url)) {
572 return TEST_PLAYER;
573 }
574
Andreas Huber0a73d812011-03-21 16:28:04 -0700575 if (!strncasecmp("http://", url, 7)
576 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-02-16 09:05:38 -0800577 size_t len = strlen(url);
578 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
579 return NU_PLAYER;
580 }
Andreas Huber5bc087c2010-12-23 10:27:40 -0800581
Andreas Hubered8d14f2011-02-16 09:05:38 -0800582 if (strstr(url,"m3u8")) {
583 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800584 }
585 }
586
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 // use MidiFile for MIDI extensions
588 int lenURL = strlen(url);
589 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
590 int len = strlen(FILE_EXTS[i].extension);
591 int start = lenURL - len;
592 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900593 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700594 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595 }
596 }
597 }
598
Andreas Huber47f59cf2009-08-07 09:30:32 -0700599 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600}
601
602static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
603 notify_callback_f notifyFunc)
604{
605 sp<MediaPlayerBase> p;
606 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 case SONIVOX_PLAYER:
608 LOGV(" create MidiFile");
609 p = new MidiFile();
610 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700611 case STAGEFRIGHT_PLAYER:
612 LOGV(" create StagefrightPlayer");
613 p = new StagefrightPlayer;
614 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800615 case NU_PLAYER:
616 LOGV(" create NuPlayer");
617 p = new NuPlayerDriver;
618 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700619 case TEST_PLAYER:
620 LOGV("Create Test Player stub");
621 p = new TestPlayerStub();
622 break;
James Dong30d713a2010-11-10 18:42:40 -0800623 default:
624 LOGE("Unknown player type: %d", playerType);
625 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 }
627 if (p != NULL) {
628 if (p->initCheck() == NO_ERROR) {
629 p->setNotifyCallback(cookie, notifyFunc);
630 } else {
631 p.clear();
632 }
633 }
634 if (p == NULL) {
635 LOGE("Failed to create player object");
636 }
637 return p;
638}
639
640sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
641{
642 // determine if we have the right player type
643 sp<MediaPlayerBase> p = mPlayer;
644 if ((p != NULL) && (p->playerType() != playerType)) {
645 LOGV("delete player");
646 p.clear();
647 }
648 if (p == NULL) {
649 p = android::createPlayer(playerType, this, notify);
650 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700651
Jason Simmonsdb29e522011-08-12 13:46:55 -0700652 if (p != NULL) {
653 p->setUID(mUID);
654 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700655
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 return p;
657}
658
Andreas Huber2db84552010-01-28 11:19:57 -0800659status_t MediaPlayerService::Client::setDataSource(
660 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661{
662 LOGV("setDataSource(%s)", url);
663 if (url == NULL)
664 return UNKNOWN_ERROR;
665
Dave Burked681bbb2011-08-30 14:39:17 +0100666 if ((strncmp(url, "http://", 7) == 0) ||
667 (strncmp(url, "https://", 8) == 0) ||
668 (strncmp(url, "rtsp://", 7) == 0)) {
669 if (!checkPermission("android.permission.INTERNET")) {
670 return PERMISSION_DENIED;
671 }
672 }
673
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800674 if (strncmp(url, "content://", 10) == 0) {
675 // get a filedescriptor for the content Uri and
676 // pass it to the setDataSource(fd) method
677
678 String16 url16(url);
679 int fd = android::openContentProviderFile(url16);
680 if (fd < 0)
681 {
682 LOGE("Couldn't open fd for %s", url);
683 return UNKNOWN_ERROR;
684 }
685 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
686 close(fd);
687 return mStatus;
688 } else {
689 player_type playerType = getPlayerType(url);
690 LOGV("player type = %d", playerType);
691
692 // create the right type of player
693 sp<MediaPlayerBase> p = createPlayer(playerType);
694 if (p == NULL) return NO_INIT;
695
696 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700697 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800698 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
699 }
700
701 // now set data source
702 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800703 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700704 if (mStatus == NO_ERROR) {
705 mPlayer = p;
706 } else {
707 LOGE(" error: %d", mStatus);
708 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800709 return mStatus;
710 }
711}
712
713status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
714{
715 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
716 struct stat sb;
717 int ret = fstat(fd, &sb);
718 if (ret != 0) {
719 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
720 return UNKNOWN_ERROR;
721 }
722
723 LOGV("st_dev = %llu", sb.st_dev);
724 LOGV("st_mode = %u", sb.st_mode);
725 LOGV("st_uid = %lu", sb.st_uid);
726 LOGV("st_gid = %lu", sb.st_gid);
727 LOGV("st_size = %llu", sb.st_size);
728
729 if (offset >= sb.st_size) {
730 LOGE("offset error");
731 ::close(fd);
732 return UNKNOWN_ERROR;
733 }
734 if (offset + length > sb.st_size) {
735 length = sb.st_size - offset;
736 LOGV("calculated length = %lld", length);
737 }
738
739 player_type playerType = getPlayerType(fd, offset, length);
740 LOGV("player type = %d", playerType);
741
742 // create the right type of player
743 sp<MediaPlayerBase> p = createPlayer(playerType);
744 if (p == NULL) return NO_INIT;
745
746 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700747 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
749 }
750
751 // now set data source
752 mStatus = p->setDataSource(fd, offset, length);
753 if (mStatus == NO_ERROR) mPlayer = p;
Dave Burked681bbb2011-08-30 14:39:17 +0100754
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800755 return mStatus;
756}
757
Andreas Hubere2b10282010-11-23 11:41:34 -0800758status_t MediaPlayerService::Client::setDataSource(
759 const sp<IStreamSource> &source) {
760 // create the right type of player
Andreas Huberf9334412010-12-15 15:17:42 -0800761 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Hubere2b10282010-11-23 11:41:34 -0800762
763 if (p == NULL) {
764 return NO_INIT;
765 }
766
767 if (!p->hardwareOutput()) {
768 mAudioOutput = new AudioOutput(mAudioSessionId);
769 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
770 }
771
772 // now set data source
773 mStatus = p->setDataSource(source);
774
775 if (mStatus == OK) {
776 mPlayer = p;
777 }
778
779 return mStatus;
780}
781
Andreas Huber5daeb122010-08-16 08:49:37 -0700782status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783{
784 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
785 sp<MediaPlayerBase> p = getPlayer();
786 if (p == 0) return UNKNOWN_ERROR;
787 return p->setVideoSurface(surface);
788}
789
Glenn Kasten11731182011-02-08 17:26:17 -0800790status_t MediaPlayerService::Client::setVideoSurfaceTexture(
791 const sp<ISurfaceTexture>& surfaceTexture)
792{
793 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
794 sp<MediaPlayerBase> p = getPlayer();
795 if (p == 0) return UNKNOWN_ERROR;
796 return p->setVideoSurfaceTexture(surfaceTexture);
797}
798
Nicolas Catania1d187f12009-05-12 23:25:55 -0700799status_t MediaPlayerService::Client::invoke(const Parcel& request,
800 Parcel *reply)
801{
802 sp<MediaPlayerBase> p = getPlayer();
803 if (p == NULL) return UNKNOWN_ERROR;
804 return p->invoke(request, reply);
805}
806
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700807// This call doesn't need to access the native player.
808status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
809{
810 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700811 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700812
Nicolas Catania48290382009-07-10 13:53:06 -0700813 if (unmarshallFilter(filter, &allow, &status) &&
814 unmarshallFilter(filter, &drop, &status)) {
815 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700816
817 mMetadataAllow = allow;
818 mMetadataDrop = drop;
819 }
820 return status;
821}
822
Nicolas Catania48290382009-07-10 13:53:06 -0700823status_t MediaPlayerService::Client::getMetadata(
824 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700825{
nikoa64c8c72009-07-20 15:07:26 -0700826 sp<MediaPlayerBase> player = getPlayer();
827 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700828
nikod608a812009-07-16 16:39:53 -0700829 status_t status;
830 // Placeholder for the return code, updated by the caller.
831 reply->writeInt32(-1);
832
nikoa64c8c72009-07-20 15:07:26 -0700833 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700834
835 // We don't block notifications while we fetch the data. We clear
836 // mMetadataUpdated first so we don't lose notifications happening
837 // during the rest of this call.
838 {
839 Mutex::Autolock lock(mLock);
840 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700841 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700842 }
843 mMetadataUpdated.clear();
844 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700845
nikoa64c8c72009-07-20 15:07:26 -0700846 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700847
nikoa64c8c72009-07-20 15:07:26 -0700848 metadata.appendHeader();
849 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700850
851 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700852 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700853 LOGE("getMetadata failed %d", status);
854 return status;
855 }
856
857 // FIXME: Implement filtering on the result. Not critical since
858 // filtering takes place on the update notifications already. This
859 // would be when all the metadata are fetch and a filter is set.
860
nikod608a812009-07-16 16:39:53 -0700861 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700862 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700863 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700864}
865
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800866status_t MediaPlayerService::Client::prepareAsync()
867{
868 LOGV("[%d] prepareAsync", mConnId);
869 sp<MediaPlayerBase> p = getPlayer();
870 if (p == 0) return UNKNOWN_ERROR;
871 status_t ret = p->prepareAsync();
872#if CALLBACK_ANTAGONIZER
873 LOGD("start Antagonizer");
874 if (ret == NO_ERROR) mAntagonizer->start();
875#endif
876 return ret;
877}
878
879status_t MediaPlayerService::Client::start()
880{
881 LOGV("[%d] start", mConnId);
882 sp<MediaPlayerBase> p = getPlayer();
883 if (p == 0) return UNKNOWN_ERROR;
884 p->setLooping(mLoop);
885 return p->start();
886}
887
888status_t MediaPlayerService::Client::stop()
889{
890 LOGV("[%d] stop", mConnId);
891 sp<MediaPlayerBase> p = getPlayer();
892 if (p == 0) return UNKNOWN_ERROR;
893 return p->stop();
894}
895
896status_t MediaPlayerService::Client::pause()
897{
898 LOGV("[%d] pause", mConnId);
899 sp<MediaPlayerBase> p = getPlayer();
900 if (p == 0) return UNKNOWN_ERROR;
901 return p->pause();
902}
903
904status_t MediaPlayerService::Client::isPlaying(bool* state)
905{
906 *state = false;
907 sp<MediaPlayerBase> p = getPlayer();
908 if (p == 0) return UNKNOWN_ERROR;
909 *state = p->isPlaying();
910 LOGV("[%d] isPlaying: %d", mConnId, *state);
911 return NO_ERROR;
912}
913
914status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
915{
916 LOGV("getCurrentPosition");
917 sp<MediaPlayerBase> p = getPlayer();
918 if (p == 0) return UNKNOWN_ERROR;
919 status_t ret = p->getCurrentPosition(msec);
920 if (ret == NO_ERROR) {
921 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
922 } else {
923 LOGE("getCurrentPosition returned %d", ret);
924 }
925 return ret;
926}
927
928status_t MediaPlayerService::Client::getDuration(int *msec)
929{
930 LOGV("getDuration");
931 sp<MediaPlayerBase> p = getPlayer();
932 if (p == 0) return UNKNOWN_ERROR;
933 status_t ret = p->getDuration(msec);
934 if (ret == NO_ERROR) {
935 LOGV("[%d] getDuration = %d", mConnId, *msec);
936 } else {
937 LOGE("getDuration returned %d", ret);
938 }
939 return ret;
940}
941
942status_t MediaPlayerService::Client::seekTo(int msec)
943{
944 LOGV("[%d] seekTo(%d)", mConnId, msec);
945 sp<MediaPlayerBase> p = getPlayer();
946 if (p == 0) return UNKNOWN_ERROR;
947 return p->seekTo(msec);
948}
949
950status_t MediaPlayerService::Client::reset()
951{
952 LOGV("[%d] reset", mConnId);
953 sp<MediaPlayerBase> p = getPlayer();
954 if (p == 0) return UNKNOWN_ERROR;
955 return p->reset();
956}
957
958status_t MediaPlayerService::Client::setAudioStreamType(int type)
959{
960 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
961 // TODO: for hardware output, call player instead
962 Mutex::Autolock l(mLock);
963 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
964 return NO_ERROR;
965}
966
967status_t MediaPlayerService::Client::setLooping(int loop)
968{
969 LOGV("[%d] setLooping(%d)", mConnId, loop);
970 mLoop = loop;
971 sp<MediaPlayerBase> p = getPlayer();
972 if (p != 0) return p->setLooping(loop);
973 return NO_ERROR;
974}
975
976status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
977{
978 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
979 // TODO: for hardware output, call player instead
980 Mutex::Autolock l(mLock);
981 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
982 return NO_ERROR;
983}
984
Eric Laurent2beeb502010-07-16 07:43:46 -0700985status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
986{
987 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
988 Mutex::Autolock l(mLock);
989 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
990 return NO_ERROR;
991}
992
993status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
994{
995 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
996 Mutex::Autolock l(mLock);
997 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
998 return NO_ERROR;
999}
Nicolas Catania48290382009-07-10 13:53:06 -07001000
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001001status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1002 LOGV("[%d] setParameter(%d)", mConnId, key);
1003 sp<MediaPlayerBase> p = getPlayer();
1004 if (p == 0) return UNKNOWN_ERROR;
1005 return p->setParameter(key, request);
1006}
1007
1008status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1009 LOGV("[%d] getParameter(%d)", mConnId, key);
1010 sp<MediaPlayerBase> p = getPlayer();
1011 if (p == 0) return UNKNOWN_ERROR;
1012 return p->getParameter(key, reply);
1013}
1014
Gloria Wangb483c472011-04-11 17:23:27 -07001015void MediaPlayerService::Client::notify(
1016 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001017{
1018 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001019
1020 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001021 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001022 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001023
1024 if(client->shouldDropMetadata(metadata_type)) {
1025 return;
1026 }
1027
1028 // Update the list of metadata that have changed. getMetadata
1029 // also access mMetadataUpdated and clears it.
1030 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001031 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001032 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001033 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001034}
1035
Nicolas Catania48290382009-07-10 13:53:06 -07001036
nikoa64c8c72009-07-20 15:07:26 -07001037bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001038{
Nicolas Catania48290382009-07-10 13:53:06 -07001039 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001040
Nicolas Catania48290382009-07-10 13:53:06 -07001041 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001042 return true;
1043 }
1044
Nicolas Catania48290382009-07-10 13:53:06 -07001045 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001046 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001047 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001048 return true;
1049 }
1050}
1051
Nicolas Catania48290382009-07-10 13:53:06 -07001052
nikoa64c8c72009-07-20 15:07:26 -07001053void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001054 Mutex::Autolock lock(mLock);
1055 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1056 mMetadataUpdated.add(metadata_type);
1057 }
1058}
1059
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001060#if CALLBACK_ANTAGONIZER
1061const int Antagonizer::interval = 10000; // 10 msecs
1062
1063Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1064 mExit(false), mActive(false), mClient(client), mCb(cb)
1065{
1066 createThread(callbackThread, this);
1067}
1068
1069void Antagonizer::kill()
1070{
1071 Mutex::Autolock _l(mLock);
1072 mActive = false;
1073 mExit = true;
1074 mCondition.wait(mLock);
1075}
1076
1077int Antagonizer::callbackThread(void* user)
1078{
1079 LOGD("Antagonizer started");
1080 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1081 while (!p->mExit) {
1082 if (p->mActive) {
1083 LOGV("send event");
1084 p->mCb(p->mClient, 0, 0, 0);
1085 }
1086 usleep(interval);
1087 }
1088 Mutex::Autolock _l(p->mLock);
1089 p->mCondition.signal();
1090 LOGD("Antagonizer stopped");
1091 return 0;
1092}
1093#endif
1094
1095static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1096
1097sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1098{
1099 LOGV("decode(%s)", url);
1100 sp<MemoryBase> mem;
1101 sp<MediaPlayerBase> player;
1102
1103 // Protect our precious, precious DRMd ringtones by only allowing
1104 // decoding of http, but not filesystem paths or content Uris.
1105 // If the application wants to decode those, it should open a
1106 // filedescriptor for them and use that.
1107 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1108 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1109 return mem;
1110 }
1111
1112 player_type playerType = getPlayerType(url);
1113 LOGV("player type = %d", playerType);
1114
1115 // create the right type of player
1116 sp<AudioCache> cache = new AudioCache(url);
1117 player = android::createPlayer(playerType, cache.get(), cache->notify);
1118 if (player == NULL) goto Exit;
1119 if (player->hardwareOutput()) goto Exit;
1120
1121 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1122
1123 // set data source
1124 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1125
1126 LOGV("prepare");
1127 player->prepareAsync();
1128
1129 LOGV("wait for prepare");
1130 if (cache->wait() != NO_ERROR) goto Exit;
1131
1132 LOGV("start");
1133 player->start();
1134
1135 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001136 cache->wait();
1137 // in case of error, return what was successfully decoded.
1138 if (cache->size() == 0) {
1139 goto Exit;
1140 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001141
1142 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1143 *pSampleRate = cache->sampleRate();
1144 *pNumChannels = cache->channelCount();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001145 *pFormat = (int)cache->format();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001146 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1147
1148Exit:
1149 if (player != 0) player->reset();
1150 return mem;
1151}
1152
1153sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1154{
1155 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1156 sp<MemoryBase> mem;
1157 sp<MediaPlayerBase> player;
1158
1159 player_type playerType = getPlayerType(fd, offset, length);
1160 LOGV("player type = %d", playerType);
1161
1162 // create the right type of player
1163 sp<AudioCache> cache = new AudioCache("decode_fd");
1164 player = android::createPlayer(playerType, cache.get(), cache->notify);
1165 if (player == NULL) goto Exit;
1166 if (player->hardwareOutput()) goto Exit;
1167
1168 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1169
1170 // set data source
1171 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1172
1173 LOGV("prepare");
1174 player->prepareAsync();
1175
1176 LOGV("wait for prepare");
1177 if (cache->wait() != NO_ERROR) goto Exit;
1178
1179 LOGV("start");
1180 player->start();
1181
1182 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001183 cache->wait();
1184 // in case of error, return what was successfully decoded.
1185 if (cache->size() == 0) {
1186 goto Exit;
1187 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001188
1189 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1190 *pSampleRate = cache->sampleRate();
1191 *pNumChannels = cache->channelCount();
1192 *pFormat = cache->format();
1193 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1194
1195Exit:
1196 if (player != 0) player->reset();
1197 ::close(fd);
1198 return mem;
1199}
1200
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001201
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001202#undef LOG_TAG
1203#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001204MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001205 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001206 mCallbackCookie(NULL),
1207 mSessionId(sessionId) {
1208 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001209 mTrack = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -07001210 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001211 mLeftVolume = 1.0;
1212 mRightVolume = 1.0;
1213 mLatency = 0;
1214 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001215 mAuxEffectId = 0;
1216 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001217 setMinBufferCount();
1218}
1219
1220MediaPlayerService::AudioOutput::~AudioOutput()
1221{
1222 close();
1223}
1224
1225void MediaPlayerService::AudioOutput::setMinBufferCount()
1226{
1227 char value[PROPERTY_VALUE_MAX];
1228 if (property_get("ro.kernel.qemu", value, 0)) {
1229 mIsOnEmulator = true;
1230 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1231 }
1232}
1233
1234bool MediaPlayerService::AudioOutput::isOnEmulator()
1235{
1236 setMinBufferCount();
1237 return mIsOnEmulator;
1238}
1239
1240int MediaPlayerService::AudioOutput::getMinBufferCount()
1241{
1242 setMinBufferCount();
1243 return mMinBufferCount;
1244}
1245
1246ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1247{
1248 if (mTrack == 0) return NO_INIT;
1249 return mTrack->frameCount() * frameSize();
1250}
1251
1252ssize_t MediaPlayerService::AudioOutput::frameCount() const
1253{
1254 if (mTrack == 0) return NO_INIT;
1255 return mTrack->frameCount();
1256}
1257
1258ssize_t MediaPlayerService::AudioOutput::channelCount() const
1259{
1260 if (mTrack == 0) return NO_INIT;
1261 return mTrack->channelCount();
1262}
1263
1264ssize_t MediaPlayerService::AudioOutput::frameSize() const
1265{
1266 if (mTrack == 0) return NO_INIT;
1267 return mTrack->frameSize();
1268}
1269
1270uint32_t MediaPlayerService::AudioOutput::latency () const
1271{
1272 return mLatency;
1273}
1274
1275float MediaPlayerService::AudioOutput::msecsPerFrame() const
1276{
1277 return mMsecsPerFrame;
1278}
1279
Eric Laurent342e9cf2010-01-19 17:37:09 -08001280status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1281{
1282 if (mTrack == 0) return NO_INIT;
1283 return mTrack->getPosition(position);
1284}
1285
Andreas Huber20111aa2009-07-14 16:56:47 -07001286status_t MediaPlayerService::AudioOutput::open(
1287 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1288 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289{
Andreas Huber20111aa2009-07-14 16:56:47 -07001290 mCallback = cb;
1291 mCallbackCookie = cookie;
1292
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001293 // Check argument "bufferCount" against the mininum buffer count
1294 if (bufferCount < mMinBufferCount) {
1295 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1296 bufferCount = mMinBufferCount;
1297
1298 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001299 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001300 if (mTrack) close();
1301 int afSampleRate;
1302 int afFrameCount;
1303 int frameCount;
1304
1305 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1306 return NO_INIT;
1307 }
1308 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1309 return NO_INIT;
1310 }
1311
1312 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001313
1314 AudioTrack *t;
1315 if (mCallback != NULL) {
1316 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001317 mStreamType,
1318 sampleRate,
1319 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001320 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001321 frameCount,
1322 0 /* flags */,
1323 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001324 this,
1325 0,
1326 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001327 } else {
1328 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001329 mStreamType,
1330 sampleRate,
1331 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001332 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001333 frameCount,
1334 0,
1335 NULL,
1336 NULL,
1337 0,
1338 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001339 }
1340
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001341 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1342 LOGE("Unable to create audio track");
1343 delete t;
1344 return NO_INIT;
1345 }
1346
1347 LOGV("setVolume");
1348 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001349
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001351 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001353
1354 t->setAuxEffectSendLevel(mSendLevel);
1355 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001356}
1357
1358void MediaPlayerService::AudioOutput::start()
1359{
1360 LOGV("start");
1361 if (mTrack) {
1362 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001363 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364 mTrack->start();
1365 }
1366}
1367
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001368
1369
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1371{
Andreas Huber20111aa2009-07-14 16:56:47 -07001372 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1373
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001375 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001376 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001377 return ret;
1378 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001379 return NO_INIT;
1380}
1381
1382void MediaPlayerService::AudioOutput::stop()
1383{
1384 LOGV("stop");
1385 if (mTrack) mTrack->stop();
1386}
1387
1388void MediaPlayerService::AudioOutput::flush()
1389{
1390 LOGV("flush");
1391 if (mTrack) mTrack->flush();
1392}
1393
1394void MediaPlayerService::AudioOutput::pause()
1395{
1396 LOGV("pause");
1397 if (mTrack) mTrack->pause();
1398}
1399
1400void MediaPlayerService::AudioOutput::close()
1401{
1402 LOGV("close");
1403 delete mTrack;
1404 mTrack = 0;
1405}
1406
1407void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1408{
1409 LOGV("setVolume(%f, %f)", left, right);
1410 mLeftVolume = left;
1411 mRightVolume = right;
1412 if (mTrack) {
1413 mTrack->setVolume(left, right);
1414 }
1415}
1416
Eric Laurent2beeb502010-07-16 07:43:46 -07001417status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1418{
1419 LOGV("setAuxEffectSendLevel(%f)", level);
1420 mSendLevel = level;
1421 if (mTrack) {
1422 return mTrack->setAuxEffectSendLevel(level);
1423 }
1424 return NO_ERROR;
1425}
1426
1427status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1428{
1429 LOGV("attachAuxEffect(%d)", effectId);
1430 mAuxEffectId = effectId;
1431 if (mTrack) {
1432 return mTrack->attachAuxEffect(effectId);
1433 }
1434 return NO_ERROR;
1435}
1436
Andreas Huber20111aa2009-07-14 16:56:47 -07001437// static
1438void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001439 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001440 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001441 if (event != AudioTrack::EVENT_MORE_DATA) {
1442 return;
1443 }
1444
1445 AudioOutput *me = (AudioOutput *)cookie;
1446 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1447
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001448 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001449 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001450
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001451 if (actualSize == 0 && buffer->size > 0) {
1452 // We've reached EOS but the audio track is not stopped yet,
1453 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001454
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001455 memset(buffer->raw, 0, buffer->size);
1456 actualSize = buffer->size;
1457 }
1458
1459 buffer->size = actualSize;
Andreas Huber20111aa2009-07-14 16:56:47 -07001460}
1461
Eric Laurent8c563ed2010-10-07 18:23:03 -07001462int MediaPlayerService::AudioOutput::getSessionId()
1463{
1464 return mSessionId;
1465}
1466
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467#undef LOG_TAG
1468#define LOG_TAG "AudioCache"
1469MediaPlayerService::AudioCache::AudioCache(const char* name) :
1470 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1471 mError(NO_ERROR), mCommandComplete(false)
1472{
1473 // create ashmem heap
1474 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1475}
1476
1477uint32_t MediaPlayerService::AudioCache::latency () const
1478{
1479 return 0;
1480}
1481
1482float MediaPlayerService::AudioCache::msecsPerFrame() const
1483{
1484 return mMsecsPerFrame;
1485}
1486
Eric Laurent342e9cf2010-01-19 17:37:09 -08001487status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1488{
1489 if (position == 0) return BAD_VALUE;
1490 *position = mSize;
1491 return NO_ERROR;
1492}
1493
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001494////////////////////////////////////////////////////////////////////////////////
1495
1496struct CallbackThread : public Thread {
1497 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1498 MediaPlayerBase::AudioSink::AudioCallback cb,
1499 void *cookie);
1500
1501protected:
1502 virtual ~CallbackThread();
1503
1504 virtual bool threadLoop();
1505
1506private:
1507 wp<MediaPlayerBase::AudioSink> mSink;
1508 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1509 void *mCookie;
1510 void *mBuffer;
1511 size_t mBufferSize;
1512
1513 CallbackThread(const CallbackThread &);
1514 CallbackThread &operator=(const CallbackThread &);
1515};
1516
1517CallbackThread::CallbackThread(
1518 const wp<MediaPlayerBase::AudioSink> &sink,
1519 MediaPlayerBase::AudioSink::AudioCallback cb,
1520 void *cookie)
1521 : mSink(sink),
1522 mCallback(cb),
1523 mCookie(cookie),
1524 mBuffer(NULL),
1525 mBufferSize(0) {
1526}
1527
1528CallbackThread::~CallbackThread() {
1529 if (mBuffer) {
1530 free(mBuffer);
1531 mBuffer = NULL;
1532 }
1533}
1534
1535bool CallbackThread::threadLoop() {
1536 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1537 if (sink == NULL) {
1538 return false;
1539 }
1540
1541 if (mBuffer == NULL) {
1542 mBufferSize = sink->bufferSize();
1543 mBuffer = malloc(mBufferSize);
1544 }
1545
1546 size_t actualSize =
1547 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1548
1549 if (actualSize > 0) {
1550 sink->write(mBuffer, actualSize);
1551 }
1552
1553 return true;
1554}
1555
1556////////////////////////////////////////////////////////////////////////////////
1557
Andreas Huber20111aa2009-07-14 16:56:47 -07001558status_t MediaPlayerService::AudioCache::open(
1559 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1560 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001561{
Dave Sparks8eb80112009-12-09 20:20:26 -08001562 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001563 if (mHeap->getHeapID() < 0) {
1564 return NO_INIT;
1565 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001566
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001567 mSampleRate = sampleRate;
1568 mChannelCount = (uint16_t)channelCount;
1569 mFormat = (uint16_t)format;
1570 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001571
1572 if (cb != NULL) {
1573 mCallbackThread = new CallbackThread(this, cb, cookie);
1574 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001575 return NO_ERROR;
1576}
1577
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001578void MediaPlayerService::AudioCache::start() {
1579 if (mCallbackThread != NULL) {
1580 mCallbackThread->run("AudioCache callback");
1581 }
1582}
1583
1584void MediaPlayerService::AudioCache::stop() {
1585 if (mCallbackThread != NULL) {
1586 mCallbackThread->requestExitAndWait();
1587 }
1588}
1589
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001590ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1591{
1592 LOGV("write(%p, %u)", buffer, size);
1593 if ((buffer == 0) || (size == 0)) return size;
1594
1595 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1596 if (p == NULL) return NO_INIT;
1597 p += mSize;
1598 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1599 if (mSize + size > mHeap->getSize()) {
1600 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1601 size = mHeap->getSize() - mSize;
1602 }
1603 memcpy(p, buffer, size);
1604 mSize += size;
1605 return size;
1606}
1607
1608// call with lock held
1609status_t MediaPlayerService::AudioCache::wait()
1610{
1611 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001612 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613 mSignal.wait(mLock);
1614 }
1615 mCommandComplete = false;
1616
1617 if (mError == NO_ERROR) {
1618 LOGV("wait - success");
1619 } else {
1620 LOGV("wait - error");
1621 }
1622 return mError;
1623}
1624
Gloria Wangb483c472011-04-11 17:23:27 -07001625void MediaPlayerService::AudioCache::notify(
1626 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627{
1628 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1629 AudioCache* p = static_cast<AudioCache*>(cookie);
1630
1631 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001632 switch (msg)
1633 {
1634 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001635 LOGE("Error %d, %d occurred", ext1, ext2);
1636 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001637 break;
1638 case MEDIA_PREPARED:
1639 LOGV("prepared");
1640 break;
1641 case MEDIA_PLAYBACK_COMPLETE:
1642 LOGV("playback complete");
1643 break;
1644 default:
1645 LOGV("ignored");
1646 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001647 }
1648
1649 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001650 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001651 p->mCommandComplete = true;
1652 p->mSignal.signal();
1653}
1654
Eric Laurent8c563ed2010-10-07 18:23:03 -07001655int MediaPlayerService::AudioCache::getSessionId()
1656{
1657 return 0;
1658}
1659
Gloria Wang7cf180c2011-02-19 18:37:57 -08001660void MediaPlayerService::addBatteryData(uint32_t params)
1661{
1662 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001663
1664 int32_t time = systemTime() / 1000000L;
1665
1666 // change audio output devices. This notification comes from AudioFlinger
1667 if ((params & kBatteryDataSpeakerOn)
1668 || (params & kBatteryDataOtherAudioDeviceOn)) {
1669
1670 int deviceOn[NUM_AUDIO_DEVICES];
1671 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1672 deviceOn[i] = 0;
1673 }
1674
1675 if ((params & kBatteryDataSpeakerOn)
1676 && (params & kBatteryDataOtherAudioDeviceOn)) {
1677 deviceOn[SPEAKER_AND_OTHER] = 1;
1678 } else if (params & kBatteryDataSpeakerOn) {
1679 deviceOn[SPEAKER] = 1;
1680 } else {
1681 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1682 }
1683
1684 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1685 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1686
1687 if (mBatteryAudio.refCount > 0) { // if playing audio
1688 if (!deviceOn[i]) {
1689 mBatteryAudio.lastTime[i] += time;
1690 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1691 mBatteryAudio.lastTime[i] = 0;
1692 } else {
1693 mBatteryAudio.lastTime[i] = 0 - time;
1694 }
1695 }
1696
1697 mBatteryAudio.deviceOn[i] = deviceOn[i];
1698 }
1699 }
1700 return;
1701 }
1702
1703 // an sudio stream is started
1704 if (params & kBatteryDataAudioFlingerStart) {
1705 // record the start time only if currently no other audio
1706 // is being played
1707 if (mBatteryAudio.refCount == 0) {
1708 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1709 if (mBatteryAudio.deviceOn[i]) {
1710 mBatteryAudio.lastTime[i] -= time;
1711 }
1712 }
1713 }
1714
1715 mBatteryAudio.refCount ++;
1716 return;
1717
1718 } else if (params & kBatteryDataAudioFlingerStop) {
1719 if (mBatteryAudio.refCount <= 0) {
1720 LOGW("Battery track warning: refCount is <= 0");
1721 return;
1722 }
1723
1724 // record the stop time only if currently this is the only
1725 // audio being played
1726 if (mBatteryAudio.refCount == 1) {
1727 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1728 if (mBatteryAudio.deviceOn[i]) {
1729 mBatteryAudio.lastTime[i] += time;
1730 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1731 mBatteryAudio.lastTime[i] = 0;
1732 }
1733 }
1734 }
1735
1736 mBatteryAudio.refCount --;
1737 return;
1738 }
1739
Gloria Wang7cf180c2011-02-19 18:37:57 -08001740 int uid = IPCThreadState::self()->getCallingUid();
1741 if (uid == AID_MEDIA) {
1742 return;
1743 }
1744 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001745
1746 if (index < 0) { // create a new entry for this UID
1747 BatteryUsageInfo info;
1748 info.audioTotalTime = 0;
1749 info.videoTotalTime = 0;
1750 info.audioLastTime = 0;
1751 info.videoLastTime = 0;
1752 info.refCount = 0;
1753
Gloria Wang9ee159b2011-02-24 14:51:45 -08001754 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1755 LOGE("Battery track error: no memory for new app");
1756 return;
1757 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001758 }
1759
1760 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1761
1762 if (params & kBatteryDataCodecStarted) {
1763 if (params & kBatteryDataTrackAudio) {
1764 info.audioLastTime -= time;
1765 info.refCount ++;
1766 }
1767 if (params & kBatteryDataTrackVideo) {
1768 info.videoLastTime -= time;
1769 info.refCount ++;
1770 }
1771 } else {
1772 if (info.refCount == 0) {
1773 LOGW("Battery track warning: refCount is already 0");
1774 return;
1775 } else if (info.refCount < 0) {
1776 LOGE("Battery track error: refCount < 0");
1777 mBatteryData.removeItem(uid);
1778 return;
1779 }
1780
1781 if (params & kBatteryDataTrackAudio) {
1782 info.audioLastTime += time;
1783 info.refCount --;
1784 }
1785 if (params & kBatteryDataTrackVideo) {
1786 info.videoLastTime += time;
1787 info.refCount --;
1788 }
1789
1790 // no stream is being played by this UID
1791 if (info.refCount == 0) {
1792 info.audioTotalTime += info.audioLastTime;
1793 info.audioLastTime = 0;
1794 info.videoTotalTime += info.videoLastTime;
1795 info.videoLastTime = 0;
1796 }
1797 }
1798}
1799
1800status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1801 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001802
1803 // audio output devices usage
1804 int32_t time = systemTime() / 1000000L; //in ms
1805 int32_t totalTime;
1806
1807 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1808 totalTime = mBatteryAudio.totalTime[i];
1809
1810 if (mBatteryAudio.deviceOn[i]
1811 && (mBatteryAudio.lastTime[i] != 0)) {
1812 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1813 totalTime += tmpTime;
1814 }
1815
1816 reply->writeInt32(totalTime);
1817 // reset the total time
1818 mBatteryAudio.totalTime[i] = 0;
1819 }
1820
1821 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001822 BatteryUsageInfo info;
1823 int size = mBatteryData.size();
1824
1825 reply->writeInt32(size);
1826 int i = 0;
1827
1828 while (i < size) {
1829 info = mBatteryData.valueAt(i);
1830
1831 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1832 reply->writeInt32(info.audioTotalTime);
1833 reply->writeInt32(info.videoTotalTime);
1834
1835 info.audioTotalTime = 0;
1836 info.videoTotalTime = 0;
1837
1838 // remove the UID entry where no stream is being played
1839 if (info.refCount <= 0) {
1840 mBatteryData.removeItemsAt(i);
1841 size --;
1842 i --;
1843 }
1844 i++;
1845 }
1846 return NO_ERROR;
1847}
nikoa64c8c72009-07-20 15:07:26 -07001848} // namespace android