blob: b6553586c9fad3b78eb48bd289d10569d1b8c59f [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>
Jamie Gennis2fa0ac22011-10-26 18:36:31 -070043#include <gui/SurfaceTextureClient.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070044#include <utils/Errors.h> // for status_t
45#include <utils/String8.h>
Marco Nelissenc39d2e32009-09-20 10:42:13 -070046#include <utils/SystemClock.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070047#include <utils/Vector.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048#include <cutils/properties.h>
49
50#include <media/MediaPlayerInterface.h>
51#include <media/mediarecorder.h>
52#include <media/MediaMetadataRetrieverInterface.h>
nikobc726922009-07-20 15:07:26 -070053#include <media/Metadata.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054#include <media/AudioTrack.h>
James Donged732462011-03-14 17:01:38 -070055#include <media/MemoryLeakTrackUtil.h>
Eric Laurent9968a362011-09-27 09:48:56 -070056#include <media/stagefright/MediaErrors.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
Dima Zavin34bb4192011-05-11 14:15:23 -070058#include <system/audio.h>
Dima Zavin24fc2fb2011-04-19 22:30:36 -070059
Gloria Wangd211f412011-02-19 18:37:57 -080060#include <private/android_filesystem_config.h>
61
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062#include "MediaRecorderClient.h"
63#include "MediaPlayerService.h"
64#include "MetadataRetrieverClient.h"
65
66#include "MidiFile.h"
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070067#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070068#include "StagefrightPlayer.h"
Andreas Hubera1587462010-12-15 15:17:42 -080069#include "nuplayer/NuPlayerDriver.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070070
Andreas Hubere46b7be2009-07-14 16:56:47 -070071#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070072
Nicolas Cataniab2c69392009-07-08 08:57:42 -070073namespace {
nikobc726922009-07-20 15:07:26 -070074using android::media::Metadata;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070075using android::status_t;
76using android::OK;
77using android::BAD_VALUE;
78using android::NOT_ENOUGH_DATA;
79using android::Parcel;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070080
81// Max number of entries in the filter.
82const int kMaxFilterSize = 64; // I pulled that out of thin air.
83
nikobc726922009-07-20 15:07:26 -070084// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070085
Nicolas Cataniab2c69392009-07-08 08:57:42 -070086
87// Unmarshall a filter from a Parcel.
88// Filter format in a parcel:
89//
90// 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
91// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92// | number of entries (n) |
93// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94// | metadata type 1 |
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// | metadata type 2 |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// ....
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | metadata type n |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102//
103// @param p Parcel that should start with a filter.
104// @param[out] filter On exit contains the list of metadata type to be
105// filtered.
106// @param[out] status On exit contains the status code to be returned.
107// @return true if the parcel starts with a valid filter.
108bool unmarshallFilter(const Parcel& p,
nikobc726922009-07-20 15:07:26 -0700109 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700110 status_t *status)
111{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700112 int32_t val;
113 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700114 {
115 LOGE("Failed to read filter's length");
116 *status = NOT_ENOUGH_DATA;
117 return false;
118 }
119
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700120 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700121 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700122 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700123 *status = BAD_VALUE;
124 return false;
125 }
126
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700127 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700128
129 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700130 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700131
nikobc726922009-07-20 15:07:26 -0700132 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700133
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700134
135 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700136 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700137 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700138 *status = NOT_ENOUGH_DATA;
139 return false;
140 }
141
nikobc726922009-07-20 15:07:26 -0700142 const Metadata::Type *data =
143 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700144
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700145 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700146 {
147 LOGE("Filter had no data");
148 *status = BAD_VALUE;
149 return false;
150 }
151
152 // TODO: The stl impl of vector would be more efficient here
153 // because it degenerates into a memcpy on pod types. Try to
154 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700155 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700156 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700157 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700158 ++data;
159 }
160 *status = OK;
161 return true;
162}
163
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700164// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700165// @param val To be searched.
166// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700167bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700168{
169 // Deal with empty and ANY right away
170 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700171 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700172
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700173 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700174}
175
176} // anonymous namespace
177
178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179namespace android {
180
Dave Burkefc301b02011-08-30 14:39:17 +0100181static bool checkPermission(const char* permissionString) {
182#ifndef HAVE_ANDROID_OS
183 return true;
184#endif
185 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
186 bool ok = checkCallingPermission(String16(permissionString));
187 if (!ok) LOGE("Request requires %s", permissionString);
188 return ok;
189}
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191// TODO: Temp hack until we can register players
192typedef struct {
193 const char *extension;
194 const player_type playertype;
195} extmap;
196extmap FILE_EXTS [] = {
197 {".mid", SONIVOX_PLAYER},
198 {".midi", SONIVOX_PLAYER},
199 {".smf", SONIVOX_PLAYER},
200 {".xmf", SONIVOX_PLAYER},
201 {".imy", SONIVOX_PLAYER},
202 {".rtttl", SONIVOX_PLAYER},
203 {".rtx", SONIVOX_PLAYER},
204 {".ota", SONIVOX_PLAYER},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205};
206
207// 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 -0800208/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
209/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
210
211void MediaPlayerService::instantiate() {
212 defaultServiceManager()->addService(
213 String16("media.player"), new MediaPlayerService());
214}
215
216MediaPlayerService::MediaPlayerService()
217{
218 LOGV("MediaPlayerService created");
219 mNextConnId = 1;
Gloria Wang9b3f1522011-02-24 14:51:45 -0800220
221 mBatteryAudio.refCount = 0;
222 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
223 mBatteryAudio.deviceOn[i] = 0;
224 mBatteryAudio.lastTime[i] = 0;
225 mBatteryAudio.totalTime[i] = 0;
226 }
227 // speaker is on by default
228 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229}
230
231MediaPlayerService::~MediaPlayerService()
232{
233 LOGV("MediaPlayerService destroyed");
234}
235
236sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
237{
Gloria Wang608a2632009-10-29 15:46:37 -0700238 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
239 wp<MediaRecorderClient> w = recorder;
240 Mutex::Autolock lock(mLock);
241 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 LOGV("Create new media recorder client from pid %d", pid);
243 return recorder;
244}
245
Gloria Wang608a2632009-10-29 15:46:37 -0700246void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
247{
248 Mutex::Autolock lock(mLock);
249 mMediaRecorderClients.remove(client);
250 LOGV("Delete media recorder client");
251}
252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
254{
255 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
256 LOGV("Create new media retriever from pid %d", pid);
257 return retriever;
258}
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burkefc301b02011-08-30 14:39:17 +0100261 int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262{
263 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber603d7392011-06-30 15:47:02 -0700264
265 sp<Client> c = new Client(
266 this, pid, connId, client, audioSessionId,
267 IPCThreadState::self()->getCallingUid());
268
Dave Burkefc301b02011-08-30 14:39:17 +0100269 LOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
270 IPCThreadState::self()->getCallingUid());
271
272 wp<Client> w = c;
273 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 Mutex::Autolock lock(mLock);
275 mClients.add(w);
276 }
Andreas Huber52b52cd2010-11-23 11:41:34 -0800277 return c;
278}
279
Andreas Huber784202e2009-10-15 13:46:54 -0700280sp<IOMX> MediaPlayerService::getOMX() {
281 Mutex::Autolock autoLock(mLock);
282
283 if (mOMX.get() == NULL) {
284 mOMX = new OMX;
285 }
286
287 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700288}
289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
295
296 result.append(" AudioCache\n");
297 if (mHeap != 0) {
298 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
299 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
300 result.append(buffer);
301 }
302 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
303 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
304 result.append(buffer);
305 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
306 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
307 result.append(buffer);
308 ::write(fd, result.string(), result.size());
309 return NO_ERROR;
310}
311
312status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
313{
314 const size_t SIZE = 256;
315 char buffer[SIZE];
316 String8 result;
317
318 result.append(" AudioOutput\n");
319 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
320 mStreamType, mLeftVolume, mRightVolume);
321 result.append(buffer);
322 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
323 mMsecsPerFrame, mLatency);
324 result.append(buffer);
Eric Laurent7070b362010-07-16 07:43:46 -0700325 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
326 mAuxEffectId, mSendLevel);
327 result.append(buffer);
328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 ::write(fd, result.string(), result.size());
330 if (mTrack != 0) {
331 mTrack->dump(fd, args);
332 }
333 return NO_ERROR;
334}
335
336status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
337{
338 const size_t SIZE = 256;
339 char buffer[SIZE];
340 String8 result;
341 result.append(" Client\n");
342 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
343 mPid, mConnId, mStatus, mLoop?"true": "false");
344 result.append(buffer);
345 write(fd, result.string(), result.size());
Andreas Huberfddf5d92011-06-07 15:52:25 -0700346 if (mPlayer != NULL) {
347 mPlayer->dump(fd, args);
348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 if (mAudioOutput != 0) {
350 mAudioOutput->dump(fd, args);
351 }
352 write(fd, "\n", 1);
353 return NO_ERROR;
354}
355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
357{
358 const size_t SIZE = 256;
359 char buffer[SIZE];
360 String8 result;
361 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
362 snprintf(buffer, SIZE, "Permission Denial: "
363 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
364 IPCThreadState::self()->getCallingPid(),
365 IPCThreadState::self()->getCallingUid());
366 result.append(buffer);
367 } else {
368 Mutex::Autolock lock(mLock);
369 for (int i = 0, n = mClients.size(); i < n; ++i) {
370 sp<Client> c = mClients[i].promote();
371 if (c != 0) c->dump(fd, args);
372 }
James Dong929642e2010-07-08 11:16:11 -0700373 if (mMediaRecorderClients.size() == 0) {
374 result.append(" No media recorder client\n\n");
375 } else {
376 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
377 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Dongdc8bbe792011-10-18 22:29:20 -0700378 if (c != 0) {
379 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
380 result.append(buffer);
381 write(fd, result.string(), result.size());
382 result = "\n";
383 c->dump(fd, args);
384 }
James Dong929642e2010-07-08 11:16:11 -0700385 }
Gloria Wang608a2632009-10-29 15:46:37 -0700386 }
387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 result.append(" Files opened and/or mapped:\n");
Glenn Kasten6af763b2011-05-04 17:58:57 -0700389 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 FILE *f = fopen(buffer, "r");
391 if (f) {
392 while (!feof(f)) {
393 fgets(buffer, SIZE, f);
Dave Sparks124a3462010-09-27 16:55:18 -0700394 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 strstr(buffer, " /system/sounds/") ||
Dave Sparks124a3462010-09-27 16:55:18 -0700396 strstr(buffer, " /data/") ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 strstr(buffer, " /system/media/")) {
398 result.append(" ");
399 result.append(buffer);
400 }
401 }
402 fclose(f);
403 } else {
404 result.append("couldn't open ");
405 result.append(buffer);
406 result.append("\n");
407 }
408
Glenn Kasten6af763b2011-05-04 17:58:57 -0700409 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 DIR *d = opendir(buffer);
411 if (d) {
412 struct dirent *ent;
413 while((ent = readdir(d)) != NULL) {
414 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten6af763b2011-05-04 17:58:57 -0700415 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 struct stat s;
417 if (lstat(buffer, &s) == 0) {
418 if ((s.st_mode & S_IFMT) == S_IFLNK) {
419 char linkto[256];
420 int len = readlink(buffer, linkto, sizeof(linkto));
421 if(len > 0) {
422 if(len > 255) {
423 linkto[252] = '.';
424 linkto[253] = '.';
425 linkto[254] = '.';
426 linkto[255] = 0;
427 } else {
428 linkto[len] = 0;
429 }
Dave Sparks124a3462010-09-27 16:55:18 -0700430 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks124a3462010-09-27 16:55:18 -0700432 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 strstr(linkto, "/system/media/") == linkto) {
434 result.append(" ");
435 result.append(buffer);
436 result.append(" -> ");
437 result.append(linkto);
438 result.append("\n");
439 }
440 }
441 } else {
442 result.append(" unexpected type for ");
443 result.append(buffer);
444 result.append("\n");
445 }
446 }
447 }
448 }
449 closedir(d);
450 } else {
451 result.append("couldn't open ");
452 result.append(buffer);
453 result.append("\n");
454 }
455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 bool dumpMem = false;
457 for (size_t i = 0; i < args.size(); i++) {
458 if (args[i] == String16("-m")) {
459 dumpMem = true;
460 }
461 }
462 if (dumpMem) {
James Donged732462011-03-14 17:01:38 -0700463 dumpMemoryAddresses(fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 }
466 write(fd, result.string(), result.size());
467 return NO_ERROR;
468}
469
470void MediaPlayerService::removeClient(wp<Client> client)
471{
472 Mutex::Autolock lock(mLock);
473 mClients.remove(client);
474}
475
Andreas Huber603d7392011-06-30 15:47:02 -0700476MediaPlayerService::Client::Client(
477 const sp<MediaPlayerService>& service, pid_t pid,
478 int32_t connId, const sp<IMediaPlayerClient>& client,
479 int audioSessionId, uid_t uid)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480{
481 LOGV("Client(%d) constructor", connId);
482 mPid = pid;
483 mConnId = connId;
484 mService = service;
485 mClient = client;
486 mLoop = false;
487 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700488 mAudioSessionId = audioSessionId;
Andreas Huber603d7392011-06-30 15:47:02 -0700489 mUID = uid;
Eric Laurent619346f2010-06-21 09:27:30 -0700490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491#if CALLBACK_ANTAGONIZER
492 LOGD("create Antagonizer");
493 mAntagonizer = new Antagonizer(notify, this);
494#endif
495}
496
497MediaPlayerService::Client::~Client()
498{
499 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
500 mAudioOutput.clear();
501 wp<Client> client(this);
502 disconnect();
503 mService->removeClient(client);
504}
505
506void MediaPlayerService::Client::disconnect()
507{
508 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
509 // grab local reference and clear main reference to prevent future
510 // access to object
511 sp<MediaPlayerBase> p;
512 {
513 Mutex::Autolock l(mLock);
514 p = mPlayer;
515 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700516 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 mPlayer.clear();
519
520 // clear the notification to prevent callbacks to dead client
521 // and reset the player. We assume the player will serialize
522 // access to itself if necessary.
523 if (p != 0) {
524 p->setNotifyCallback(0, 0);
525#if CALLBACK_ANTAGONIZER
526 LOGD("kill Antagonizer");
527 mAntagonizer->kill();
528#endif
529 p->reset();
530 }
531
Jamie Gennis2fa0ac22011-10-26 18:36:31 -0700532 disconnectNativeWindow();
533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 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
Andreas Hubera6be6dc2011-10-11 15:24:07 -0700592 if (!strncasecmp("rtsp://", url, 7)) {
593 return NU_PLAYER;
594 }
595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 // use MidiFile for MIDI extensions
597 int lenURL = strlen(url);
598 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
599 int len = strlen(FILE_EXTS[i].extension);
600 int start = lenURL - len;
601 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900602 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700603 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605 }
606 }
607
Andreas Huber0d596d42009-08-07 09:30:32 -0700608 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609}
610
611static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
612 notify_callback_f notifyFunc)
613{
614 sp<MediaPlayerBase> p;
615 switch (playerType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 case SONIVOX_PLAYER:
617 LOGV(" create MidiFile");
618 p = new MidiFile();
619 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700620 case STAGEFRIGHT_PLAYER:
621 LOGV(" create StagefrightPlayer");
622 p = new StagefrightPlayer;
623 break;
Andreas Hubera1587462010-12-15 15:17:42 -0800624 case NU_PLAYER:
625 LOGV(" create NuPlayer");
626 p = new NuPlayerDriver;
627 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700628 case TEST_PLAYER:
629 LOGV("Create Test Player stub");
630 p = new TestPlayerStub();
631 break;
James Dong8ec2d9a2010-11-10 18:42:40 -0800632 default:
633 LOGE("Unknown player type: %d", playerType);
634 return NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636 if (p != NULL) {
637 if (p->initCheck() == NO_ERROR) {
638 p->setNotifyCallback(cookie, notifyFunc);
639 } else {
640 p.clear();
641 }
642 }
643 if (p == NULL) {
644 LOGE("Failed to create player object");
645 }
646 return p;
647}
648
649sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
650{
651 // determine if we have the right player type
652 sp<MediaPlayerBase> p = mPlayer;
653 if ((p != NULL) && (p->playerType() != playerType)) {
654 LOGV("delete player");
655 p.clear();
656 }
657 if (p == NULL) {
658 p = android::createPlayer(playerType, this, notify);
659 }
Andreas Huber603d7392011-06-30 15:47:02 -0700660
Jason Simmonsd9792ac2011-08-12 13:46:55 -0700661 if (p != NULL) {
662 p->setUID(mUID);
663 }
Andreas Huber603d7392011-06-30 15:47:02 -0700664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 return p;
666}
667
Andreas Huber25643002010-01-28 11:19:57 -0800668status_t MediaPlayerService::Client::setDataSource(
669 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670{
671 LOGV("setDataSource(%s)", url);
672 if (url == NULL)
673 return UNKNOWN_ERROR;
674
Dave Burkefc301b02011-08-30 14:39:17 +0100675 if ((strncmp(url, "http://", 7) == 0) ||
676 (strncmp(url, "https://", 8) == 0) ||
677 (strncmp(url, "rtsp://", 7) == 0)) {
678 if (!checkPermission("android.permission.INTERNET")) {
679 return PERMISSION_DENIED;
680 }
681 }
682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 if (strncmp(url, "content://", 10) == 0) {
684 // get a filedescriptor for the content Uri and
685 // pass it to the setDataSource(fd) method
686
687 String16 url16(url);
688 int fd = android::openContentProviderFile(url16);
689 if (fd < 0)
690 {
691 LOGE("Couldn't open fd for %s", url);
692 return UNKNOWN_ERROR;
693 }
694 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
695 close(fd);
696 return mStatus;
697 } else {
698 player_type playerType = getPlayerType(url);
699 LOGV("player type = %d", playerType);
700
701 // create the right type of player
702 sp<MediaPlayerBase> p = createPlayer(playerType);
703 if (p == NULL) return NO_INIT;
704
705 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700706 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
708 }
709
710 // now set data source
711 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800712 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700713 if (mStatus == NO_ERROR) {
714 mPlayer = p;
715 } else {
716 LOGE(" error: %d", mStatus);
717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 return mStatus;
719 }
720}
721
722status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
723{
724 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
725 struct stat sb;
726 int ret = fstat(fd, &sb);
727 if (ret != 0) {
728 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
729 return UNKNOWN_ERROR;
730 }
731
732 LOGV("st_dev = %llu", sb.st_dev);
733 LOGV("st_mode = %u", sb.st_mode);
734 LOGV("st_uid = %lu", sb.st_uid);
735 LOGV("st_gid = %lu", sb.st_gid);
736 LOGV("st_size = %llu", sb.st_size);
737
738 if (offset >= sb.st_size) {
739 LOGE("offset error");
740 ::close(fd);
741 return UNKNOWN_ERROR;
742 }
743 if (offset + length > sb.st_size) {
744 length = sb.st_size - offset;
745 LOGV("calculated length = %lld", length);
746 }
747
748 player_type playerType = getPlayerType(fd, offset, length);
749 LOGV("player type = %d", playerType);
750
751 // create the right type of player
752 sp<MediaPlayerBase> p = createPlayer(playerType);
753 if (p == NULL) return NO_INIT;
754
755 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700756 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
758 }
759
760 // now set data source
761 mStatus = p->setDataSource(fd, offset, length);
762 if (mStatus == NO_ERROR) mPlayer = p;
Dave Burkefc301b02011-08-30 14:39:17 +0100763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 return mStatus;
765}
766
Andreas Huber52b52cd2010-11-23 11:41:34 -0800767status_t MediaPlayerService::Client::setDataSource(
768 const sp<IStreamSource> &source) {
769 // create the right type of player
Andreas Hubera1587462010-12-15 15:17:42 -0800770 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Huber52b52cd2010-11-23 11:41:34 -0800771
772 if (p == NULL) {
773 return NO_INIT;
774 }
775
776 if (!p->hardwareOutput()) {
777 mAudioOutput = new AudioOutput(mAudioSessionId);
778 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
779 }
780
781 // now set data source
782 mStatus = p->setDataSource(source);
783
784 if (mStatus == OK) {
785 mPlayer = p;
786 }
787
788 return mStatus;
789}
790
Andreas Hubere3c01832010-08-16 08:49:37 -0700791status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792{
793 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
794 sp<MediaPlayerBase> p = getPlayer();
795 if (p == 0) return UNKNOWN_ERROR;
796 return p->setVideoSurface(surface);
797}
798
Jamie Gennis2fa0ac22011-10-26 18:36:31 -0700799void MediaPlayerService::Client::disconnectNativeWindow() {
800 if (mConnectedWindow != NULL) {
801 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
802 NATIVE_WINDOW_API_MEDIA);
803
804 if (err != OK) {
805 LOGW("native_window_api_disconnect returned an error: %s (%d)",
806 strerror(-err), err);
807 }
808 }
809 mConnectedWindow.clear();
810}
811
Glenn Kastencc562a32011-02-08 17:26:17 -0800812status_t MediaPlayerService::Client::setVideoSurfaceTexture(
813 const sp<ISurfaceTexture>& surfaceTexture)
814{
815 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
816 sp<MediaPlayerBase> p = getPlayer();
817 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis2fa0ac22011-10-26 18:36:31 -0700818
819 sp<IBinder> binder(surfaceTexture == NULL ? NULL :
820 surfaceTexture->asBinder());
821 if (mConnectedWindowBinder == binder) {
822 return OK;
823 }
824
825 sp<ANativeWindow> anw;
826 if (surfaceTexture != NULL) {
827 anw = new SurfaceTextureClient(surfaceTexture);
828 status_t err = native_window_api_connect(anw.get(),
829 NATIVE_WINDOW_API_MEDIA);
830
831 if (err != OK) {
832 LOGE("setVideoSurfaceTexture failed: %d", err);
833 // Note that we must do the reset before disconnecting from the ANW.
834 // Otherwise queue/dequeue calls could be made on the disconnected
835 // ANW, which may result in errors.
836 reset();
837
838 disconnectNativeWindow();
839
840 return err;
841 }
842 }
843
844 // Note that we must set the player's new SurfaceTexture before
845 // disconnecting the old one. Otherwise queue/dequeue calls could be made
846 // on the disconnected ANW, which may result in errors.
847 status_t err = p->setVideoSurfaceTexture(surfaceTexture);
848
849 disconnectNativeWindow();
850
851 mConnectedWindow = anw;
852
853 if (err == OK) {
854 mConnectedWindowBinder = binder;
855 } else {
856 disconnectNativeWindow();
857 }
858
859 return err;
Glenn Kastencc562a32011-02-08 17:26:17 -0800860}
861
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700862status_t MediaPlayerService::Client::invoke(const Parcel& request,
863 Parcel *reply)
864{
865 sp<MediaPlayerBase> p = getPlayer();
866 if (p == NULL) return UNKNOWN_ERROR;
867 return p->invoke(request, reply);
868}
869
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700870// This call doesn't need to access the native player.
871status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
872{
873 status_t status;
nikobc726922009-07-20 15:07:26 -0700874 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700875
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700876 if (unmarshallFilter(filter, &allow, &status) &&
877 unmarshallFilter(filter, &drop, &status)) {
878 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700879
880 mMetadataAllow = allow;
881 mMetadataDrop = drop;
882 }
883 return status;
884}
885
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700886status_t MediaPlayerService::Client::getMetadata(
887 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700888{
nikobc726922009-07-20 15:07:26 -0700889 sp<MediaPlayerBase> player = getPlayer();
890 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700891
niko89948372009-07-16 16:39:53 -0700892 status_t status;
893 // Placeholder for the return code, updated by the caller.
894 reply->writeInt32(-1);
895
nikobc726922009-07-20 15:07:26 -0700896 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700897
898 // We don't block notifications while we fetch the data. We clear
899 // mMetadataUpdated first so we don't lose notifications happening
900 // during the rest of this call.
901 {
902 Mutex::Autolock lock(mLock);
903 if (update_only) {
niko89948372009-07-16 16:39:53 -0700904 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700905 }
906 mMetadataUpdated.clear();
907 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700908
nikobc726922009-07-20 15:07:26 -0700909 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700910
nikobc726922009-07-20 15:07:26 -0700911 metadata.appendHeader();
912 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700913
914 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700915 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700916 LOGE("getMetadata failed %d", status);
917 return status;
918 }
919
920 // FIXME: Implement filtering on the result. Not critical since
921 // filtering takes place on the update notifications already. This
922 // would be when all the metadata are fetch and a filter is set.
923
niko89948372009-07-16 16:39:53 -0700924 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700925 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700926 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700927}
928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929status_t MediaPlayerService::Client::prepareAsync()
930{
931 LOGV("[%d] prepareAsync", mConnId);
932 sp<MediaPlayerBase> p = getPlayer();
933 if (p == 0) return UNKNOWN_ERROR;
934 status_t ret = p->prepareAsync();
935#if CALLBACK_ANTAGONIZER
936 LOGD("start Antagonizer");
937 if (ret == NO_ERROR) mAntagonizer->start();
938#endif
939 return ret;
940}
941
942status_t MediaPlayerService::Client::start()
943{
944 LOGV("[%d] start", mConnId);
945 sp<MediaPlayerBase> p = getPlayer();
946 if (p == 0) return UNKNOWN_ERROR;
947 p->setLooping(mLoop);
948 return p->start();
949}
950
951status_t MediaPlayerService::Client::stop()
952{
953 LOGV("[%d] stop", mConnId);
954 sp<MediaPlayerBase> p = getPlayer();
955 if (p == 0) return UNKNOWN_ERROR;
956 return p->stop();
957}
958
959status_t MediaPlayerService::Client::pause()
960{
961 LOGV("[%d] pause", mConnId);
962 sp<MediaPlayerBase> p = getPlayer();
963 if (p == 0) return UNKNOWN_ERROR;
964 return p->pause();
965}
966
967status_t MediaPlayerService::Client::isPlaying(bool* state)
968{
969 *state = false;
970 sp<MediaPlayerBase> p = getPlayer();
971 if (p == 0) return UNKNOWN_ERROR;
972 *state = p->isPlaying();
973 LOGV("[%d] isPlaying: %d", mConnId, *state);
974 return NO_ERROR;
975}
976
977status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
978{
979 LOGV("getCurrentPosition");
980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == 0) return UNKNOWN_ERROR;
982 status_t ret = p->getCurrentPosition(msec);
983 if (ret == NO_ERROR) {
984 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
985 } else {
986 LOGE("getCurrentPosition returned %d", ret);
987 }
988 return ret;
989}
990
991status_t MediaPlayerService::Client::getDuration(int *msec)
992{
993 LOGV("getDuration");
994 sp<MediaPlayerBase> p = getPlayer();
995 if (p == 0) return UNKNOWN_ERROR;
996 status_t ret = p->getDuration(msec);
997 if (ret == NO_ERROR) {
998 LOGV("[%d] getDuration = %d", mConnId, *msec);
999 } else {
1000 LOGE("getDuration returned %d", ret);
1001 }
1002 return ret;
1003}
1004
1005status_t MediaPlayerService::Client::seekTo(int msec)
1006{
1007 LOGV("[%d] seekTo(%d)", mConnId, msec);
1008 sp<MediaPlayerBase> p = getPlayer();
1009 if (p == 0) return UNKNOWN_ERROR;
1010 return p->seekTo(msec);
1011}
1012
1013status_t MediaPlayerService::Client::reset()
1014{
1015 LOGV("[%d] reset", mConnId);
1016 sp<MediaPlayerBase> p = getPlayer();
1017 if (p == 0) return UNKNOWN_ERROR;
1018 return p->reset();
1019}
1020
1021status_t MediaPlayerService::Client::setAudioStreamType(int type)
1022{
1023 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1024 // TODO: for hardware output, call player instead
1025 Mutex::Autolock l(mLock);
1026 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1027 return NO_ERROR;
1028}
1029
1030status_t MediaPlayerService::Client::setLooping(int loop)
1031{
1032 LOGV("[%d] setLooping(%d)", mConnId, loop);
1033 mLoop = loop;
1034 sp<MediaPlayerBase> p = getPlayer();
1035 if (p != 0) return p->setLooping(loop);
1036 return NO_ERROR;
1037}
1038
1039status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1040{
1041 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1042 // TODO: for hardware output, call player instead
1043 Mutex::Autolock l(mLock);
1044 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1045 return NO_ERROR;
1046}
1047
Eric Laurent7070b362010-07-16 07:43:46 -07001048status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1049{
1050 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1051 Mutex::Autolock l(mLock);
1052 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1053 return NO_ERROR;
1054}
1055
1056status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1057{
1058 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1059 Mutex::Autolock l(mLock);
1060 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1061 return NO_ERROR;
1062}
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001063
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001064status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1065 LOGV("[%d] setParameter(%d)", mConnId, key);
1066 sp<MediaPlayerBase> p = getPlayer();
1067 if (p == 0) return UNKNOWN_ERROR;
1068 return p->setParameter(key, request);
1069}
1070
1071status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1072 LOGV("[%d] getParameter(%d)", mConnId, key);
1073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 return p->getParameter(key, reply);
1076}
1077
Gloria Wang162ee492011-04-11 17:23:27 -07001078void MediaPlayerService::Client::notify(
1079 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080{
1081 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001082
1083 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001084 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001085 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001086
1087 if(client->shouldDropMetadata(metadata_type)) {
1088 return;
1089 }
1090
1091 // Update the list of metadata that have changed. getMetadata
1092 // also access mMetadataUpdated and clears it.
1093 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wang162ee492011-04-11 17:23:27 -07001096 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097}
1098
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001099
nikobc726922009-07-20 15:07:26 -07001100bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001101{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001102 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001103
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001104 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001105 return true;
1106 }
1107
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001108 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001109 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001110 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001111 return true;
1112 }
1113}
1114
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001115
nikobc726922009-07-20 15:07:26 -07001116void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001117 Mutex::Autolock lock(mLock);
1118 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1119 mMetadataUpdated.add(metadata_type);
1120 }
1121}
1122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123#if CALLBACK_ANTAGONIZER
1124const int Antagonizer::interval = 10000; // 10 msecs
1125
1126Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1127 mExit(false), mActive(false), mClient(client), mCb(cb)
1128{
1129 createThread(callbackThread, this);
1130}
1131
1132void Antagonizer::kill()
1133{
1134 Mutex::Autolock _l(mLock);
1135 mActive = false;
1136 mExit = true;
1137 mCondition.wait(mLock);
1138}
1139
1140int Antagonizer::callbackThread(void* user)
1141{
1142 LOGD("Antagonizer started");
1143 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1144 while (!p->mExit) {
1145 if (p->mActive) {
1146 LOGV("send event");
1147 p->mCb(p->mClient, 0, 0, 0);
1148 }
1149 usleep(interval);
1150 }
1151 Mutex::Autolock _l(p->mLock);
1152 p->mCondition.signal();
1153 LOGD("Antagonizer stopped");
1154 return 0;
1155}
1156#endif
1157
1158static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1159
1160sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1161{
1162 LOGV("decode(%s)", url);
1163 sp<MemoryBase> mem;
1164 sp<MediaPlayerBase> player;
1165
1166 // Protect our precious, precious DRMd ringtones by only allowing
1167 // decoding of http, but not filesystem paths or content Uris.
1168 // If the application wants to decode those, it should open a
1169 // filedescriptor for them and use that.
1170 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1171 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1172 return mem;
1173 }
1174
1175 player_type playerType = getPlayerType(url);
1176 LOGV("player type = %d", playerType);
1177
1178 // create the right type of player
1179 sp<AudioCache> cache = new AudioCache(url);
1180 player = android::createPlayer(playerType, cache.get(), cache->notify);
1181 if (player == NULL) goto Exit;
1182 if (player->hardwareOutput()) goto Exit;
1183
1184 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1185
1186 // set data source
1187 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1188
1189 LOGV("prepare");
1190 player->prepareAsync();
1191
1192 LOGV("wait for prepare");
1193 if (cache->wait() != NO_ERROR) goto Exit;
1194
1195 LOGV("start");
1196 player->start();
1197
1198 LOGV("wait for playback complete");
Eric Laurent9968a362011-09-27 09:48:56 -07001199 cache->wait();
1200 // in case of error, return what was successfully decoded.
1201 if (cache->size() == 0) {
1202 goto Exit;
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204
1205 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1206 *pSampleRate = cache->sampleRate();
1207 *pNumChannels = cache->channelCount();
Jean-Michel Trivi54392232011-05-24 15:53:33 -07001208 *pFormat = (int)cache->format();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1210
1211Exit:
1212 if (player != 0) player->reset();
1213 return mem;
1214}
1215
1216sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1217{
1218 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1219 sp<MemoryBase> mem;
1220 sp<MediaPlayerBase> player;
1221
1222 player_type playerType = getPlayerType(fd, offset, length);
1223 LOGV("player type = %d", playerType);
1224
1225 // create the right type of player
1226 sp<AudioCache> cache = new AudioCache("decode_fd");
1227 player = android::createPlayer(playerType, cache.get(), cache->notify);
1228 if (player == NULL) goto Exit;
1229 if (player->hardwareOutput()) goto Exit;
1230
1231 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1232
1233 // set data source
1234 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1235
1236 LOGV("prepare");
1237 player->prepareAsync();
1238
1239 LOGV("wait for prepare");
1240 if (cache->wait() != NO_ERROR) goto Exit;
1241
1242 LOGV("start");
1243 player->start();
1244
1245 LOGV("wait for playback complete");
Eric Laurent9968a362011-09-27 09:48:56 -07001246 cache->wait();
1247 // in case of error, return what was successfully decoded.
1248 if (cache->size() == 0) {
1249 goto Exit;
1250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251
1252 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1253 *pSampleRate = cache->sampleRate();
1254 *pNumChannels = cache->channelCount();
1255 *pFormat = cache->format();
1256 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1257
1258Exit:
1259 if (player != 0) player->reset();
1260 ::close(fd);
1261 return mem;
1262}
1263
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265#undef LOG_TAG
1266#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001267MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001268 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001269 mCallbackCookie(NULL),
1270 mSessionId(sessionId) {
1271 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 mTrack = 0;
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001273 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 mLeftVolume = 1.0;
1275 mRightVolume = 1.0;
1276 mLatency = 0;
1277 mMsecsPerFrame = 0;
Eric Laurent7070b362010-07-16 07:43:46 -07001278 mAuxEffectId = 0;
1279 mSendLevel = 0.0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 setMinBufferCount();
1281}
1282
1283MediaPlayerService::AudioOutput::~AudioOutput()
1284{
1285 close();
1286}
1287
1288void MediaPlayerService::AudioOutput::setMinBufferCount()
1289{
1290 char value[PROPERTY_VALUE_MAX];
1291 if (property_get("ro.kernel.qemu", value, 0)) {
1292 mIsOnEmulator = true;
1293 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1294 }
1295}
1296
1297bool MediaPlayerService::AudioOutput::isOnEmulator()
1298{
1299 setMinBufferCount();
1300 return mIsOnEmulator;
1301}
1302
1303int MediaPlayerService::AudioOutput::getMinBufferCount()
1304{
1305 setMinBufferCount();
1306 return mMinBufferCount;
1307}
1308
1309ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1310{
1311 if (mTrack == 0) return NO_INIT;
1312 return mTrack->frameCount() * frameSize();
1313}
1314
1315ssize_t MediaPlayerService::AudioOutput::frameCount() const
1316{
1317 if (mTrack == 0) return NO_INIT;
1318 return mTrack->frameCount();
1319}
1320
1321ssize_t MediaPlayerService::AudioOutput::channelCount() const
1322{
1323 if (mTrack == 0) return NO_INIT;
1324 return mTrack->channelCount();
1325}
1326
1327ssize_t MediaPlayerService::AudioOutput::frameSize() const
1328{
1329 if (mTrack == 0) return NO_INIT;
1330 return mTrack->frameSize();
1331}
1332
1333uint32_t MediaPlayerService::AudioOutput::latency () const
1334{
1335 return mLatency;
1336}
1337
1338float MediaPlayerService::AudioOutput::msecsPerFrame() const
1339{
1340 return mMsecsPerFrame;
1341}
1342
Eric Laurent0986e792010-01-19 17:37:09 -08001343status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1344{
1345 if (mTrack == 0) return NO_INIT;
1346 return mTrack->getPosition(position);
1347}
1348
Andreas Hubere46b7be2009-07-14 16:56:47 -07001349status_t MediaPlayerService::AudioOutput::open(
1350 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1351 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001353 mCallback = cb;
1354 mCallbackCookie = cookie;
1355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 // Check argument "bufferCount" against the mininum buffer count
1357 if (bufferCount < mMinBufferCount) {
1358 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1359 bufferCount = mMinBufferCount;
1360
1361 }
Eric Laurent619346f2010-06-21 09:27:30 -07001362 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 if (mTrack) close();
1364 int afSampleRate;
1365 int afFrameCount;
1366 int frameCount;
1367
1368 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1369 return NO_INIT;
1370 }
1371 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1372 return NO_INIT;
1373 }
1374
1375 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001376
1377 AudioTrack *t;
1378 if (mCallback != NULL) {
1379 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001380 mStreamType,
1381 sampleRate,
1382 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001383 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta553c252009-07-17 12:17:14 -07001384 frameCount,
1385 0 /* flags */,
1386 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001387 this,
1388 0,
1389 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001390 } else {
1391 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001392 mStreamType,
1393 sampleRate,
1394 format,
Dima Zavin24fc2fb2011-04-19 22:30:36 -07001395 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001396 frameCount,
1397 0,
1398 NULL,
1399 NULL,
1400 0,
1401 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001402 }
1403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1405 LOGE("Unable to create audio track");
1406 delete t;
1407 return NO_INIT;
1408 }
1409
1410 LOGV("setVolume");
1411 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001414 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 mTrack = t;
Eric Laurent7070b362010-07-16 07:43:46 -07001416
1417 t->setAuxEffectSendLevel(mSendLevel);
1418 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419}
1420
1421void MediaPlayerService::AudioOutput::start()
1422{
1423 LOGV("start");
1424 if (mTrack) {
1425 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent7070b362010-07-16 07:43:46 -07001426 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 mTrack->start();
1428 }
1429}
1430
Marco Nelissene274db12010-01-12 09:23:54 -08001431
1432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1434{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001435 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001438 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001439 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001440 return ret;
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 return NO_INIT;
1443}
1444
1445void MediaPlayerService::AudioOutput::stop()
1446{
1447 LOGV("stop");
1448 if (mTrack) mTrack->stop();
1449}
1450
1451void MediaPlayerService::AudioOutput::flush()
1452{
1453 LOGV("flush");
1454 if (mTrack) mTrack->flush();
1455}
1456
1457void MediaPlayerService::AudioOutput::pause()
1458{
1459 LOGV("pause");
1460 if (mTrack) mTrack->pause();
1461}
1462
1463void MediaPlayerService::AudioOutput::close()
1464{
1465 LOGV("close");
1466 delete mTrack;
1467 mTrack = 0;
1468}
1469
1470void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1471{
1472 LOGV("setVolume(%f, %f)", left, right);
1473 mLeftVolume = left;
1474 mRightVolume = right;
1475 if (mTrack) {
1476 mTrack->setVolume(left, right);
1477 }
1478}
1479
Eric Laurent7070b362010-07-16 07:43:46 -07001480status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1481{
1482 LOGV("setAuxEffectSendLevel(%f)", level);
1483 mSendLevel = level;
1484 if (mTrack) {
1485 return mTrack->setAuxEffectSendLevel(level);
1486 }
1487 return NO_ERROR;
1488}
1489
1490status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1491{
1492 LOGV("attachAuxEffect(%d)", effectId);
1493 mAuxEffectId = effectId;
1494 if (mTrack) {
1495 return mTrack->attachAuxEffect(effectId);
1496 }
1497 return NO_ERROR;
1498}
1499
Andreas Hubere46b7be2009-07-14 16:56:47 -07001500// static
1501void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastene46a86f2011-06-01 15:20:35 -07001502 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001503 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001504 if (event != AudioTrack::EVENT_MORE_DATA) {
1505 return;
1506 }
1507
1508 AudioOutput *me = (AudioOutput *)cookie;
1509 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1510
Andreas Huber6ed937e2010-02-09 16:59:18 -08001511 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001512 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001513
Andreas Huberc6e3b272011-04-04 11:43:40 -07001514 if (actualSize == 0 && buffer->size > 0) {
1515 // We've reached EOS but the audio track is not stopped yet,
1516 // keep playing silence.
Andreas Huber406a18b2010-02-18 16:45:13 -08001517
Andreas Huberc6e3b272011-04-04 11:43:40 -07001518 memset(buffer->raw, 0, buffer->size);
1519 actualSize = buffer->size;
1520 }
1521
1522 buffer->size = actualSize;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001523}
1524
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001525int MediaPlayerService::AudioOutput::getSessionId()
1526{
1527 return mSessionId;
1528}
1529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530#undef LOG_TAG
1531#define LOG_TAG "AudioCache"
1532MediaPlayerService::AudioCache::AudioCache(const char* name) :
1533 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1534 mError(NO_ERROR), mCommandComplete(false)
1535{
1536 // create ashmem heap
1537 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1538}
1539
1540uint32_t MediaPlayerService::AudioCache::latency () const
1541{
1542 return 0;
1543}
1544
1545float MediaPlayerService::AudioCache::msecsPerFrame() const
1546{
1547 return mMsecsPerFrame;
1548}
1549
Eric Laurent0986e792010-01-19 17:37:09 -08001550status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1551{
1552 if (position == 0) return BAD_VALUE;
1553 *position = mSize;
1554 return NO_ERROR;
1555}
1556
Andreas Huber6ed937e2010-02-09 16:59:18 -08001557////////////////////////////////////////////////////////////////////////////////
1558
1559struct CallbackThread : public Thread {
1560 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1561 MediaPlayerBase::AudioSink::AudioCallback cb,
1562 void *cookie);
1563
1564protected:
1565 virtual ~CallbackThread();
1566
1567 virtual bool threadLoop();
1568
1569private:
1570 wp<MediaPlayerBase::AudioSink> mSink;
1571 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1572 void *mCookie;
1573 void *mBuffer;
1574 size_t mBufferSize;
1575
1576 CallbackThread(const CallbackThread &);
1577 CallbackThread &operator=(const CallbackThread &);
1578};
1579
1580CallbackThread::CallbackThread(
1581 const wp<MediaPlayerBase::AudioSink> &sink,
1582 MediaPlayerBase::AudioSink::AudioCallback cb,
1583 void *cookie)
1584 : mSink(sink),
1585 mCallback(cb),
1586 mCookie(cookie),
1587 mBuffer(NULL),
1588 mBufferSize(0) {
1589}
1590
1591CallbackThread::~CallbackThread() {
1592 if (mBuffer) {
1593 free(mBuffer);
1594 mBuffer = NULL;
1595 }
1596}
1597
1598bool CallbackThread::threadLoop() {
1599 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1600 if (sink == NULL) {
1601 return false;
1602 }
1603
1604 if (mBuffer == NULL) {
1605 mBufferSize = sink->bufferSize();
1606 mBuffer = malloc(mBufferSize);
1607 }
1608
1609 size_t actualSize =
1610 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1611
1612 if (actualSize > 0) {
1613 sink->write(mBuffer, actualSize);
1614 }
1615
1616 return true;
1617}
1618
1619////////////////////////////////////////////////////////////////////////////////
1620
Andreas Hubere46b7be2009-07-14 16:56:47 -07001621status_t MediaPlayerService::AudioCache::open(
1622 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1623 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624{
Dave Sparks14f89402009-12-09 20:20:26 -08001625 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001626 if (mHeap->getHeapID() < 0) {
1627 return NO_INIT;
1628 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 mSampleRate = sampleRate;
1631 mChannelCount = (uint16_t)channelCount;
1632 mFormat = (uint16_t)format;
1633 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001634
1635 if (cb != NULL) {
1636 mCallbackThread = new CallbackThread(this, cb, cookie);
1637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 return NO_ERROR;
1639}
1640
Andreas Huber6ed937e2010-02-09 16:59:18 -08001641void MediaPlayerService::AudioCache::start() {
1642 if (mCallbackThread != NULL) {
1643 mCallbackThread->run("AudioCache callback");
1644 }
1645}
1646
1647void MediaPlayerService::AudioCache::stop() {
1648 if (mCallbackThread != NULL) {
1649 mCallbackThread->requestExitAndWait();
1650 }
1651}
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1654{
1655 LOGV("write(%p, %u)", buffer, size);
1656 if ((buffer == 0) || (size == 0)) return size;
1657
1658 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1659 if (p == NULL) return NO_INIT;
1660 p += mSize;
1661 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1662 if (mSize + size > mHeap->getSize()) {
1663 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1664 size = mHeap->getSize() - mSize;
1665 }
1666 memcpy(p, buffer, size);
1667 mSize += size;
1668 return size;
1669}
1670
1671// call with lock held
1672status_t MediaPlayerService::AudioCache::wait()
1673{
1674 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001675 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 mSignal.wait(mLock);
1677 }
1678 mCommandComplete = false;
1679
1680 if (mError == NO_ERROR) {
1681 LOGV("wait - success");
1682 } else {
1683 LOGV("wait - error");
1684 }
1685 return mError;
1686}
1687
Gloria Wang162ee492011-04-11 17:23:27 -07001688void MediaPlayerService::AudioCache::notify(
1689 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690{
1691 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1692 AudioCache* p = static_cast<AudioCache*>(cookie);
1693
1694 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001695 switch (msg)
1696 {
1697 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 LOGE("Error %d, %d occurred", ext1, ext2);
1699 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001700 break;
1701 case MEDIA_PREPARED:
1702 LOGV("prepared");
1703 break;
1704 case MEDIA_PLAYBACK_COMPLETE:
1705 LOGV("playback complete");
1706 break;
1707 default:
1708 LOGV("ignored");
1709 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
1712 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001713 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 p->mCommandComplete = true;
1715 p->mSignal.signal();
1716}
1717
Eric Laurentb3bdf3f2010-10-07 18:23:03 -07001718int MediaPlayerService::AudioCache::getSessionId()
1719{
1720 return 0;
1721}
1722
Gloria Wangd211f412011-02-19 18:37:57 -08001723void MediaPlayerService::addBatteryData(uint32_t params)
1724{
1725 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001726
1727 int32_t time = systemTime() / 1000000L;
1728
1729 // change audio output devices. This notification comes from AudioFlinger
1730 if ((params & kBatteryDataSpeakerOn)
1731 || (params & kBatteryDataOtherAudioDeviceOn)) {
1732
1733 int deviceOn[NUM_AUDIO_DEVICES];
1734 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1735 deviceOn[i] = 0;
1736 }
1737
1738 if ((params & kBatteryDataSpeakerOn)
1739 && (params & kBatteryDataOtherAudioDeviceOn)) {
1740 deviceOn[SPEAKER_AND_OTHER] = 1;
1741 } else if (params & kBatteryDataSpeakerOn) {
1742 deviceOn[SPEAKER] = 1;
1743 } else {
1744 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1745 }
1746
1747 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1748 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1749
1750 if (mBatteryAudio.refCount > 0) { // if playing audio
1751 if (!deviceOn[i]) {
1752 mBatteryAudio.lastTime[i] += time;
1753 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1754 mBatteryAudio.lastTime[i] = 0;
1755 } else {
1756 mBatteryAudio.lastTime[i] = 0 - time;
1757 }
1758 }
1759
1760 mBatteryAudio.deviceOn[i] = deviceOn[i];
1761 }
1762 }
1763 return;
1764 }
1765
1766 // an sudio stream is started
1767 if (params & kBatteryDataAudioFlingerStart) {
1768 // record the start time only if currently no other audio
1769 // is being played
1770 if (mBatteryAudio.refCount == 0) {
1771 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1772 if (mBatteryAudio.deviceOn[i]) {
1773 mBatteryAudio.lastTime[i] -= time;
1774 }
1775 }
1776 }
1777
1778 mBatteryAudio.refCount ++;
1779 return;
1780
1781 } else if (params & kBatteryDataAudioFlingerStop) {
1782 if (mBatteryAudio.refCount <= 0) {
1783 LOGW("Battery track warning: refCount is <= 0");
1784 return;
1785 }
1786
1787 // record the stop time only if currently this is the only
1788 // audio being played
1789 if (mBatteryAudio.refCount == 1) {
1790 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1791 if (mBatteryAudio.deviceOn[i]) {
1792 mBatteryAudio.lastTime[i] += time;
1793 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1794 mBatteryAudio.lastTime[i] = 0;
1795 }
1796 }
1797 }
1798
1799 mBatteryAudio.refCount --;
1800 return;
1801 }
1802
Gloria Wangd211f412011-02-19 18:37:57 -08001803 int uid = IPCThreadState::self()->getCallingUid();
1804 if (uid == AID_MEDIA) {
1805 return;
1806 }
1807 int index = mBatteryData.indexOfKey(uid);
Gloria Wangd211f412011-02-19 18:37:57 -08001808
1809 if (index < 0) { // create a new entry for this UID
1810 BatteryUsageInfo info;
1811 info.audioTotalTime = 0;
1812 info.videoTotalTime = 0;
1813 info.audioLastTime = 0;
1814 info.videoLastTime = 0;
1815 info.refCount = 0;
1816
Gloria Wang9b3f1522011-02-24 14:51:45 -08001817 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1818 LOGE("Battery track error: no memory for new app");
1819 return;
1820 }
Gloria Wangd211f412011-02-19 18:37:57 -08001821 }
1822
1823 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1824
1825 if (params & kBatteryDataCodecStarted) {
1826 if (params & kBatteryDataTrackAudio) {
1827 info.audioLastTime -= time;
1828 info.refCount ++;
1829 }
1830 if (params & kBatteryDataTrackVideo) {
1831 info.videoLastTime -= time;
1832 info.refCount ++;
1833 }
1834 } else {
1835 if (info.refCount == 0) {
1836 LOGW("Battery track warning: refCount is already 0");
1837 return;
1838 } else if (info.refCount < 0) {
1839 LOGE("Battery track error: refCount < 0");
1840 mBatteryData.removeItem(uid);
1841 return;
1842 }
1843
1844 if (params & kBatteryDataTrackAudio) {
1845 info.audioLastTime += time;
1846 info.refCount --;
1847 }
1848 if (params & kBatteryDataTrackVideo) {
1849 info.videoLastTime += time;
1850 info.refCount --;
1851 }
1852
1853 // no stream is being played by this UID
1854 if (info.refCount == 0) {
1855 info.audioTotalTime += info.audioLastTime;
1856 info.audioLastTime = 0;
1857 info.videoTotalTime += info.videoLastTime;
1858 info.videoLastTime = 0;
1859 }
1860 }
1861}
1862
1863status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1864 Mutex::Autolock lock(mLock);
Gloria Wang9b3f1522011-02-24 14:51:45 -08001865
1866 // audio output devices usage
1867 int32_t time = systemTime() / 1000000L; //in ms
1868 int32_t totalTime;
1869
1870 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1871 totalTime = mBatteryAudio.totalTime[i];
1872
1873 if (mBatteryAudio.deviceOn[i]
1874 && (mBatteryAudio.lastTime[i] != 0)) {
1875 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1876 totalTime += tmpTime;
1877 }
1878
1879 reply->writeInt32(totalTime);
1880 // reset the total time
1881 mBatteryAudio.totalTime[i] = 0;
1882 }
1883
1884 // codec usage
Gloria Wangd211f412011-02-19 18:37:57 -08001885 BatteryUsageInfo info;
1886 int size = mBatteryData.size();
1887
1888 reply->writeInt32(size);
1889 int i = 0;
1890
1891 while (i < size) {
1892 info = mBatteryData.valueAt(i);
1893
1894 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1895 reply->writeInt32(info.audioTotalTime);
1896 reply->writeInt32(info.videoTotalTime);
1897
1898 info.audioTotalTime = 0;
1899 info.videoTotalTime = 0;
1900
1901 // remove the UID entry where no stream is being played
1902 if (info.refCount <= 0) {
1903 mBatteryData.removeItemsAt(i);
1904 size --;
1905 i --;
1906 }
1907 i++;
1908 }
1909 return NO_ERROR;
1910}
nikobc726922009-07-20 15:07:26 -07001911} // namespace android