blob: b7d2b5c701b46ca4ae43f7581b1e6f2ec1f740ff [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>
Eric Laurent9968a362011-09-27 09:48:56 -070055#include <media/stagefright/MediaErrors.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Dima Zavin34bb4192011-05-11 14:15:23 -070057#include <system/audio.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070058
Gloria Wangd211f412011-02-19 18:37:57 -080059#include <private/android_filesystem_config.h>
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061#include "MediaRecorderClient.h"
62#include "MediaPlayerService.h"
63#include "MetadataRetrieverClient.h"
64
65#include "MidiFile.h"
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070066#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070067#include "StagefrightPlayer.h"
Andreas Hubera1587462010-12-15 15:17:42 -080068#include "nuplayer/NuPlayerDriver.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070069
Andreas Hubere46b7be2009-07-14 16:56:47 -070070#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070071
Mike J. Chenda548442011-08-15 13:24:13 -070072namespace android {
73sp<MediaPlayerBase> createAAH_TXPlayer();
74sp<MediaPlayerBase> createAAH_RXPlayer();
75}
76
Nicolas Cataniab2c69392009-07-08 08:57:42 -070077namespace {
nikobc726922009-07-20 15:07:26 -070078using android::media::Metadata;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070079using android::status_t;
80using android::OK;
81using android::BAD_VALUE;
82using android::NOT_ENOUGH_DATA;
83using android::Parcel;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070084
85// Max number of entries in the filter.
86const int kMaxFilterSize = 64; // I pulled that out of thin air.
87
nikobc726922009-07-20 15:07:26 -070088// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070089
Nicolas Cataniab2c69392009-07-08 08:57:42 -070090
91// Unmarshall a filter from a Parcel.
92// Filter format in a parcel:
93//
94// 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
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// | number of entries (n) |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// | metadata type 1 |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | metadata type 2 |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// ....
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | metadata type n |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//
107// @param p Parcel that should start with a filter.
108// @param[out] filter On exit contains the list of metadata type to be
109// filtered.
110// @param[out] status On exit contains the status code to be returned.
111// @return true if the parcel starts with a valid filter.
112bool unmarshallFilter(const Parcel& p,
nikobc726922009-07-20 15:07:26 -0700113 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700114 status_t *status)
115{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700116 int32_t val;
117 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700118 {
119 LOGE("Failed to read filter's length");
120 *status = NOT_ENOUGH_DATA;
121 return false;
122 }
123
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700124 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700125 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700126 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700127 *status = BAD_VALUE;
128 return false;
129 }
130
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700131 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700132
133 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700134 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700135
nikobc726922009-07-20 15:07:26 -0700136 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700137
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700138
139 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700140 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700141 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700142 *status = NOT_ENOUGH_DATA;
143 return false;
144 }
145
nikobc726922009-07-20 15:07:26 -0700146 const Metadata::Type *data =
147 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700148
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700149 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700150 {
151 LOGE("Filter had no data");
152 *status = BAD_VALUE;
153 return false;
154 }
155
156 // TODO: The stl impl of vector would be more efficient here
157 // because it degenerates into a memcpy on pod types. Try to
158 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700159 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700160 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700161 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700162 ++data;
163 }
164 *status = OK;
165 return true;
166}
167
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700168// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700169// @param val To be searched.
170// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700172{
173 // Deal with empty and ANY right away
174 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700175 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700176
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700177 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700178}
179
180} // anonymous namespace
181
182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183namespace android {
184
Dave Burkefc301b02011-08-30 14:39:17 +0100185static bool checkPermission(const char* permissionString) {
186#ifndef HAVE_ANDROID_OS
187 return true;
188#endif
189 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
190 bool ok = checkCallingPermission(String16(permissionString));
191 if (!ok) LOGE("Request requires %s", permissionString);
192 return ok;
193}
194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195// TODO: Temp hack until we can register players
196typedef struct {
197 const char *extension;
198 const player_type playertype;
199} extmap;
200extmap FILE_EXTS [] = {
201 {".mid", SONIVOX_PLAYER},
202 {".midi", SONIVOX_PLAYER},
203 {".smf", SONIVOX_PLAYER},
204 {".xmf", SONIVOX_PLAYER},
205 {".imy", SONIVOX_PLAYER},
206 {".rtttl", SONIVOX_PLAYER},
207 {".rtx", SONIVOX_PLAYER},
208 {".ota", SONIVOX_PLAYER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209};
210
211// 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 -0800212/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
213/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
214
215void MediaPlayerService::instantiate() {
216 defaultServiceManager()->addService(
217 String16("media.player"), new MediaPlayerService());
218}
219
220MediaPlayerService::MediaPlayerService()
221{
222 LOGV("MediaPlayerService created");
223 mNextConnId = 1;
Gloria Wang9b3f1522011-02-24 14:51:45 -0800224
225 mBatteryAudio.refCount = 0;
226 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
227 mBatteryAudio.deviceOn[i] = 0;
228 mBatteryAudio.lastTime[i] = 0;
229 mBatteryAudio.totalTime[i] = 0;
230 }
231 // speaker is on by default
232 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233}
234
235MediaPlayerService::~MediaPlayerService()
236{
237 LOGV("MediaPlayerService destroyed");
238}
239
240sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
241{
Gloria Wang608a2632009-10-29 15:46:37 -0700242 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
243 wp<MediaRecorderClient> w = recorder;
244 Mutex::Autolock lock(mLock);
245 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 LOGV("Create new media recorder client from pid %d", pid);
247 return recorder;
248}
249
Gloria Wang608a2632009-10-29 15:46:37 -0700250void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
251{
252 Mutex::Autolock lock(mLock);
253 mMediaRecorderClients.remove(client);
254 LOGV("Delete media recorder client");
255}
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
258{
259 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
260 LOGV("Create new media retriever from pid %d", pid);
261 return retriever;
262}
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burkefc301b02011-08-30 14:39:17 +0100265 int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266{
267 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700268
269 sp<Client> c = new Client(
270 this, pid, connId, client, audioSessionId,
271 IPCThreadState::self()->getCallingUid());
272
Dave Burkefc301b02011-08-30 14:39:17 +0100273 LOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
274 IPCThreadState::self()->getCallingUid());
275
276 wp<Client> w = c;
277 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 Mutex::Autolock lock(mLock);
279 mClients.add(w);
280 }
Andreas Huber52b52cd2010-11-23 11:41:34 -0800281 return c;
282}
283
Andreas Huber784202e2009-10-15 13:46:54 -0700284sp<IOMX> MediaPlayerService::getOMX() {
285 Mutex::Autolock autoLock(mLock);
286
287 if (mOMX.get() == NULL) {
288 mOMX = new OMX;
289 }
290
291 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700292}
293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
295{
296 const size_t SIZE = 256;
297 char buffer[SIZE];
298 String8 result;
299
300 result.append(" AudioCache\n");
301 if (mHeap != 0) {
302 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
303 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
304 result.append(buffer);
305 }
306 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
307 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
308 result.append(buffer);
309 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
310 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
311 result.append(buffer);
312 ::write(fd, result.string(), result.size());
313 return NO_ERROR;
314}
315
316status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
317{
318 const size_t SIZE = 256;
319 char buffer[SIZE];
320 String8 result;
321
322 result.append(" AudioOutput\n");
323 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
324 mStreamType, mLeftVolume, mRightVolume);
325 result.append(buffer);
326 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
327 mMsecsPerFrame, mLatency);
328 result.append(buffer);
Eric Laurent7070b362010-07-16 07:43:46 -0700329 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
330 mAuxEffectId, mSendLevel);
331 result.append(buffer);
332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 ::write(fd, result.string(), result.size());
334 if (mTrack != 0) {
335 mTrack->dump(fd, args);
336 }
337 return NO_ERROR;
338}
339
340status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
341{
342 const size_t SIZE = 256;
343 char buffer[SIZE];
344 String8 result;
345 result.append(" Client\n");
346 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
347 mPid, mConnId, mStatus, mLoop?"true": "false");
348 result.append(buffer);
349 write(fd, result.string(), result.size());
Andreas Huberfddf5d92011-06-07 15:52:25 -0700350 if (mPlayer != NULL) {
351 mPlayer->dump(fd, args);
352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 if (mAudioOutput != 0) {
354 mAudioOutput->dump(fd, args);
355 }
356 write(fd, "\n", 1);
357 return NO_ERROR;
358}
359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
361{
362 const size_t SIZE = 256;
363 char buffer[SIZE];
364 String8 result;
365 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
366 snprintf(buffer, SIZE, "Permission Denial: "
367 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
368 IPCThreadState::self()->getCallingPid(),
369 IPCThreadState::self()->getCallingUid());
370 result.append(buffer);
371 } else {
372 Mutex::Autolock lock(mLock);
373 for (int i = 0, n = mClients.size(); i < n; ++i) {
374 sp<Client> c = mClients[i].promote();
375 if (c != 0) c->dump(fd, args);
376 }
James Dong929642e2010-07-08 11:16:11 -0700377 if (mMediaRecorderClients.size() == 0) {
378 result.append(" No media recorder client\n\n");
379 } else {
380 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
381 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
382 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
383 result.append(buffer);
384 write(fd, result.string(), result.size());
385 result = "\n";
386 c->dump(fd, args);
387 }
Gloria Wang608a2632009-10-29 15:46:37 -0700388 }
389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 result.append(" Files opened and/or mapped:\n");
Glenn Kasten6af763b2011-05-04 17:58:57 -0700391 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 FILE *f = fopen(buffer, "r");
393 if (f) {
394 while (!feof(f)) {
395 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700396 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700398 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 strstr(buffer, " /system/media/")) {
400 result.append(" ");
401 result.append(buffer);
402 }
403 }
404 fclose(f);
405 } else {
406 result.append("couldn't open ");
407 result.append(buffer);
408 result.append("\n");
409 }
410
Glenn Kasten6af763b2011-05-04 17:58:57 -0700411 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 DIR *d = opendir(buffer);
413 if (d) {
414 struct dirent *ent;
415 while((ent = readdir(d)) != NULL) {
416 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten6af763b2011-05-04 17:58:57 -0700417 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 struct stat s;
419 if (lstat(buffer, &s) == 0) {
420 if ((s.st_mode & S_IFMT) == S_IFLNK) {
421 char linkto[256];
422 int len = readlink(buffer, linkto, sizeof(linkto));
423 if(len > 0) {
424 if(len > 255) {
425 linkto[252] = '.';
426 linkto[253] = '.';
427 linkto[254] = '.';
428 linkto[255] = 0;
429 } else {
430 linkto[len] = 0;
431 }
Dave Sparks124a3462010-09-27 16:55:18 -0700432 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700434 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 strstr(linkto, "/system/media/") == linkto) {
436 result.append(" ");
437 result.append(buffer);
438 result.append(" -> ");
439 result.append(linkto);
440 result.append("\n");
441 }
442 }
443 } else {
444 result.append(" unexpected type for ");
445 result.append(buffer);
446 result.append("\n");
447 }
448 }
449 }
450 }
451 closedir(d);
452 } else {
453 result.append("couldn't open ");
454 result.append(buffer);
455 result.append("\n");
456 }
457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 bool dumpMem = false;
459 for (size_t i = 0; i < args.size(); i++) {
460 if (args[i] == String16("-m")) {
461 dumpMem = true;
462 }
463 }
464 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700465 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 }
468 write(fd, result.string(), result.size());
469 return NO_ERROR;
470}
471
472void MediaPlayerService::removeClient(wp<Client> client)
473{
474 Mutex::Autolock lock(mLock);
475 mClients.remove(client);
476}
477
Andreas Huber603d7392011-06-30 15:47:02 -0700478MediaPlayerService::Client::Client(
479 const sp<MediaPlayerService>& service, pid_t pid,
480 int32_t connId, const sp<IMediaPlayerClient>& client,
481 int audioSessionId, uid_t uid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482{
483 LOGV("Client(%d) constructor", connId);
484 mPid = pid;
485 mConnId = connId;
486 mService = service;
487 mClient = client;
488 mLoop = false;
489 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700490 mAudioSessionId = audioSessionId;
Andreas Huber603d7392011-06-30 15:47:02 -0700491 mUID = uid;
Eric Laurent619346f2010-06-21 09:27:30 -0700492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493#if CALLBACK_ANTAGONIZER
494 LOGD("create Antagonizer");
495 mAntagonizer = new Antagonizer(notify, this);
496#endif
497}
498
499MediaPlayerService::Client::~Client()
500{
501 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
502 mAudioOutput.clear();
503 wp<Client> client(this);
504 disconnect();
505 mService->removeClient(client);
506}
507
508void MediaPlayerService::Client::disconnect()
509{
510 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
511 // grab local reference and clear main reference to prevent future
512 // access to object
513 sp<MediaPlayerBase> p;
514 {
515 Mutex::Autolock l(mLock);
516 p = mPlayer;
517 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700518 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 mPlayer.clear();
521
522 // clear the notification to prevent callbacks to dead client
523 // and reset the player. We assume the player will serialize
524 // access to itself if necessary.
525 if (p != 0) {
526 p->setNotifyCallback(0, 0);
527#if CALLBACK_ANTAGONIZER
528 LOGD("kill Antagonizer");
529 mAntagonizer->kill();
530#endif
531 p->reset();
532 }
533
534 IPCThreadState::self()->flushCommands();
535}
536
Andreas Huber0d596d42009-08-07 09:30:32 -0700537static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700538 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700539}
540
James Dong392ff3b2009-09-06 14:29:45 -0700541player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542{
543 char buf[20];
544 lseek(fd, offset, SEEK_SET);
545 read(fd, buf, sizeof(buf));
546 lseek(fd, offset, SEEK_SET);
547
548 long ident = *((long*)buf);
549
550 // Ogg vorbis?
551 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700552 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553
554 // Some kind of MIDI?
555 EAS_DATA_HANDLE easdata;
556 if (EAS_Init(&easdata) == EAS_SUCCESS) {
557 EAS_FILE locator;
558 locator.path = NULL;
559 locator.fd = fd;
560 locator.offset = offset;
561 locator.length = length;
562 EAS_HANDLE eashandle;
563 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
564 EAS_CloseFile(easdata, eashandle);
565 EAS_Shutdown(easdata);
566 return SONIVOX_PLAYER;
567 }
568 EAS_Shutdown(easdata);
569 }
570
Andreas Huber0d596d42009-08-07 09:30:32 -0700571 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572}
573
James Dong392ff3b2009-09-06 14:29:45 -0700574player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700576 if (TestPlayerStub::canBeUsed(url)) {
577 return TEST_PLAYER;
578 }
579
Andreas Huber554d0ea2011-03-21 16:28:04 -0700580 if (!strncasecmp("http://", url, 7)
581 || !strncasecmp("https://", url, 8)) {
Andreas Huberd6c421f2011-02-16 09:05:38 -0800582 size_t len = strlen(url);
583 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
584 return NU_PLAYER;
585 }
Andreas Huber54e66492010-12-23 10:27:40 -0800586
Andreas Huberd6c421f2011-02-16 09:05:38 -0800587 if (strstr(url,"m3u8")) {
588 return NU_PLAYER;
Andreas Huber54e66492010-12-23 10:27:40 -0800589 }
590 }
591
Mike J. Chenda548442011-08-15 13:24:13 -0700592 if (!strncasecmp("aahRX://", url, 8)) {
593 return AAH_RX_PLAYER;
594 }
595
596 if (!strncasecmp("aahTX://", url, 8)) {
597 return AAH_TX_PLAYER;
598 }
599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 // use MidiFile for MIDI extensions
601 int lenURL = strlen(url);
602 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
603 int len = strlen(FILE_EXTS[i].extension);
604 int start = lenURL - len;
605 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900606 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700607 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
609 }
610 }
611
Andreas Huber0d596d42009-08-07 09:30:32 -0700612 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613}
614
615static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
616 notify_callback_f notifyFunc)
617{
618 sp<MediaPlayerBase> p;
619 switch (playerType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 case SONIVOX_PLAYER:
621 LOGV(" create MidiFile");
622 p = new MidiFile();
623 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700624 case STAGEFRIGHT_PLAYER:
625 LOGV(" create StagefrightPlayer");
626 p = new StagefrightPlayer;
627 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800628 case NU_PLAYER:
629 LOGV(" create NuPlayer");
630 p = new NuPlayerDriver;
631 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700632 case TEST_PLAYER:
633 LOGV("Create Test Player stub");
634 p = new TestPlayerStub();
635 break;
Mike J. Chenda548442011-08-15 13:24:13 -0700636 case AAH_RX_PLAYER:
637 LOGV(" create A@H RX Player");
638 p = createAAH_RXPlayer();
639 break;
640 case AAH_TX_PLAYER:
641 LOGV(" create A@H TX Player");
642 p = createAAH_TXPlayer();
643 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800644 default:
645 LOGE("Unknown player type: %d", playerType);
646 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 }
648 if (p != NULL) {
649 if (p->initCheck() == NO_ERROR) {
650 p->setNotifyCallback(cookie, notifyFunc);
651 } else {
652 p.clear();
653 }
654 }
655 if (p == NULL) {
656 LOGE("Failed to create player object");
657 }
658 return p;
659}
660
661sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
662{
663 // determine if we have the right player type
664 sp<MediaPlayerBase> p = mPlayer;
665 if ((p != NULL) && (p->playerType() != playerType)) {
666 LOGV("delete player");
667 p.clear();
668 }
669 if (p == NULL) {
670 p = android::createPlayer(playerType, this, notify);
671 }
Andreas Huber603d7392011-06-30 15:47:02 -0700672
Jason Simmonsd9792ac2011-08-12 13:46:55 -0700673 if (p != NULL) {
674 p->setUID(mUID);
675 }
Andreas Huber603d7392011-06-30 15:47:02 -0700676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 return p;
678}
679
Andreas Huber25643002010-01-28 11:19:57 -0800680status_t MediaPlayerService::Client::setDataSource(
681 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682{
683 LOGV("setDataSource(%s)", url);
684 if (url == NULL)
685 return UNKNOWN_ERROR;
686
Dave Burkefc301b02011-08-30 14:39:17 +0100687 if ((strncmp(url, "http://", 7) == 0) ||
688 (strncmp(url, "https://", 8) == 0) ||
689 (strncmp(url, "rtsp://", 7) == 0)) {
690 if (!checkPermission("android.permission.INTERNET")) {
691 return PERMISSION_DENIED;
692 }
693 }
694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 if (strncmp(url, "content://", 10) == 0) {
696 // get a filedescriptor for the content Uri and
697 // pass it to the setDataSource(fd) method
698
699 String16 url16(url);
700 int fd = android::openContentProviderFile(url16);
701 if (fd < 0)
702 {
703 LOGE("Couldn't open fd for %s", url);
704 return UNKNOWN_ERROR;
705 }
706 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
707 close(fd);
708 return mStatus;
709 } else {
710 player_type playerType = getPlayerType(url);
711 LOGV("player type = %d", playerType);
712
713 // create the right type of player
714 sp<MediaPlayerBase> p = createPlayer(playerType);
715 if (p == NULL) return NO_INIT;
716
717 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700718 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
720 }
721
722 // now set data source
723 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800724 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700725 if (mStatus == NO_ERROR) {
726 mPlayer = p;
727 } else {
728 LOGE(" error: %d", mStatus);
729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 return mStatus;
731 }
732}
733
734status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
735{
736 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
737 struct stat sb;
738 int ret = fstat(fd, &sb);
739 if (ret != 0) {
740 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
741 return UNKNOWN_ERROR;
742 }
743
744 LOGV("st_dev = %llu", sb.st_dev);
745 LOGV("st_mode = %u", sb.st_mode);
746 LOGV("st_uid = %lu", sb.st_uid);
747 LOGV("st_gid = %lu", sb.st_gid);
748 LOGV("st_size = %llu", sb.st_size);
749
750 if (offset >= sb.st_size) {
751 LOGE("offset error");
752 ::close(fd);
753 return UNKNOWN_ERROR;
754 }
755 if (offset + length > sb.st_size) {
756 length = sb.st_size - offset;
757 LOGV("calculated length = %lld", length);
758 }
759
760 player_type playerType = getPlayerType(fd, offset, length);
761 LOGV("player type = %d", playerType);
762
763 // create the right type of player
764 sp<MediaPlayerBase> p = createPlayer(playerType);
765 if (p == NULL) return NO_INIT;
766
767 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700768 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
770 }
771
772 // now set data source
773 mStatus = p->setDataSource(fd, offset, length);
774 if (mStatus == NO_ERROR) mPlayer = p;
Dave Burkefc301b02011-08-30 14:39:17 +0100775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 return mStatus;
777}
778
Andreas Huber52b52cd2010-11-23 11:41:34 -0800779status_t MediaPlayerService::Client::setDataSource(
780 const sp<IStreamSource> &source) {
781 // create the right type of player
Andreas Hubera1587462010-12-15 15:17:42 -0800782 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Huber52b52cd2010-11-23 11:41:34 -0800783
784 if (p == NULL) {
785 return NO_INIT;
786 }
787
788 if (!p->hardwareOutput()) {
789 mAudioOutput = new AudioOutput(mAudioSessionId);
790 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
791 }
792
793 // now set data source
794 mStatus = p->setDataSource(source);
795
796 if (mStatus == OK) {
797 mPlayer = p;
798 }
799
800 return mStatus;
801}
802
Andreas Hubere3c01832010-08-16 08:49:37 -0700803status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804{
805 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
806 sp<MediaPlayerBase> p = getPlayer();
807 if (p == 0) return UNKNOWN_ERROR;
808 return p->setVideoSurface(surface);
809}
810
Glenn Kastencc562a32011-02-08 17:26:17 -0800811status_t MediaPlayerService::Client::setVideoSurfaceTexture(
812 const sp<ISurfaceTexture>& surfaceTexture)
813{
814 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
815 sp<MediaPlayerBase> p = getPlayer();
816 if (p == 0) return UNKNOWN_ERROR;
817 return p->setVideoSurfaceTexture(surfaceTexture);
818}
819
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700820status_t MediaPlayerService::Client::invoke(const Parcel& request,
821 Parcel *reply)
822{
823 sp<MediaPlayerBase> p = getPlayer();
824 if (p == NULL) return UNKNOWN_ERROR;
825 return p->invoke(request, reply);
826}
827
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700828// This call doesn't need to access the native player.
829status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
830{
831 status_t status;
nikobc726922009-07-20 15:07:26 -0700832 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700833
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700834 if (unmarshallFilter(filter, &allow, &status) &&
835 unmarshallFilter(filter, &drop, &status)) {
836 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700837
838 mMetadataAllow = allow;
839 mMetadataDrop = drop;
840 }
841 return status;
842}
843
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700844status_t MediaPlayerService::Client::getMetadata(
845 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700846{
nikobc726922009-07-20 15:07:26 -0700847 sp<MediaPlayerBase> player = getPlayer();
848 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700849
niko89948372009-07-16 16:39:53 -0700850 status_t status;
851 // Placeholder for the return code, updated by the caller.
852 reply->writeInt32(-1);
853
nikobc726922009-07-20 15:07:26 -0700854 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700855
856 // We don't block notifications while we fetch the data. We clear
857 // mMetadataUpdated first so we don't lose notifications happening
858 // during the rest of this call.
859 {
860 Mutex::Autolock lock(mLock);
861 if (update_only) {
niko89948372009-07-16 16:39:53 -0700862 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700863 }
864 mMetadataUpdated.clear();
865 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700866
nikobc726922009-07-20 15:07:26 -0700867 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700868
nikobc726922009-07-20 15:07:26 -0700869 metadata.appendHeader();
870 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700871
872 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700873 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700874 LOGE("getMetadata failed %d", status);
875 return status;
876 }
877
878 // FIXME: Implement filtering on the result. Not critical since
879 // filtering takes place on the update notifications already. This
880 // would be when all the metadata are fetch and a filter is set.
881
niko89948372009-07-16 16:39:53 -0700882 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700883 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700884 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700885}
886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887status_t MediaPlayerService::Client::prepareAsync()
888{
889 LOGV("[%d] prepareAsync", mConnId);
890 sp<MediaPlayerBase> p = getPlayer();
891 if (p == 0) return UNKNOWN_ERROR;
892 status_t ret = p->prepareAsync();
893#if CALLBACK_ANTAGONIZER
894 LOGD("start Antagonizer");
895 if (ret == NO_ERROR) mAntagonizer->start();
896#endif
897 return ret;
898}
899
900status_t MediaPlayerService::Client::start()
901{
902 LOGV("[%d] start", mConnId);
903 sp<MediaPlayerBase> p = getPlayer();
904 if (p == 0) return UNKNOWN_ERROR;
905 p->setLooping(mLoop);
906 return p->start();
907}
908
909status_t MediaPlayerService::Client::stop()
910{
911 LOGV("[%d] stop", mConnId);
912 sp<MediaPlayerBase> p = getPlayer();
913 if (p == 0) return UNKNOWN_ERROR;
914 return p->stop();
915}
916
917status_t MediaPlayerService::Client::pause()
918{
919 LOGV("[%d] pause", mConnId);
920 sp<MediaPlayerBase> p = getPlayer();
921 if (p == 0) return UNKNOWN_ERROR;
922 return p->pause();
923}
924
925status_t MediaPlayerService::Client::isPlaying(bool* state)
926{
927 *state = false;
928 sp<MediaPlayerBase> p = getPlayer();
929 if (p == 0) return UNKNOWN_ERROR;
930 *state = p->isPlaying();
931 LOGV("[%d] isPlaying: %d", mConnId, *state);
932 return NO_ERROR;
933}
934
935status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
936{
937 LOGV("getCurrentPosition");
938 sp<MediaPlayerBase> p = getPlayer();
939 if (p == 0) return UNKNOWN_ERROR;
940 status_t ret = p->getCurrentPosition(msec);
941 if (ret == NO_ERROR) {
942 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
943 } else {
944 LOGE("getCurrentPosition returned %d", ret);
945 }
946 return ret;
947}
948
949status_t MediaPlayerService::Client::getDuration(int *msec)
950{
951 LOGV("getDuration");
952 sp<MediaPlayerBase> p = getPlayer();
953 if (p == 0) return UNKNOWN_ERROR;
954 status_t ret = p->getDuration(msec);
955 if (ret == NO_ERROR) {
956 LOGV("[%d] getDuration = %d", mConnId, *msec);
957 } else {
958 LOGE("getDuration returned %d", ret);
959 }
960 return ret;
961}
962
963status_t MediaPlayerService::Client::seekTo(int msec)
964{
965 LOGV("[%d] seekTo(%d)", mConnId, msec);
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 return p->seekTo(msec);
969}
970
971status_t MediaPlayerService::Client::reset()
972{
973 LOGV("[%d] reset", mConnId);
974 sp<MediaPlayerBase> p = getPlayer();
975 if (p == 0) return UNKNOWN_ERROR;
976 return p->reset();
977}
978
979status_t MediaPlayerService::Client::setAudioStreamType(int type)
980{
981 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
982 // TODO: for hardware output, call player instead
983 Mutex::Autolock l(mLock);
984 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
985 return NO_ERROR;
986}
987
988status_t MediaPlayerService::Client::setLooping(int loop)
989{
990 LOGV("[%d] setLooping(%d)", mConnId, loop);
991 mLoop = loop;
992 sp<MediaPlayerBase> p = getPlayer();
993 if (p != 0) return p->setLooping(loop);
994 return NO_ERROR;
995}
996
997status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
998{
999 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
Mike J. Chenda548442011-08-15 13:24:13 -07001000
1001 // for hardware output, call player instead
1002 sp<MediaPlayerBase> p = getPlayer();
1003 {
1004 Mutex::Autolock l(mLock);
1005 if (p != 0 && p->hardwareOutput()) {
1006 MediaPlayerHWInterface* hwp =
1007 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1008 return hwp->setVolume(leftVolume, rightVolume);
1009 } else {
1010 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1011 return NO_ERROR;
1012 }
1013 }
1014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 return NO_ERROR;
1016}
1017
Eric Laurent7070b362010-07-16 07:43:46 -07001018status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1019{
1020 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1021 Mutex::Autolock l(mLock);
1022 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1023 return NO_ERROR;
1024}
1025
1026status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1027{
1028 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1029 Mutex::Autolock l(mLock);
1030 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1031 return NO_ERROR;
1032}
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001033
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001034status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1035 LOGV("[%d] setParameter(%d)", mConnId, key);
1036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 return p->setParameter(key, request);
1039}
1040
1041status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1042 LOGV("[%d] getParameter(%d)", mConnId, key);
1043 sp<MediaPlayerBase> p = getPlayer();
1044 if (p == 0) return UNKNOWN_ERROR;
1045 return p->getParameter(key, reply);
1046}
1047
Gloria Wang162ee492011-04-11 17:23:27 -07001048void MediaPlayerService::Client::notify(
1049 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050{
1051 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001052
1053 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001054 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001055 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001056
1057 if(client->shouldDropMetadata(metadata_type)) {
1058 return;
1059 }
1060
1061 // Update the list of metadata that have changed. getMetadata
1062 // also access mMetadataUpdated and clears it.
1063 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001066 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067}
1068
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001069
nikobc726922009-07-20 15:07:26 -07001070bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001071{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001072 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001073
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001074 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001075 return true;
1076 }
1077
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001078 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001079 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001080 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001081 return true;
1082 }
1083}
1084
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001085
nikobc726922009-07-20 15:07:26 -07001086void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001087 Mutex::Autolock lock(mLock);
1088 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1089 mMetadataUpdated.add(metadata_type);
1090 }
1091}
1092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093#if CALLBACK_ANTAGONIZER
1094const int Antagonizer::interval = 10000; // 10 msecs
1095
1096Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1097 mExit(false), mActive(false), mClient(client), mCb(cb)
1098{
1099 createThread(callbackThread, this);
1100}
1101
1102void Antagonizer::kill()
1103{
1104 Mutex::Autolock _l(mLock);
1105 mActive = false;
1106 mExit = true;
1107 mCondition.wait(mLock);
1108}
1109
1110int Antagonizer::callbackThread(void* user)
1111{
1112 LOGD("Antagonizer started");
1113 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1114 while (!p->mExit) {
1115 if (p->mActive) {
1116 LOGV("send event");
1117 p->mCb(p->mClient, 0, 0, 0);
1118 }
1119 usleep(interval);
1120 }
1121 Mutex::Autolock _l(p->mLock);
1122 p->mCondition.signal();
1123 LOGD("Antagonizer stopped");
1124 return 0;
1125}
1126#endif
1127
1128static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1129
1130sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1131{
1132 LOGV("decode(%s)", url);
1133 sp<MemoryBase> mem;
1134 sp<MediaPlayerBase> player;
1135
1136 // Protect our precious, precious DRMd ringtones by only allowing
1137 // decoding of http, but not filesystem paths or content Uris.
1138 // If the application wants to decode those, it should open a
1139 // filedescriptor for them and use that.
1140 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1141 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1142 return mem;
1143 }
1144
1145 player_type playerType = getPlayerType(url);
1146 LOGV("player type = %d", playerType);
1147
1148 // create the right type of player
1149 sp<AudioCache> cache = new AudioCache(url);
1150 player = android::createPlayer(playerType, cache.get(), cache->notify);
1151 if (player == NULL) goto Exit;
1152 if (player->hardwareOutput()) goto Exit;
1153
1154 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1155
1156 // set data source
1157 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1158
1159 LOGV("prepare");
1160 player->prepareAsync();
1161
1162 LOGV("wait for prepare");
1163 if (cache->wait() != NO_ERROR) goto Exit;
1164
1165 LOGV("start");
1166 player->start();
1167
1168 LOGV("wait for playback complete");
Eric Laurent9968a362011-09-27 09:48:56 -07001169 cache->wait();
1170 // in case of error, return what was successfully decoded.
1171 if (cache->size() == 0) {
1172 goto Exit;
1173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174
1175 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1176 *pSampleRate = cache->sampleRate();
1177 *pNumChannels = cache->channelCount();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001178 *pFormat = (int)cache->format();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1180
1181Exit:
1182 if (player != 0) player->reset();
1183 return mem;
1184}
1185
1186sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1187{
1188 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1189 sp<MemoryBase> mem;
1190 sp<MediaPlayerBase> player;
1191
1192 player_type playerType = getPlayerType(fd, offset, length);
1193 LOGV("player type = %d", playerType);
1194
1195 // create the right type of player
1196 sp<AudioCache> cache = new AudioCache("decode_fd");
1197 player = android::createPlayer(playerType, cache.get(), cache->notify);
1198 if (player == NULL) goto Exit;
1199 if (player->hardwareOutput()) goto Exit;
1200
1201 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1202
1203 // set data source
1204 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1205
1206 LOGV("prepare");
1207 player->prepareAsync();
1208
1209 LOGV("wait for prepare");
1210 if (cache->wait() != NO_ERROR) goto Exit;
1211
1212 LOGV("start");
1213 player->start();
1214
1215 LOGV("wait for playback complete");
Eric Laurent9968a362011-09-27 09:48:56 -07001216 cache->wait();
1217 // in case of error, return what was successfully decoded.
1218 if (cache->size() == 0) {
1219 goto Exit;
1220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221
1222 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1223 *pSampleRate = cache->sampleRate();
1224 *pNumChannels = cache->channelCount();
1225 *pFormat = cache->format();
1226 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1227
1228Exit:
1229 if (player != 0) player->reset();
1230 ::close(fd);
1231 return mem;
1232}
1233
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235#undef LOG_TAG
1236#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001237MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001238 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001239 mCallbackCookie(NULL),
1240 mSessionId(sessionId) {
1241 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001243 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 mLeftVolume = 1.0;
1245 mRightVolume = 1.0;
1246 mLatency = 0;
1247 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001248 mAuxEffectId = 0;
1249 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 setMinBufferCount();
1251}
1252
1253MediaPlayerService::AudioOutput::~AudioOutput()
1254{
1255 close();
1256}
1257
1258void MediaPlayerService::AudioOutput::setMinBufferCount()
1259{
1260 char value[PROPERTY_VALUE_MAX];
1261 if (property_get("ro.kernel.qemu", value, 0)) {
1262 mIsOnEmulator = true;
1263 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1264 }
1265}
1266
1267bool MediaPlayerService::AudioOutput::isOnEmulator()
1268{
1269 setMinBufferCount();
1270 return mIsOnEmulator;
1271}
1272
1273int MediaPlayerService::AudioOutput::getMinBufferCount()
1274{
1275 setMinBufferCount();
1276 return mMinBufferCount;
1277}
1278
1279ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1280{
1281 if (mTrack == 0) return NO_INIT;
1282 return mTrack->frameCount() * frameSize();
1283}
1284
1285ssize_t MediaPlayerService::AudioOutput::frameCount() const
1286{
1287 if (mTrack == 0) return NO_INIT;
1288 return mTrack->frameCount();
1289}
1290
1291ssize_t MediaPlayerService::AudioOutput::channelCount() const
1292{
1293 if (mTrack == 0) return NO_INIT;
1294 return mTrack->channelCount();
1295}
1296
1297ssize_t MediaPlayerService::AudioOutput::frameSize() const
1298{
1299 if (mTrack == 0) return NO_INIT;
1300 return mTrack->frameSize();
1301}
1302
1303uint32_t MediaPlayerService::AudioOutput::latency () const
1304{
1305 return mLatency;
1306}
1307
1308float MediaPlayerService::AudioOutput::msecsPerFrame() const
1309{
1310 return mMsecsPerFrame;
1311}
1312
Eric Laurent0986e792010-01-19 17:37:09 -08001313status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1314{
1315 if (mTrack == 0) return NO_INIT;
1316 return mTrack->getPosition(position);
1317}
1318
Andreas Hubere46b7be2009-07-14 16:56:47 -07001319status_t MediaPlayerService::AudioOutput::open(
1320 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1321 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001323 mCallback = cb;
1324 mCallbackCookie = cookie;
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // Check argument "bufferCount" against the mininum buffer count
1327 if (bufferCount < mMinBufferCount) {
1328 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1329 bufferCount = mMinBufferCount;
1330
1331 }
Eric Laurent619346f2010-06-21 09:27:30 -07001332 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 if (mTrack) close();
1334 int afSampleRate;
1335 int afFrameCount;
1336 int frameCount;
1337
1338 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1339 return NO_INIT;
1340 }
1341 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1342 return NO_INIT;
1343 }
1344
1345 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001346
1347 AudioTrack *t;
1348 if (mCallback != NULL) {
1349 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001350 mStreamType,
1351 sampleRate,
1352 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001353 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001354 frameCount,
1355 0 /* flags */,
1356 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001357 this,
1358 0,
1359 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001360 } else {
1361 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001362 mStreamType,
1363 sampleRate,
1364 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001365 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001366 frameCount,
1367 0,
1368 NULL,
1369 NULL,
1370 0,
1371 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001372 }
1373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1375 LOGE("Unable to create audio track");
1376 delete t;
1377 return NO_INIT;
1378 }
1379
1380 LOGV("setVolume");
1381 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001384 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001386
1387 t->setAuxEffectSendLevel(mSendLevel);
1388 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389}
1390
1391void MediaPlayerService::AudioOutput::start()
1392{
1393 LOGV("start");
1394 if (mTrack) {
1395 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001396 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 mTrack->start();
1398 }
1399}
1400
Marco Nelissene274db12010-01-12 09:23:54 -08001401
1402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1404{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001405 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001408 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001409 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001410 return ret;
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 return NO_INIT;
1413}
1414
1415void MediaPlayerService::AudioOutput::stop()
1416{
1417 LOGV("stop");
1418 if (mTrack) mTrack->stop();
1419}
1420
1421void MediaPlayerService::AudioOutput::flush()
1422{
1423 LOGV("flush");
1424 if (mTrack) mTrack->flush();
1425}
1426
1427void MediaPlayerService::AudioOutput::pause()
1428{
1429 LOGV("pause");
1430 if (mTrack) mTrack->pause();
1431}
1432
1433void MediaPlayerService::AudioOutput::close()
1434{
1435 LOGV("close");
1436 delete mTrack;
1437 mTrack = 0;
1438}
1439
1440void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1441{
1442 LOGV("setVolume(%f, %f)", left, right);
1443 mLeftVolume = left;
1444 mRightVolume = right;
1445 if (mTrack) {
1446 mTrack->setVolume(left, right);
1447 }
1448}
1449
Eric Laurent7070b362010-07-16 07:43:46 -07001450status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1451{
1452 LOGV("setAuxEffectSendLevel(%f)", level);
1453 mSendLevel = level;
1454 if (mTrack) {
1455 return mTrack->setAuxEffectSendLevel(level);
1456 }
1457 return NO_ERROR;
1458}
1459
1460status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1461{
1462 LOGV("attachAuxEffect(%d)", effectId);
1463 mAuxEffectId = effectId;
1464 if (mTrack) {
1465 return mTrack->attachAuxEffect(effectId);
1466 }
1467 return NO_ERROR;
1468}
1469
Andreas Hubere46b7be2009-07-14 16:56:47 -07001470// static
1471void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastene46a86f2011-06-01 15:20:35 -07001472 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001473 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001474 if (event != AudioTrack::EVENT_MORE_DATA) {
1475 return;
1476 }
1477
1478 AudioOutput *me = (AudioOutput *)cookie;
1479 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1480
Andreas Huber6ed937e2010-02-09 16:59:18 -08001481 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001482 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001483
Andreas Huberc6e3b272011-04-04 11:43:40 -07001484 if (actualSize == 0 && buffer->size > 0) {
1485 // We've reached EOS but the audio track is not stopped yet,
1486 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001487
Andreas Huberc6e3b272011-04-04 11:43:40 -07001488 memset(buffer->raw, 0, buffer->size);
1489 actualSize = buffer->size;
1490 }
1491
1492 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001493}
1494
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001495int MediaPlayerService::AudioOutput::getSessionId()
1496{
1497 return mSessionId;
1498}
1499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500#undef LOG_TAG
1501#define LOG_TAG "AudioCache"
1502MediaPlayerService::AudioCache::AudioCache(const char* name) :
1503 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1504 mError(NO_ERROR), mCommandComplete(false)
1505{
1506 // create ashmem heap
1507 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1508}
1509
1510uint32_t MediaPlayerService::AudioCache::latency () const
1511{
1512 return 0;
1513}
1514
1515float MediaPlayerService::AudioCache::msecsPerFrame() const
1516{
1517 return mMsecsPerFrame;
1518}
1519
Eric Laurent0986e792010-01-19 17:37:09 -08001520status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1521{
1522 if (position == 0) return BAD_VALUE;
1523 *position = mSize;
1524 return NO_ERROR;
1525}
1526
Andreas Huber6ed937e2010-02-09 16:59:18 -08001527////////////////////////////////////////////////////////////////////////////////
1528
1529struct CallbackThread : public Thread {
1530 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1531 MediaPlayerBase::AudioSink::AudioCallback cb,
1532 void *cookie);
1533
1534protected:
1535 virtual ~CallbackThread();
1536
1537 virtual bool threadLoop();
1538
1539private:
1540 wp<MediaPlayerBase::AudioSink> mSink;
1541 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1542 void *mCookie;
1543 void *mBuffer;
1544 size_t mBufferSize;
1545
1546 CallbackThread(const CallbackThread &);
1547 CallbackThread &operator=(const CallbackThread &);
1548};
1549
1550CallbackThread::CallbackThread(
1551 const wp<MediaPlayerBase::AudioSink> &sink,
1552 MediaPlayerBase::AudioSink::AudioCallback cb,
1553 void *cookie)
1554 : mSink(sink),
1555 mCallback(cb),
1556 mCookie(cookie),
1557 mBuffer(NULL),
1558 mBufferSize(0) {
1559}
1560
1561CallbackThread::~CallbackThread() {
1562 if (mBuffer) {
1563 free(mBuffer);
1564 mBuffer = NULL;
1565 }
1566}
1567
1568bool CallbackThread::threadLoop() {
1569 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1570 if (sink == NULL) {
1571 return false;
1572 }
1573
1574 if (mBuffer == NULL) {
1575 mBufferSize = sink->bufferSize();
1576 mBuffer = malloc(mBufferSize);
1577 }
1578
1579 size_t actualSize =
1580 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1581
1582 if (actualSize > 0) {
1583 sink->write(mBuffer, actualSize);
1584 }
1585
1586 return true;
1587}
1588
1589////////////////////////////////////////////////////////////////////////////////
1590
Andreas Hubere46b7be2009-07-14 16:56:47 -07001591status_t MediaPlayerService::AudioCache::open(
1592 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1593 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594{
Dave Sparks14f89402009-12-09 20:20:26 -08001595 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001596 if (mHeap->getHeapID() < 0) {
1597 return NO_INIT;
1598 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 mSampleRate = sampleRate;
1601 mChannelCount = (uint16_t)channelCount;
1602 mFormat = (uint16_t)format;
1603 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001604
1605 if (cb != NULL) {
1606 mCallbackThread = new CallbackThread(this, cb, cookie);
1607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 return NO_ERROR;
1609}
1610
Andreas Huber6ed937e2010-02-09 16:59:18 -08001611void MediaPlayerService::AudioCache::start() {
1612 if (mCallbackThread != NULL) {
1613 mCallbackThread->run("AudioCache callback");
1614 }
1615}
1616
1617void MediaPlayerService::AudioCache::stop() {
1618 if (mCallbackThread != NULL) {
1619 mCallbackThread->requestExitAndWait();
1620 }
1621}
1622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1624{
1625 LOGV("write(%p, %u)", buffer, size);
1626 if ((buffer == 0) || (size == 0)) return size;
1627
1628 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1629 if (p == NULL) return NO_INIT;
1630 p += mSize;
1631 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1632 if (mSize + size > mHeap->getSize()) {
1633 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1634 size = mHeap->getSize() - mSize;
1635 }
1636 memcpy(p, buffer, size);
1637 mSize += size;
1638 return size;
1639}
1640
1641// call with lock held
1642status_t MediaPlayerService::AudioCache::wait()
1643{
1644 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001645 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 mSignal.wait(mLock);
1647 }
1648 mCommandComplete = false;
1649
1650 if (mError == NO_ERROR) {
1651 LOGV("wait - success");
1652 } else {
1653 LOGV("wait - error");
1654 }
1655 return mError;
1656}
1657
Gloria Wang162ee492011-04-11 17:23:27 -07001658void MediaPlayerService::AudioCache::notify(
1659 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660{
1661 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1662 AudioCache* p = static_cast<AudioCache*>(cookie);
1663
1664 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001665 switch (msg)
1666 {
1667 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 LOGE("Error %d, %d occurred", ext1, ext2);
1669 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001670 break;
1671 case MEDIA_PREPARED:
1672 LOGV("prepared");
1673 break;
1674 case MEDIA_PLAYBACK_COMPLETE:
1675 LOGV("playback complete");
1676 break;
1677 default:
1678 LOGV("ignored");
1679 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
1681
1682 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001683 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 p->mCommandComplete = true;
1685 p->mSignal.signal();
1686}
1687
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001688int MediaPlayerService::AudioCache::getSessionId()
1689{
1690 return 0;
1691}
1692
Gloria Wangd211f412011-02-19 18:37:57 -08001693void MediaPlayerService::addBatteryData(uint32_t params)
1694{
1695 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001696
1697 int32_t time = systemTime() / 1000000L;
1698
1699 // change audio output devices. This notification comes from AudioFlinger
1700 if ((params & kBatteryDataSpeakerOn)
1701 || (params & kBatteryDataOtherAudioDeviceOn)) {
1702
1703 int deviceOn[NUM_AUDIO_DEVICES];
1704 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1705 deviceOn[i] = 0;
1706 }
1707
1708 if ((params & kBatteryDataSpeakerOn)
1709 && (params & kBatteryDataOtherAudioDeviceOn)) {
1710 deviceOn[SPEAKER_AND_OTHER] = 1;
1711 } else if (params & kBatteryDataSpeakerOn) {
1712 deviceOn[SPEAKER] = 1;
1713 } else {
1714 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1715 }
1716
1717 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1718 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1719
1720 if (mBatteryAudio.refCount > 0) { // if playing audio
1721 if (!deviceOn[i]) {
1722 mBatteryAudio.lastTime[i] += time;
1723 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1724 mBatteryAudio.lastTime[i] = 0;
1725 } else {
1726 mBatteryAudio.lastTime[i] = 0 - time;
1727 }
1728 }
1729
1730 mBatteryAudio.deviceOn[i] = deviceOn[i];
1731 }
1732 }
1733 return;
1734 }
1735
1736 // an sudio stream is started
1737 if (params & kBatteryDataAudioFlingerStart) {
1738 // record the start time only if currently no other audio
1739 // is being played
1740 if (mBatteryAudio.refCount == 0) {
1741 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1742 if (mBatteryAudio.deviceOn[i]) {
1743 mBatteryAudio.lastTime[i] -= time;
1744 }
1745 }
1746 }
1747
1748 mBatteryAudio.refCount ++;
1749 return;
1750
1751 } else if (params & kBatteryDataAudioFlingerStop) {
1752 if (mBatteryAudio.refCount <= 0) {
1753 LOGW("Battery track warning: refCount is <= 0");
1754 return;
1755 }
1756
1757 // record the stop time only if currently this is the only
1758 // audio being played
1759 if (mBatteryAudio.refCount == 1) {
1760 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1761 if (mBatteryAudio.deviceOn[i]) {
1762 mBatteryAudio.lastTime[i] += time;
1763 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1764 mBatteryAudio.lastTime[i] = 0;
1765 }
1766 }
1767 }
1768
1769 mBatteryAudio.refCount --;
1770 return;
1771 }
1772
Gloria Wangd211f412011-02-19 18:37:57 -08001773 int uid = IPCThreadState::self()->getCallingUid();
1774 if (uid == AID_MEDIA) {
1775 return;
1776 }
1777 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001778
1779 if (index < 0) { // create a new entry for this UID
1780 BatteryUsageInfo info;
1781 info.audioTotalTime = 0;
1782 info.videoTotalTime = 0;
1783 info.audioLastTime = 0;
1784 info.videoLastTime = 0;
1785 info.refCount = 0;
1786
Gloria Wang9b3f1522011-02-24 14:51:45 -08001787 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1788 LOGE("Battery track error: no memory for new app");
1789 return;
1790 }
Gloria Wangd211f412011-02-19 18:37:57 -08001791 }
1792
1793 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1794
1795 if (params & kBatteryDataCodecStarted) {
1796 if (params & kBatteryDataTrackAudio) {
1797 info.audioLastTime -= time;
1798 info.refCount ++;
1799 }
1800 if (params & kBatteryDataTrackVideo) {
1801 info.videoLastTime -= time;
1802 info.refCount ++;
1803 }
1804 } else {
1805 if (info.refCount == 0) {
1806 LOGW("Battery track warning: refCount is already 0");
1807 return;
1808 } else if (info.refCount < 0) {
1809 LOGE("Battery track error: refCount < 0");
1810 mBatteryData.removeItem(uid);
1811 return;
1812 }
1813
1814 if (params & kBatteryDataTrackAudio) {
1815 info.audioLastTime += time;
1816 info.refCount --;
1817 }
1818 if (params & kBatteryDataTrackVideo) {
1819 info.videoLastTime += time;
1820 info.refCount --;
1821 }
1822
1823 // no stream is being played by this UID
1824 if (info.refCount == 0) {
1825 info.audioTotalTime += info.audioLastTime;
1826 info.audioLastTime = 0;
1827 info.videoTotalTime += info.videoLastTime;
1828 info.videoLastTime = 0;
1829 }
1830 }
1831}
1832
1833status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1834 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001835
1836 // audio output devices usage
1837 int32_t time = systemTime() / 1000000L; //in ms
1838 int32_t totalTime;
1839
1840 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1841 totalTime = mBatteryAudio.totalTime[i];
1842
1843 if (mBatteryAudio.deviceOn[i]
1844 && (mBatteryAudio.lastTime[i] != 0)) {
1845 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1846 totalTime += tmpTime;
1847 }
1848
1849 reply->writeInt32(totalTime);
1850 // reset the total time
1851 mBatteryAudio.totalTime[i] = 0;
1852 }
1853
1854 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001855 BatteryUsageInfo info;
1856 int size = mBatteryData.size();
1857
1858 reply->writeInt32(size);
1859 int i = 0;
1860
1861 while (i < size) {
1862 info = mBatteryData.valueAt(i);
1863
1864 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1865 reply->writeInt32(info.audioTotalTime);
1866 reply->writeInt32(info.videoTotalTime);
1867
1868 info.audioTotalTime = 0;
1869 info.videoTotalTime = 0;
1870
1871 // remove the UID entry where no stream is being played
1872 if (info.refCount <= 0) {
1873 mBatteryData.removeItemsAt(i);
1874 size --;
1875 i --;
1876 }
1877 i++;
1878 }
1879 return NO_ERROR;
1880}
nikobc726922009-07-20 15:07:26 -07001881} // namespace android