blob: ba9f54f5f045696da2bd3cdd47dc72646e686fb0 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
37#include <android_runtime/ActivityManager.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070038
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Jamie Gennis7dae00b2011-10-26 18:36:31 -070043#include <gui/SurfaceTextureClient.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070044#include <utils/Errors.h> // for status_t
45#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070046#include <utils/SystemClock.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070047#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-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>
nikoa64c8c72009-07-20 15:07:26 -070053#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080054#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070055#include <media/MemoryLeakTrackUtil.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070056#include <media/stagefright/MediaErrors.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080057
Dima Zavin64760242011-05-11 14:15:23 -070058#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070059
Gloria Wang7cf180c2011-02-19 18:37:57 -080060#include <private/android_filesystem_config.h>
61
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080062#include "MediaRecorderClient.h"
63#include "MediaPlayerService.h"
64#include "MetadataRetrieverClient.h"
65
66#include "MidiFile.h"
Nicolas Catania14d27472009-07-13 14:37:49 -070067#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070068#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080069#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070070
Andreas Huber20111aa2009-07-14 16:56:47 -070071#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070072
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070073namespace {
nikoa64c8c72009-07-20 15:07:26 -070074using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-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 Cataniaa7e0e8b2009-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
nikoa64c8c72009-07-20 15:07:26 -070084// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070085
Nicolas Cataniaa7e0e8b2009-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,
nikoa64c8c72009-07-20 15:07:26 -0700109 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700110 status_t *status)
111{
Nicolas Catania48290382009-07-10 13:53:06 -0700112 int32_t val;
113 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-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 Catania48290382009-07-10 13:53:06 -0700120 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700121 {
Nicolas Catania48290382009-07-10 13:53:06 -0700122 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700123 *status = BAD_VALUE;
124 return false;
125 }
126
Nicolas Catania48290382009-07-10 13:53:06 -0700127 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128
129 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700130 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131
nikoa64c8c72009-07-20 15:07:26 -0700132 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133
Nicolas Catania48290382009-07-10 13:53:06 -0700134
135 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Nicolas Catania48290382009-07-10 13:53:06 -0700137 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = NOT_ENOUGH_DATA;
139 return false;
140 }
141
nikoa64c8c72009-07-20 15:07:26 -0700142 const Metadata::Type *data =
143 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144
Nicolas Catania48290382009-07-10 13:53:06 -0700145 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-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 Catania48290382009-07-10 13:53:06 -0700155 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700156 {
Nicolas Catania48290382009-07-10 13:53:06 -0700157 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158 ++data;
159 }
160 *status = OK;
161 return true;
162}
163
Nicolas Catania48290382009-07-10 13:53:06 -0700164// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165// @param val To be searched.
166// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700167bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700168{
169 // Deal with empty and ANY right away
170 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700171 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172
Nicolas Catania48290382009-07-10 13:53:06 -0700173 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174}
175
176} // anonymous namespace
177
178
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800179namespace android {
180
Dave Burked681bbb2011-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 Project89fa4ad2009-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 Project89fa4ad2009-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 Project89fa4ad2009-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 Wang9ee159b2011-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 Project89fa4ad2009-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 Wangdac6a312009-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 Project89fa4ad2009-03-03 19:31:44 -0800242 LOGV("Create new media recorder client from pid %d", pid);
243 return recorder;
244}
245
Gloria Wangdac6a312009-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 Project89fa4ad2009-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 Project89fa4ad2009-03-03 19:31:44 -0800260sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100261 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262{
263 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700264
265 sp<Client> c = new Client(
266 this, pid, connId, client, audioSessionId,
267 IPCThreadState::self()->getCallingUid());
268
Dave Burked681bbb2011-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 Project89fa4ad2009-03-03 19:31:44 -0800274 Mutex::Autolock lock(mLock);
275 mClients.add(w);
276 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800277 return c;
278}
279
Andreas Huber318ad9c2009-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 Huber20111aa2009-07-14 16:56:47 -0700288}
289
The Android Open Source Project89fa4ad2009-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 Laurent2beeb502010-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 Project89fa4ad2009-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 Hubera0b1d4b2011-06-07 15:52:25 -0700346 if (mPlayer != NULL) {
347 mPlayer->dump(fd, args);
348 }
The Android Open Source Project89fa4ad2009-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 Project89fa4ad2009-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 Dongb9141222010-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 Donge579e282011-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 Dongb9141222010-07-08 11:16:11 -0700385 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700386 }
387
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800388 result.append(" Files opened and/or mapped:\n");
Glenn Kasten0512ab52011-05-04 17:58:57 -0700389 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800390 FILE *f = fopen(buffer, "r");
391 if (f) {
392 while (!feof(f)) {
393 fgets(buffer, SIZE, f);
Dave Sparks02fa8342010-09-27 16:55:18 -0700394 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800395 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700396 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-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 Kasten0512ab52011-05-04 17:58:57 -0700409 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project89fa4ad2009-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 Kasten0512ab52011-05-04 17:58:57 -0700415 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project89fa4ad2009-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 Sparks02fa8342010-09-27 16:55:18 -0700430 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700432 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-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 Project89fa4ad2009-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 Dong8635b7b2011-03-14 17:01:38 -0700463 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 }
The Android Open Source Project89fa4ad2009-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 Huber9b80c2b2011-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 Project89fa4ad2009-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 Laurenta514bdb2010-06-21 09:27:30 -0700488 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700489 mUID = uid;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700490
The Android Open Source Project89fa4ad2009-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 Sparks795fa582009-03-24 17:57:12 -0700516 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700517
The Android Open Source Project89fa4ad2009-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 Gennis7dae00b2011-10-26 18:36:31 -0700532 disconnectNativeWindow();
533
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534 IPCThreadState::self()->flushCommands();
535}
536
Andreas Huber47f59cf2009-08-07 09:30:32 -0700537static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700538 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700539}
540
James Dong148c1a22009-09-06 14:29:45 -0700541player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-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 Huber608d77b2010-06-23 16:40:57 -0700552 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-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 Huber47f59cf2009-08-07 09:30:32 -0700571 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800572}
573
James Dong148c1a22009-09-06 14:29:45 -0700574player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575{
Nicolas Catania14d27472009-07-13 14:37:49 -0700576 if (TestPlayerStub::canBeUsed(url)) {
577 return TEST_PLAYER;
578 }
579
Andreas Huber0a73d812011-03-21 16:28:04 -0700580 if (!strncasecmp("http://", url, 7)
581 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-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 Huber5bc087c2010-12-23 10:27:40 -0800586
Andreas Hubered8d14f2011-02-16 09:05:38 -0800587 if (strstr(url,"m3u8")) {
588 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800589 }
590 }
591
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592 // use MidiFile for MIDI extensions
593 int lenURL = strlen(url);
594 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
595 int len = strlen(FILE_EXTS[i].extension);
596 int start = lenURL - len;
597 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900598 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700599 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 }
601 }
602 }
603
Andreas Huber47f59cf2009-08-07 09:30:32 -0700604 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605}
606
607static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
608 notify_callback_f notifyFunc)
609{
610 sp<MediaPlayerBase> p;
611 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800612 case SONIVOX_PLAYER:
613 LOGV(" create MidiFile");
614 p = new MidiFile();
615 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700616 case STAGEFRIGHT_PLAYER:
617 LOGV(" create StagefrightPlayer");
618 p = new StagefrightPlayer;
619 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800620 case NU_PLAYER:
621 LOGV(" create NuPlayer");
622 p = new NuPlayerDriver;
623 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700624 case TEST_PLAYER:
625 LOGV("Create Test Player stub");
626 p = new TestPlayerStub();
627 break;
James Dong30d713a2010-11-10 18:42:40 -0800628 default:
629 LOGE("Unknown player type: %d", playerType);
630 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 }
632 if (p != NULL) {
633 if (p->initCheck() == NO_ERROR) {
634 p->setNotifyCallback(cookie, notifyFunc);
635 } else {
636 p.clear();
637 }
638 }
639 if (p == NULL) {
640 LOGE("Failed to create player object");
641 }
642 return p;
643}
644
645sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
646{
647 // determine if we have the right player type
648 sp<MediaPlayerBase> p = mPlayer;
649 if ((p != NULL) && (p->playerType() != playerType)) {
650 LOGV("delete player");
651 p.clear();
652 }
653 if (p == NULL) {
654 p = android::createPlayer(playerType, this, notify);
655 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700656
Jason Simmonsdb29e522011-08-12 13:46:55 -0700657 if (p != NULL) {
658 p->setUID(mUID);
659 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700660
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661 return p;
662}
663
Andreas Huber2db84552010-01-28 11:19:57 -0800664status_t MediaPlayerService::Client::setDataSource(
665 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800666{
667 LOGV("setDataSource(%s)", url);
668 if (url == NULL)
669 return UNKNOWN_ERROR;
670
Dave Burked681bbb2011-08-30 14:39:17 +0100671 if ((strncmp(url, "http://", 7) == 0) ||
672 (strncmp(url, "https://", 8) == 0) ||
673 (strncmp(url, "rtsp://", 7) == 0)) {
674 if (!checkPermission("android.permission.INTERNET")) {
675 return PERMISSION_DENIED;
676 }
677 }
678
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800679 if (strncmp(url, "content://", 10) == 0) {
680 // get a filedescriptor for the content Uri and
681 // pass it to the setDataSource(fd) method
682
683 String16 url16(url);
684 int fd = android::openContentProviderFile(url16);
685 if (fd < 0)
686 {
687 LOGE("Couldn't open fd for %s", url);
688 return UNKNOWN_ERROR;
689 }
690 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
691 close(fd);
692 return mStatus;
693 } else {
694 player_type playerType = getPlayerType(url);
695 LOGV("player type = %d", playerType);
696
697 // create the right type of player
698 sp<MediaPlayerBase> p = createPlayer(playerType);
699 if (p == NULL) return NO_INIT;
700
701 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700702 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
704 }
705
706 // now set data source
707 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800708 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700709 if (mStatus == NO_ERROR) {
710 mPlayer = p;
711 } else {
712 LOGE(" error: %d", mStatus);
713 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714 return mStatus;
715 }
716}
717
718status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
719{
720 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
721 struct stat sb;
722 int ret = fstat(fd, &sb);
723 if (ret != 0) {
724 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
725 return UNKNOWN_ERROR;
726 }
727
728 LOGV("st_dev = %llu", sb.st_dev);
729 LOGV("st_mode = %u", sb.st_mode);
730 LOGV("st_uid = %lu", sb.st_uid);
731 LOGV("st_gid = %lu", sb.st_gid);
732 LOGV("st_size = %llu", sb.st_size);
733
734 if (offset >= sb.st_size) {
735 LOGE("offset error");
736 ::close(fd);
737 return UNKNOWN_ERROR;
738 }
739 if (offset + length > sb.st_size) {
740 length = sb.st_size - offset;
741 LOGV("calculated length = %lld", length);
742 }
743
744 player_type playerType = getPlayerType(fd, offset, length);
745 LOGV("player type = %d", playerType);
746
747 // create the right type of player
748 sp<MediaPlayerBase> p = createPlayer(playerType);
749 if (p == NULL) return NO_INIT;
750
751 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700752 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
754 }
755
756 // now set data source
757 mStatus = p->setDataSource(fd, offset, length);
758 if (mStatus == NO_ERROR) mPlayer = p;
Dave Burked681bbb2011-08-30 14:39:17 +0100759
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 return mStatus;
761}
762
Andreas Hubere2b10282010-11-23 11:41:34 -0800763status_t MediaPlayerService::Client::setDataSource(
764 const sp<IStreamSource> &source) {
765 // create the right type of player
Andreas Huberf9334412010-12-15 15:17:42 -0800766 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Hubere2b10282010-11-23 11:41:34 -0800767
768 if (p == NULL) {
769 return NO_INIT;
770 }
771
772 if (!p->hardwareOutput()) {
773 mAudioOutput = new AudioOutput(mAudioSessionId);
774 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
775 }
776
777 // now set data source
778 mStatus = p->setDataSource(source);
779
780 if (mStatus == OK) {
781 mPlayer = p;
782 }
783
784 return mStatus;
785}
786
Andreas Huber5daeb122010-08-16 08:49:37 -0700787status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800788{
789 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
790 sp<MediaPlayerBase> p = getPlayer();
791 if (p == 0) return UNKNOWN_ERROR;
792 return p->setVideoSurface(surface);
793}
794
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700795void MediaPlayerService::Client::disconnectNativeWindow() {
796 if (mConnectedWindow != NULL) {
797 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
798 NATIVE_WINDOW_API_MEDIA);
799
800 if (err != OK) {
801 LOGW("native_window_api_disconnect returned an error: %s (%d)",
802 strerror(-err), err);
803 }
804 }
805 mConnectedWindow.clear();
806}
807
Glenn Kasten11731182011-02-08 17:26:17 -0800808status_t MediaPlayerService::Client::setVideoSurfaceTexture(
809 const sp<ISurfaceTexture>& surfaceTexture)
810{
811 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
812 sp<MediaPlayerBase> p = getPlayer();
813 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700814
815 sp<IBinder> binder(surfaceTexture == NULL ? NULL :
816 surfaceTexture->asBinder());
817 if (mConnectedWindowBinder == binder) {
818 return OK;
819 }
820
821 sp<ANativeWindow> anw;
822 if (surfaceTexture != NULL) {
823 anw = new SurfaceTextureClient(surfaceTexture);
824 status_t err = native_window_api_connect(anw.get(),
825 NATIVE_WINDOW_API_MEDIA);
826
827 if (err != OK) {
828 LOGE("setVideoSurfaceTexture failed: %d", err);
829 // Note that we must do the reset before disconnecting from the ANW.
830 // Otherwise queue/dequeue calls could be made on the disconnected
831 // ANW, which may result in errors.
832 reset();
833
834 disconnectNativeWindow();
835
836 return err;
837 }
838 }
839
840 // Note that we must set the player's new SurfaceTexture before
841 // disconnecting the old one. Otherwise queue/dequeue calls could be made
842 // on the disconnected ANW, which may result in errors.
843 status_t err = p->setVideoSurfaceTexture(surfaceTexture);
844
845 disconnectNativeWindow();
846
847 mConnectedWindow = anw;
848
849 if (err == OK) {
850 mConnectedWindowBinder = binder;
851 } else {
852 disconnectNativeWindow();
853 }
854
855 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800856}
857
Nicolas Catania1d187f12009-05-12 23:25:55 -0700858status_t MediaPlayerService::Client::invoke(const Parcel& request,
859 Parcel *reply)
860{
861 sp<MediaPlayerBase> p = getPlayer();
862 if (p == NULL) return UNKNOWN_ERROR;
863 return p->invoke(request, reply);
864}
865
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700866// This call doesn't need to access the native player.
867status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
868{
869 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700870 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700871
Nicolas Catania48290382009-07-10 13:53:06 -0700872 if (unmarshallFilter(filter, &allow, &status) &&
873 unmarshallFilter(filter, &drop, &status)) {
874 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700875
876 mMetadataAllow = allow;
877 mMetadataDrop = drop;
878 }
879 return status;
880}
881
Nicolas Catania48290382009-07-10 13:53:06 -0700882status_t MediaPlayerService::Client::getMetadata(
883 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700884{
nikoa64c8c72009-07-20 15:07:26 -0700885 sp<MediaPlayerBase> player = getPlayer();
886 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700887
nikod608a812009-07-16 16:39:53 -0700888 status_t status;
889 // Placeholder for the return code, updated by the caller.
890 reply->writeInt32(-1);
891
nikoa64c8c72009-07-20 15:07:26 -0700892 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700893
894 // We don't block notifications while we fetch the data. We clear
895 // mMetadataUpdated first so we don't lose notifications happening
896 // during the rest of this call.
897 {
898 Mutex::Autolock lock(mLock);
899 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700900 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700901 }
902 mMetadataUpdated.clear();
903 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700904
nikoa64c8c72009-07-20 15:07:26 -0700905 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700906
nikoa64c8c72009-07-20 15:07:26 -0700907 metadata.appendHeader();
908 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700909
910 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700911 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700912 LOGE("getMetadata failed %d", status);
913 return status;
914 }
915
916 // FIXME: Implement filtering on the result. Not critical since
917 // filtering takes place on the update notifications already. This
918 // would be when all the metadata are fetch and a filter is set.
919
nikod608a812009-07-16 16:39:53 -0700920 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700921 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700922 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700923}
924
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800925status_t MediaPlayerService::Client::prepareAsync()
926{
927 LOGV("[%d] prepareAsync", mConnId);
928 sp<MediaPlayerBase> p = getPlayer();
929 if (p == 0) return UNKNOWN_ERROR;
930 status_t ret = p->prepareAsync();
931#if CALLBACK_ANTAGONIZER
932 LOGD("start Antagonizer");
933 if (ret == NO_ERROR) mAntagonizer->start();
934#endif
935 return ret;
936}
937
938status_t MediaPlayerService::Client::start()
939{
940 LOGV("[%d] start", mConnId);
941 sp<MediaPlayerBase> p = getPlayer();
942 if (p == 0) return UNKNOWN_ERROR;
943 p->setLooping(mLoop);
944 return p->start();
945}
946
947status_t MediaPlayerService::Client::stop()
948{
949 LOGV("[%d] stop", mConnId);
950 sp<MediaPlayerBase> p = getPlayer();
951 if (p == 0) return UNKNOWN_ERROR;
952 return p->stop();
953}
954
955status_t MediaPlayerService::Client::pause()
956{
957 LOGV("[%d] pause", mConnId);
958 sp<MediaPlayerBase> p = getPlayer();
959 if (p == 0) return UNKNOWN_ERROR;
960 return p->pause();
961}
962
963status_t MediaPlayerService::Client::isPlaying(bool* state)
964{
965 *state = false;
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 *state = p->isPlaying();
969 LOGV("[%d] isPlaying: %d", mConnId, *state);
970 return NO_ERROR;
971}
972
973status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
974{
975 LOGV("getCurrentPosition");
976 sp<MediaPlayerBase> p = getPlayer();
977 if (p == 0) return UNKNOWN_ERROR;
978 status_t ret = p->getCurrentPosition(msec);
979 if (ret == NO_ERROR) {
980 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
981 } else {
982 LOGE("getCurrentPosition returned %d", ret);
983 }
984 return ret;
985}
986
987status_t MediaPlayerService::Client::getDuration(int *msec)
988{
989 LOGV("getDuration");
990 sp<MediaPlayerBase> p = getPlayer();
991 if (p == 0) return UNKNOWN_ERROR;
992 status_t ret = p->getDuration(msec);
993 if (ret == NO_ERROR) {
994 LOGV("[%d] getDuration = %d", mConnId, *msec);
995 } else {
996 LOGE("getDuration returned %d", ret);
997 }
998 return ret;
999}
1000
1001status_t MediaPlayerService::Client::seekTo(int msec)
1002{
1003 LOGV("[%d] seekTo(%d)", mConnId, msec);
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 return p->seekTo(msec);
1007}
1008
1009status_t MediaPlayerService::Client::reset()
1010{
1011 LOGV("[%d] reset", mConnId);
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 return p->reset();
1015}
1016
1017status_t MediaPlayerService::Client::setAudioStreamType(int type)
1018{
1019 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1020 // TODO: for hardware output, call player instead
1021 Mutex::Autolock l(mLock);
1022 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1023 return NO_ERROR;
1024}
1025
1026status_t MediaPlayerService::Client::setLooping(int loop)
1027{
1028 LOGV("[%d] setLooping(%d)", mConnId, loop);
1029 mLoop = loop;
1030 sp<MediaPlayerBase> p = getPlayer();
1031 if (p != 0) return p->setLooping(loop);
1032 return NO_ERROR;
1033}
1034
1035status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1036{
1037 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1038 // TODO: for hardware output, call player instead
1039 Mutex::Autolock l(mLock);
1040 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1041 return NO_ERROR;
1042}
1043
Eric Laurent2beeb502010-07-16 07:43:46 -07001044status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1045{
1046 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1047 Mutex::Autolock l(mLock);
1048 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1049 return NO_ERROR;
1050}
1051
1052status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1053{
1054 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1055 Mutex::Autolock l(mLock);
1056 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1057 return NO_ERROR;
1058}
Nicolas Catania48290382009-07-10 13:53:06 -07001059
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001060status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1061 LOGV("[%d] setParameter(%d)", mConnId, key);
1062 sp<MediaPlayerBase> p = getPlayer();
1063 if (p == 0) return UNKNOWN_ERROR;
1064 return p->setParameter(key, request);
1065}
1066
1067status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1068 LOGV("[%d] getParameter(%d)", mConnId, key);
1069 sp<MediaPlayerBase> p = getPlayer();
1070 if (p == 0) return UNKNOWN_ERROR;
1071 return p->getParameter(key, reply);
1072}
1073
Gloria Wangb483c472011-04-11 17:23:27 -07001074void MediaPlayerService::Client::notify(
1075 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076{
1077 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001078
1079 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001080 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001081 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001082
1083 if(client->shouldDropMetadata(metadata_type)) {
1084 return;
1085 }
1086
1087 // Update the list of metadata that have changed. getMetadata
1088 // also access mMetadataUpdated and clears it.
1089 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001090 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001092 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001093}
1094
Nicolas Catania48290382009-07-10 13:53:06 -07001095
nikoa64c8c72009-07-20 15:07:26 -07001096bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001097{
Nicolas Catania48290382009-07-10 13:53:06 -07001098 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001099
Nicolas Catania48290382009-07-10 13:53:06 -07001100 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001101 return true;
1102 }
1103
Nicolas Catania48290382009-07-10 13:53:06 -07001104 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001105 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001106 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001107 return true;
1108 }
1109}
1110
Nicolas Catania48290382009-07-10 13:53:06 -07001111
nikoa64c8c72009-07-20 15:07:26 -07001112void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001113 Mutex::Autolock lock(mLock);
1114 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1115 mMetadataUpdated.add(metadata_type);
1116 }
1117}
1118
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119#if CALLBACK_ANTAGONIZER
1120const int Antagonizer::interval = 10000; // 10 msecs
1121
1122Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1123 mExit(false), mActive(false), mClient(client), mCb(cb)
1124{
1125 createThread(callbackThread, this);
1126}
1127
1128void Antagonizer::kill()
1129{
1130 Mutex::Autolock _l(mLock);
1131 mActive = false;
1132 mExit = true;
1133 mCondition.wait(mLock);
1134}
1135
1136int Antagonizer::callbackThread(void* user)
1137{
1138 LOGD("Antagonizer started");
1139 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1140 while (!p->mExit) {
1141 if (p->mActive) {
1142 LOGV("send event");
1143 p->mCb(p->mClient, 0, 0, 0);
1144 }
1145 usleep(interval);
1146 }
1147 Mutex::Autolock _l(p->mLock);
1148 p->mCondition.signal();
1149 LOGD("Antagonizer stopped");
1150 return 0;
1151}
1152#endif
1153
1154static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1155
1156sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1157{
1158 LOGV("decode(%s)", url);
1159 sp<MemoryBase> mem;
1160 sp<MediaPlayerBase> player;
1161
1162 // Protect our precious, precious DRMd ringtones by only allowing
1163 // decoding of http, but not filesystem paths or content Uris.
1164 // If the application wants to decode those, it should open a
1165 // filedescriptor for them and use that.
1166 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1167 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1168 return mem;
1169 }
1170
1171 player_type playerType = getPlayerType(url);
1172 LOGV("player type = %d", playerType);
1173
1174 // create the right type of player
1175 sp<AudioCache> cache = new AudioCache(url);
1176 player = android::createPlayer(playerType, cache.get(), cache->notify);
1177 if (player == NULL) goto Exit;
1178 if (player->hardwareOutput()) goto Exit;
1179
1180 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1181
1182 // set data source
1183 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1184
1185 LOGV("prepare");
1186 player->prepareAsync();
1187
1188 LOGV("wait for prepare");
1189 if (cache->wait() != NO_ERROR) goto Exit;
1190
1191 LOGV("start");
1192 player->start();
1193
1194 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001195 cache->wait();
1196 // in case of error, return what was successfully decoded.
1197 if (cache->size() == 0) {
1198 goto Exit;
1199 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001200
1201 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1202 *pSampleRate = cache->sampleRate();
1203 *pNumChannels = cache->channelCount();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001204 *pFormat = (int)cache->format();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001205 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1206
1207Exit:
1208 if (player != 0) player->reset();
1209 return mem;
1210}
1211
1212sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1213{
1214 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1215 sp<MemoryBase> mem;
1216 sp<MediaPlayerBase> player;
1217
1218 player_type playerType = getPlayerType(fd, offset, length);
1219 LOGV("player type = %d", playerType);
1220
1221 // create the right type of player
1222 sp<AudioCache> cache = new AudioCache("decode_fd");
1223 player = android::createPlayer(playerType, cache.get(), cache->notify);
1224 if (player == NULL) goto Exit;
1225 if (player->hardwareOutput()) goto Exit;
1226
1227 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1228
1229 // set data source
1230 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1231
1232 LOGV("prepare");
1233 player->prepareAsync();
1234
1235 LOGV("wait for prepare");
1236 if (cache->wait() != NO_ERROR) goto Exit;
1237
1238 LOGV("start");
1239 player->start();
1240
1241 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001242 cache->wait();
1243 // in case of error, return what was successfully decoded.
1244 if (cache->size() == 0) {
1245 goto Exit;
1246 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001247
1248 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1249 *pSampleRate = cache->sampleRate();
1250 *pNumChannels = cache->channelCount();
1251 *pFormat = cache->format();
1252 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1253
1254Exit:
1255 if (player != 0) player->reset();
1256 ::close(fd);
1257 return mem;
1258}
1259
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001260
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001261#undef LOG_TAG
1262#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001263MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001264 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001265 mCallbackCookie(NULL),
1266 mSessionId(sessionId) {
1267 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268 mTrack = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -07001269 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270 mLeftVolume = 1.0;
1271 mRightVolume = 1.0;
1272 mLatency = 0;
1273 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001274 mAuxEffectId = 0;
1275 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001276 setMinBufferCount();
1277}
1278
1279MediaPlayerService::AudioOutput::~AudioOutput()
1280{
1281 close();
1282}
1283
1284void MediaPlayerService::AudioOutput::setMinBufferCount()
1285{
1286 char value[PROPERTY_VALUE_MAX];
1287 if (property_get("ro.kernel.qemu", value, 0)) {
1288 mIsOnEmulator = true;
1289 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1290 }
1291}
1292
1293bool MediaPlayerService::AudioOutput::isOnEmulator()
1294{
1295 setMinBufferCount();
1296 return mIsOnEmulator;
1297}
1298
1299int MediaPlayerService::AudioOutput::getMinBufferCount()
1300{
1301 setMinBufferCount();
1302 return mMinBufferCount;
1303}
1304
1305ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1306{
1307 if (mTrack == 0) return NO_INIT;
1308 return mTrack->frameCount() * frameSize();
1309}
1310
1311ssize_t MediaPlayerService::AudioOutput::frameCount() const
1312{
1313 if (mTrack == 0) return NO_INIT;
1314 return mTrack->frameCount();
1315}
1316
1317ssize_t MediaPlayerService::AudioOutput::channelCount() const
1318{
1319 if (mTrack == 0) return NO_INIT;
1320 return mTrack->channelCount();
1321}
1322
1323ssize_t MediaPlayerService::AudioOutput::frameSize() const
1324{
1325 if (mTrack == 0) return NO_INIT;
1326 return mTrack->frameSize();
1327}
1328
1329uint32_t MediaPlayerService::AudioOutput::latency () const
1330{
1331 return mLatency;
1332}
1333
1334float MediaPlayerService::AudioOutput::msecsPerFrame() const
1335{
1336 return mMsecsPerFrame;
1337}
1338
Eric Laurent342e9cf2010-01-19 17:37:09 -08001339status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1340{
1341 if (mTrack == 0) return NO_INIT;
1342 return mTrack->getPosition(position);
1343}
1344
Andreas Huber20111aa2009-07-14 16:56:47 -07001345status_t MediaPlayerService::AudioOutput::open(
1346 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1347 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001348{
Andreas Huber20111aa2009-07-14 16:56:47 -07001349 mCallback = cb;
1350 mCallbackCookie = cookie;
1351
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001352 // Check argument "bufferCount" against the mininum buffer count
1353 if (bufferCount < mMinBufferCount) {
1354 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1355 bufferCount = mMinBufferCount;
1356
1357 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001358 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 if (mTrack) close();
1360 int afSampleRate;
1361 int afFrameCount;
1362 int frameCount;
1363
1364 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1365 return NO_INIT;
1366 }
1367 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1368 return NO_INIT;
1369 }
1370
1371 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001372
1373 AudioTrack *t;
1374 if (mCallback != NULL) {
1375 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001376 mStreamType,
1377 sampleRate,
1378 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001379 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001380 frameCount,
1381 0 /* flags */,
1382 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001383 this,
1384 0,
1385 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001386 } else {
1387 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001388 mStreamType,
1389 sampleRate,
1390 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001391 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001392 frameCount,
1393 0,
1394 NULL,
1395 NULL,
1396 0,
1397 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001398 }
1399
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1401 LOGE("Unable to create audio track");
1402 delete t;
1403 return NO_INIT;
1404 }
1405
1406 LOGV("setVolume");
1407 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001408
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001409 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001410 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001412
1413 t->setAuxEffectSendLevel(mSendLevel);
1414 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415}
1416
1417void MediaPlayerService::AudioOutput::start()
1418{
1419 LOGV("start");
1420 if (mTrack) {
1421 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001422 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 mTrack->start();
1424 }
1425}
1426
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001427
1428
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1430{
Andreas Huber20111aa2009-07-14 16:56:47 -07001431 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1432
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001433 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001434 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001435 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001436 return ret;
1437 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438 return NO_INIT;
1439}
1440
1441void MediaPlayerService::AudioOutput::stop()
1442{
1443 LOGV("stop");
1444 if (mTrack) mTrack->stop();
1445}
1446
1447void MediaPlayerService::AudioOutput::flush()
1448{
1449 LOGV("flush");
1450 if (mTrack) mTrack->flush();
1451}
1452
1453void MediaPlayerService::AudioOutput::pause()
1454{
1455 LOGV("pause");
1456 if (mTrack) mTrack->pause();
1457}
1458
1459void MediaPlayerService::AudioOutput::close()
1460{
1461 LOGV("close");
1462 delete mTrack;
1463 mTrack = 0;
1464}
1465
1466void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1467{
1468 LOGV("setVolume(%f, %f)", left, right);
1469 mLeftVolume = left;
1470 mRightVolume = right;
1471 if (mTrack) {
1472 mTrack->setVolume(left, right);
1473 }
1474}
1475
Eric Laurent2beeb502010-07-16 07:43:46 -07001476status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1477{
1478 LOGV("setAuxEffectSendLevel(%f)", level);
1479 mSendLevel = level;
1480 if (mTrack) {
1481 return mTrack->setAuxEffectSendLevel(level);
1482 }
1483 return NO_ERROR;
1484}
1485
1486status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1487{
1488 LOGV("attachAuxEffect(%d)", effectId);
1489 mAuxEffectId = effectId;
1490 if (mTrack) {
1491 return mTrack->attachAuxEffect(effectId);
1492 }
1493 return NO_ERROR;
1494}
1495
Andreas Huber20111aa2009-07-14 16:56:47 -07001496// static
1497void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001498 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001499 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001500 if (event != AudioTrack::EVENT_MORE_DATA) {
1501 return;
1502 }
1503
1504 AudioOutput *me = (AudioOutput *)cookie;
1505 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1506
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001507 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001508 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001509
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001510 if (actualSize == 0 && buffer->size > 0) {
1511 // We've reached EOS but the audio track is not stopped yet,
1512 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001513
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001514 memset(buffer->raw, 0, buffer->size);
1515 actualSize = buffer->size;
1516 }
1517
1518 buffer->size = actualSize;
Andreas Huber20111aa2009-07-14 16:56:47 -07001519}
1520
Eric Laurent8c563ed2010-10-07 18:23:03 -07001521int MediaPlayerService::AudioOutput::getSessionId()
1522{
1523 return mSessionId;
1524}
1525
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001526#undef LOG_TAG
1527#define LOG_TAG "AudioCache"
1528MediaPlayerService::AudioCache::AudioCache(const char* name) :
1529 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1530 mError(NO_ERROR), mCommandComplete(false)
1531{
1532 // create ashmem heap
1533 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1534}
1535
1536uint32_t MediaPlayerService::AudioCache::latency () const
1537{
1538 return 0;
1539}
1540
1541float MediaPlayerService::AudioCache::msecsPerFrame() const
1542{
1543 return mMsecsPerFrame;
1544}
1545
Eric Laurent342e9cf2010-01-19 17:37:09 -08001546status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1547{
1548 if (position == 0) return BAD_VALUE;
1549 *position = mSize;
1550 return NO_ERROR;
1551}
1552
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001553////////////////////////////////////////////////////////////////////////////////
1554
1555struct CallbackThread : public Thread {
1556 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1557 MediaPlayerBase::AudioSink::AudioCallback cb,
1558 void *cookie);
1559
1560protected:
1561 virtual ~CallbackThread();
1562
1563 virtual bool threadLoop();
1564
1565private:
1566 wp<MediaPlayerBase::AudioSink> mSink;
1567 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1568 void *mCookie;
1569 void *mBuffer;
1570 size_t mBufferSize;
1571
1572 CallbackThread(const CallbackThread &);
1573 CallbackThread &operator=(const CallbackThread &);
1574};
1575
1576CallbackThread::CallbackThread(
1577 const wp<MediaPlayerBase::AudioSink> &sink,
1578 MediaPlayerBase::AudioSink::AudioCallback cb,
1579 void *cookie)
1580 : mSink(sink),
1581 mCallback(cb),
1582 mCookie(cookie),
1583 mBuffer(NULL),
1584 mBufferSize(0) {
1585}
1586
1587CallbackThread::~CallbackThread() {
1588 if (mBuffer) {
1589 free(mBuffer);
1590 mBuffer = NULL;
1591 }
1592}
1593
1594bool CallbackThread::threadLoop() {
1595 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1596 if (sink == NULL) {
1597 return false;
1598 }
1599
1600 if (mBuffer == NULL) {
1601 mBufferSize = sink->bufferSize();
1602 mBuffer = malloc(mBufferSize);
1603 }
1604
1605 size_t actualSize =
1606 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1607
1608 if (actualSize > 0) {
1609 sink->write(mBuffer, actualSize);
1610 }
1611
1612 return true;
1613}
1614
1615////////////////////////////////////////////////////////////////////////////////
1616
Andreas Huber20111aa2009-07-14 16:56:47 -07001617status_t MediaPlayerService::AudioCache::open(
1618 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1619 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001620{
Dave Sparks8eb80112009-12-09 20:20:26 -08001621 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001622 if (mHeap->getHeapID() < 0) {
1623 return NO_INIT;
1624 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001625
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 mSampleRate = sampleRate;
1627 mChannelCount = (uint16_t)channelCount;
1628 mFormat = (uint16_t)format;
1629 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001630
1631 if (cb != NULL) {
1632 mCallbackThread = new CallbackThread(this, cb, cookie);
1633 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634 return NO_ERROR;
1635}
1636
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001637void MediaPlayerService::AudioCache::start() {
1638 if (mCallbackThread != NULL) {
1639 mCallbackThread->run("AudioCache callback");
1640 }
1641}
1642
1643void MediaPlayerService::AudioCache::stop() {
1644 if (mCallbackThread != NULL) {
1645 mCallbackThread->requestExitAndWait();
1646 }
1647}
1648
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001649ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1650{
1651 LOGV("write(%p, %u)", buffer, size);
1652 if ((buffer == 0) || (size == 0)) return size;
1653
1654 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1655 if (p == NULL) return NO_INIT;
1656 p += mSize;
1657 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1658 if (mSize + size > mHeap->getSize()) {
1659 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1660 size = mHeap->getSize() - mSize;
1661 }
1662 memcpy(p, buffer, size);
1663 mSize += size;
1664 return size;
1665}
1666
1667// call with lock held
1668status_t MediaPlayerService::AudioCache::wait()
1669{
1670 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001671 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672 mSignal.wait(mLock);
1673 }
1674 mCommandComplete = false;
1675
1676 if (mError == NO_ERROR) {
1677 LOGV("wait - success");
1678 } else {
1679 LOGV("wait - error");
1680 }
1681 return mError;
1682}
1683
Gloria Wangb483c472011-04-11 17:23:27 -07001684void MediaPlayerService::AudioCache::notify(
1685 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686{
1687 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1688 AudioCache* p = static_cast<AudioCache*>(cookie);
1689
1690 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001691 switch (msg)
1692 {
1693 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001694 LOGE("Error %d, %d occurred", ext1, ext2);
1695 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001696 break;
1697 case MEDIA_PREPARED:
1698 LOGV("prepared");
1699 break;
1700 case MEDIA_PLAYBACK_COMPLETE:
1701 LOGV("playback complete");
1702 break;
1703 default:
1704 LOGV("ignored");
1705 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001706 }
1707
1708 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001709 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001710 p->mCommandComplete = true;
1711 p->mSignal.signal();
1712}
1713
Eric Laurent8c563ed2010-10-07 18:23:03 -07001714int MediaPlayerService::AudioCache::getSessionId()
1715{
1716 return 0;
1717}
1718
Gloria Wang7cf180c2011-02-19 18:37:57 -08001719void MediaPlayerService::addBatteryData(uint32_t params)
1720{
1721 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001722
1723 int32_t time = systemTime() / 1000000L;
1724
1725 // change audio output devices. This notification comes from AudioFlinger
1726 if ((params & kBatteryDataSpeakerOn)
1727 || (params & kBatteryDataOtherAudioDeviceOn)) {
1728
1729 int deviceOn[NUM_AUDIO_DEVICES];
1730 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1731 deviceOn[i] = 0;
1732 }
1733
1734 if ((params & kBatteryDataSpeakerOn)
1735 && (params & kBatteryDataOtherAudioDeviceOn)) {
1736 deviceOn[SPEAKER_AND_OTHER] = 1;
1737 } else if (params & kBatteryDataSpeakerOn) {
1738 deviceOn[SPEAKER] = 1;
1739 } else {
1740 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1741 }
1742
1743 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1744 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1745
1746 if (mBatteryAudio.refCount > 0) { // if playing audio
1747 if (!deviceOn[i]) {
1748 mBatteryAudio.lastTime[i] += time;
1749 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1750 mBatteryAudio.lastTime[i] = 0;
1751 } else {
1752 mBatteryAudio.lastTime[i] = 0 - time;
1753 }
1754 }
1755
1756 mBatteryAudio.deviceOn[i] = deviceOn[i];
1757 }
1758 }
1759 return;
1760 }
1761
1762 // an sudio stream is started
1763 if (params & kBatteryDataAudioFlingerStart) {
1764 // record the start time only if currently no other audio
1765 // is being played
1766 if (mBatteryAudio.refCount == 0) {
1767 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1768 if (mBatteryAudio.deviceOn[i]) {
1769 mBatteryAudio.lastTime[i] -= time;
1770 }
1771 }
1772 }
1773
1774 mBatteryAudio.refCount ++;
1775 return;
1776
1777 } else if (params & kBatteryDataAudioFlingerStop) {
1778 if (mBatteryAudio.refCount <= 0) {
1779 LOGW("Battery track warning: refCount is <= 0");
1780 return;
1781 }
1782
1783 // record the stop time only if currently this is the only
1784 // audio being played
1785 if (mBatteryAudio.refCount == 1) {
1786 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1787 if (mBatteryAudio.deviceOn[i]) {
1788 mBatteryAudio.lastTime[i] += time;
1789 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1790 mBatteryAudio.lastTime[i] = 0;
1791 }
1792 }
1793 }
1794
1795 mBatteryAudio.refCount --;
1796 return;
1797 }
1798
Gloria Wang7cf180c2011-02-19 18:37:57 -08001799 int uid = IPCThreadState::self()->getCallingUid();
1800 if (uid == AID_MEDIA) {
1801 return;
1802 }
1803 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001804
1805 if (index < 0) { // create a new entry for this UID
1806 BatteryUsageInfo info;
1807 info.audioTotalTime = 0;
1808 info.videoTotalTime = 0;
1809 info.audioLastTime = 0;
1810 info.videoLastTime = 0;
1811 info.refCount = 0;
1812
Gloria Wang9ee159b2011-02-24 14:51:45 -08001813 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1814 LOGE("Battery track error: no memory for new app");
1815 return;
1816 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001817 }
1818
1819 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1820
1821 if (params & kBatteryDataCodecStarted) {
1822 if (params & kBatteryDataTrackAudio) {
1823 info.audioLastTime -= time;
1824 info.refCount ++;
1825 }
1826 if (params & kBatteryDataTrackVideo) {
1827 info.videoLastTime -= time;
1828 info.refCount ++;
1829 }
1830 } else {
1831 if (info.refCount == 0) {
1832 LOGW("Battery track warning: refCount is already 0");
1833 return;
1834 } else if (info.refCount < 0) {
1835 LOGE("Battery track error: refCount < 0");
1836 mBatteryData.removeItem(uid);
1837 return;
1838 }
1839
1840 if (params & kBatteryDataTrackAudio) {
1841 info.audioLastTime += time;
1842 info.refCount --;
1843 }
1844 if (params & kBatteryDataTrackVideo) {
1845 info.videoLastTime += time;
1846 info.refCount --;
1847 }
1848
1849 // no stream is being played by this UID
1850 if (info.refCount == 0) {
1851 info.audioTotalTime += info.audioLastTime;
1852 info.audioLastTime = 0;
1853 info.videoTotalTime += info.videoLastTime;
1854 info.videoLastTime = 0;
1855 }
1856 }
1857}
1858
1859status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1860 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001861
1862 // audio output devices usage
1863 int32_t time = systemTime() / 1000000L; //in ms
1864 int32_t totalTime;
1865
1866 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1867 totalTime = mBatteryAudio.totalTime[i];
1868
1869 if (mBatteryAudio.deviceOn[i]
1870 && (mBatteryAudio.lastTime[i] != 0)) {
1871 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1872 totalTime += tmpTime;
1873 }
1874
1875 reply->writeInt32(totalTime);
1876 // reset the total time
1877 mBatteryAudio.totalTime[i] = 0;
1878 }
1879
1880 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001881 BatteryUsageInfo info;
1882 int size = mBatteryData.size();
1883
1884 reply->writeInt32(size);
1885 int i = 0;
1886
1887 while (i < size) {
1888 info = mBatteryData.valueAt(i);
1889
1890 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1891 reply->writeInt32(info.audioTotalTime);
1892 reply->writeInt32(info.videoTotalTime);
1893
1894 info.audioTotalTime = 0;
1895 info.videoTotalTime = 0;
1896
1897 // remove the UID entry where no stream is being played
1898 if (info.refCount <= 0) {
1899 mBatteryData.removeItemsAt(i);
1900 size --;
1901 i --;
1902 }
1903 i++;
1904 }
1905 return NO_ERROR;
1906}
nikoa64c8c72009-07-20 15:07:26 -07001907} // namespace android