blob: 1414f4dc4dd4f5500032c0e4c6d5a371392f8360 [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
Mike J. Chen1a5e6b12011-08-15 13:24:13 -070073namespace android {
74sp<MediaPlayerBase> createAAH_TXPlayer();
75sp<MediaPlayerBase> createAAH_RXPlayer();
76}
77
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070078namespace {
nikoa64c8c72009-07-20 15:07:26 -070079using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070080using android::status_t;
81using android::OK;
82using android::BAD_VALUE;
83using android::NOT_ENOUGH_DATA;
84using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070085
86// Max number of entries in the filter.
87const int kMaxFilterSize = 64; // I pulled that out of thin air.
88
nikoa64c8c72009-07-20 15:07:26 -070089// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070090
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091
92// Unmarshall a filter from a Parcel.
93// Filter format in a parcel:
94//
95// 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
96// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
97// | number of entries (n) |
98// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99// | metadata type 1 |
100// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101// | metadata type 2 |
102// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103// ....
104// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105// | metadata type n |
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107//
108// @param p Parcel that should start with a filter.
109// @param[out] filter On exit contains the list of metadata type to be
110// filtered.
111// @param[out] status On exit contains the status code to be returned.
112// @return true if the parcel starts with a valid filter.
113bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700114 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700115 status_t *status)
116{
Nicolas Catania48290382009-07-10 13:53:06 -0700117 int32_t val;
118 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700119 {
120 LOGE("Failed to read filter's length");
121 *status = NOT_ENOUGH_DATA;
122 return false;
123 }
124
Nicolas Catania48290382009-07-10 13:53:06 -0700125 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700126 {
Nicolas Catania48290382009-07-10 13:53:06 -0700127 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 *status = BAD_VALUE;
129 return false;
130 }
131
Nicolas Catania48290382009-07-10 13:53:06 -0700132 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133
134 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700135 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136
nikoa64c8c72009-07-20 15:07:26 -0700137 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138
Nicolas Catania48290382009-07-10 13:53:06 -0700139
140 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141 {
Nicolas Catania48290382009-07-10 13:53:06 -0700142 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143 *status = NOT_ENOUGH_DATA;
144 return false;
145 }
146
nikoa64c8c72009-07-20 15:07:26 -0700147 const Metadata::Type *data =
148 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
Nicolas Catania48290382009-07-10 13:53:06 -0700150 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 {
152 LOGE("Filter had no data");
153 *status = BAD_VALUE;
154 return false;
155 }
156
157 // TODO: The stl impl of vector would be more efficient here
158 // because it degenerates into a memcpy on pod types. Try to
159 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700160 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 {
Nicolas Catania48290382009-07-10 13:53:06 -0700162 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 ++data;
164 }
165 *status = OK;
166 return true;
167}
168
Nicolas Catania48290382009-07-10 13:53:06 -0700169// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170// @param val To be searched.
171// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700172bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173{
174 // Deal with empty and ANY right away
175 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700176 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700177
Nicolas Catania48290382009-07-10 13:53:06 -0700178 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179}
180
181} // anonymous namespace
182
183
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800184namespace android {
185
Dave Burked681bbb2011-08-30 14:39:17 +0100186static bool checkPermission(const char* permissionString) {
187#ifndef HAVE_ANDROID_OS
188 return true;
189#endif
190 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
191 bool ok = checkCallingPermission(String16(permissionString));
192 if (!ok) LOGE("Request requires %s", permissionString);
193 return ok;
194}
195
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800196// TODO: Temp hack until we can register players
197typedef struct {
198 const char *extension;
199 const player_type playertype;
200} extmap;
201extmap FILE_EXTS [] = {
202 {".mid", SONIVOX_PLAYER},
203 {".midi", SONIVOX_PLAYER},
204 {".smf", SONIVOX_PLAYER},
205 {".xmf", SONIVOX_PLAYER},
206 {".imy", SONIVOX_PLAYER},
207 {".rtttl", SONIVOX_PLAYER},
208 {".rtx", SONIVOX_PLAYER},
209 {".ota", SONIVOX_PLAYER},
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800210};
211
212// 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 -0800213/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
214/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
215
216void MediaPlayerService::instantiate() {
217 defaultServiceManager()->addService(
218 String16("media.player"), new MediaPlayerService());
219}
220
221MediaPlayerService::MediaPlayerService()
222{
223 LOGV("MediaPlayerService created");
224 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800225
226 mBatteryAudio.refCount = 0;
227 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
228 mBatteryAudio.deviceOn[i] = 0;
229 mBatteryAudio.lastTime[i] = 0;
230 mBatteryAudio.totalTime[i] = 0;
231 }
232 // speaker is on by default
233 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800234}
235
236MediaPlayerService::~MediaPlayerService()
237{
238 LOGV("MediaPlayerService destroyed");
239}
240
241sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
242{
Gloria Wangdac6a312009-10-29 15:46:37 -0700243 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
244 wp<MediaRecorderClient> w = recorder;
245 Mutex::Autolock lock(mLock);
246 mMediaRecorderClients.add(w);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800247 LOGV("Create new media recorder client from pid %d", pid);
248 return recorder;
249}
250
Gloria Wangdac6a312009-10-29 15:46:37 -0700251void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
252{
253 Mutex::Autolock lock(mLock);
254 mMediaRecorderClients.remove(client);
255 LOGV("Delete media recorder client");
256}
257
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800258sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
259{
260 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
261 LOGV("Create new media retriever from pid %d", pid);
262 return retriever;
263}
264
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800265sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100266 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800267{
268 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700269
270 sp<Client> c = new Client(
271 this, pid, connId, client, audioSessionId,
272 IPCThreadState::self()->getCallingUid());
273
Dave Burked681bbb2011-08-30 14:39:17 +0100274 LOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
275 IPCThreadState::self()->getCallingUid());
276
277 wp<Client> w = c;
278 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279 Mutex::Autolock lock(mLock);
280 mClients.add(w);
281 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800282 return c;
283}
284
Andreas Huber318ad9c2009-10-15 13:46:54 -0700285sp<IOMX> MediaPlayerService::getOMX() {
286 Mutex::Autolock autoLock(mLock);
287
288 if (mOMX.get() == NULL) {
289 mOMX = new OMX;
290 }
291
292 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700293}
294
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300
301 result.append(" AudioCache\n");
302 if (mHeap != 0) {
303 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
304 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
305 result.append(buffer);
306 }
307 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
308 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
309 result.append(buffer);
310 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
311 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
312 result.append(buffer);
313 ::write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
317status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
318{
319 const size_t SIZE = 256;
320 char buffer[SIZE];
321 String8 result;
322
323 result.append(" AudioOutput\n");
324 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
325 mStreamType, mLeftVolume, mRightVolume);
326 result.append(buffer);
327 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
328 mMsecsPerFrame, mLatency);
329 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700330 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
331 mAuxEffectId, mSendLevel);
332 result.append(buffer);
333
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800334 ::write(fd, result.string(), result.size());
335 if (mTrack != 0) {
336 mTrack->dump(fd, args);
337 }
338 return NO_ERROR;
339}
340
341status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
342{
343 const size_t SIZE = 256;
344 char buffer[SIZE];
345 String8 result;
346 result.append(" Client\n");
347 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
348 mPid, mConnId, mStatus, mLoop?"true": "false");
349 result.append(buffer);
350 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700351 if (mPlayer != NULL) {
352 mPlayer->dump(fd, args);
353 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800354 if (mAudioOutput != 0) {
355 mAudioOutput->dump(fd, args);
356 }
357 write(fd, "\n", 1);
358 return NO_ERROR;
359}
360
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800361status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
362{
363 const size_t SIZE = 256;
364 char buffer[SIZE];
365 String8 result;
366 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
367 snprintf(buffer, SIZE, "Permission Denial: "
368 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
369 IPCThreadState::self()->getCallingPid(),
370 IPCThreadState::self()->getCallingUid());
371 result.append(buffer);
372 } else {
373 Mutex::Autolock lock(mLock);
374 for (int i = 0, n = mClients.size(); i < n; ++i) {
375 sp<Client> c = mClients[i].promote();
376 if (c != 0) c->dump(fd, args);
377 }
James Dongb9141222010-07-08 11:16:11 -0700378 if (mMediaRecorderClients.size() == 0) {
379 result.append(" No media recorder client\n\n");
380 } else {
381 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
382 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700383 if (c != 0) {
384 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
385 result.append(buffer);
386 write(fd, result.string(), result.size());
387 result = "\n";
388 c->dump(fd, args);
389 }
James Dongb9141222010-07-08 11:16:11 -0700390 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700391 }
392
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800393 result.append(" Files opened and/or mapped:\n");
Glenn Kasten0512ab52011-05-04 17:58:57 -0700394 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800395 FILE *f = fopen(buffer, "r");
396 if (f) {
397 while (!feof(f)) {
398 fgets(buffer, SIZE, f);
Dave Sparks02fa8342010-09-27 16:55:18 -0700399 if (strstr(buffer, " /mnt/sdcard/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700401 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800402 strstr(buffer, " /system/media/")) {
403 result.append(" ");
404 result.append(buffer);
405 }
406 }
407 fclose(f);
408 } else {
409 result.append("couldn't open ");
410 result.append(buffer);
411 result.append("\n");
412 }
413
Glenn Kasten0512ab52011-05-04 17:58:57 -0700414 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415 DIR *d = opendir(buffer);
416 if (d) {
417 struct dirent *ent;
418 while((ent = readdir(d)) != NULL) {
419 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten0512ab52011-05-04 17:58:57 -0700420 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800421 struct stat s;
422 if (lstat(buffer, &s) == 0) {
423 if ((s.st_mode & S_IFMT) == S_IFLNK) {
424 char linkto[256];
425 int len = readlink(buffer, linkto, sizeof(linkto));
426 if(len > 0) {
427 if(len > 255) {
428 linkto[252] = '.';
429 linkto[253] = '.';
430 linkto[254] = '.';
431 linkto[255] = 0;
432 } else {
433 linkto[len] = 0;
434 }
Dave Sparks02fa8342010-09-27 16:55:18 -0700435 if (strstr(linkto, "/mnt/sdcard/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700437 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438 strstr(linkto, "/system/media/") == linkto) {
439 result.append(" ");
440 result.append(buffer);
441 result.append(" -> ");
442 result.append(linkto);
443 result.append("\n");
444 }
445 }
446 } else {
447 result.append(" unexpected type for ");
448 result.append(buffer);
449 result.append("\n");
450 }
451 }
452 }
453 }
454 closedir(d);
455 } else {
456 result.append("couldn't open ");
457 result.append(buffer);
458 result.append("\n");
459 }
460
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 bool dumpMem = false;
462 for (size_t i = 0; i < args.size(); i++) {
463 if (args[i] == String16("-m")) {
464 dumpMem = true;
465 }
466 }
467 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700468 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 }
471 write(fd, result.string(), result.size());
472 return NO_ERROR;
473}
474
475void MediaPlayerService::removeClient(wp<Client> client)
476{
477 Mutex::Autolock lock(mLock);
478 mClients.remove(client);
479}
480
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700481MediaPlayerService::Client::Client(
482 const sp<MediaPlayerService>& service, pid_t pid,
483 int32_t connId, const sp<IMediaPlayerClient>& client,
484 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485{
486 LOGV("Client(%d) constructor", connId);
487 mPid = pid;
488 mConnId = connId;
489 mService = service;
490 mClient = client;
491 mLoop = false;
492 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700493 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700494 mUID = uid;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700495
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496#if CALLBACK_ANTAGONIZER
497 LOGD("create Antagonizer");
498 mAntagonizer = new Antagonizer(notify, this);
499#endif
500}
501
502MediaPlayerService::Client::~Client()
503{
504 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
505 mAudioOutput.clear();
506 wp<Client> client(this);
507 disconnect();
508 mService->removeClient(client);
509}
510
511void MediaPlayerService::Client::disconnect()
512{
513 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
514 // grab local reference and clear main reference to prevent future
515 // access to object
516 sp<MediaPlayerBase> p;
517 {
518 Mutex::Autolock l(mLock);
519 p = mPlayer;
520 }
Dave Sparks795fa582009-03-24 17:57:12 -0700521 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700522
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523 mPlayer.clear();
524
525 // clear the notification to prevent callbacks to dead client
526 // and reset the player. We assume the player will serialize
527 // access to itself if necessary.
528 if (p != 0) {
529 p->setNotifyCallback(0, 0);
530#if CALLBACK_ANTAGONIZER
531 LOGD("kill Antagonizer");
532 mAntagonizer->kill();
533#endif
534 p->reset();
535 }
536
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700537 disconnectNativeWindow();
538
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539 IPCThreadState::self()->flushCommands();
540}
541
Andreas Huber47f59cf2009-08-07 09:30:32 -0700542static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700543 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700544}
545
James Dong148c1a22009-09-06 14:29:45 -0700546player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547{
548 char buf[20];
549 lseek(fd, offset, SEEK_SET);
550 read(fd, buf, sizeof(buf));
551 lseek(fd, offset, SEEK_SET);
552
553 long ident = *((long*)buf);
554
555 // Ogg vorbis?
556 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700557 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558
559 // Some kind of MIDI?
560 EAS_DATA_HANDLE easdata;
561 if (EAS_Init(&easdata) == EAS_SUCCESS) {
562 EAS_FILE locator;
563 locator.path = NULL;
564 locator.fd = fd;
565 locator.offset = offset;
566 locator.length = length;
567 EAS_HANDLE eashandle;
568 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
569 EAS_CloseFile(easdata, eashandle);
570 EAS_Shutdown(easdata);
571 return SONIVOX_PLAYER;
572 }
573 EAS_Shutdown(easdata);
574 }
575
Andreas Huber47f59cf2009-08-07 09:30:32 -0700576 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577}
578
James Dong148c1a22009-09-06 14:29:45 -0700579player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580{
Nicolas Catania14d27472009-07-13 14:37:49 -0700581 if (TestPlayerStub::canBeUsed(url)) {
582 return TEST_PLAYER;
583 }
584
Andreas Huber0a73d812011-03-21 16:28:04 -0700585 if (!strncasecmp("http://", url, 7)
586 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-02-16 09:05:38 -0800587 size_t len = strlen(url);
588 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
589 return NU_PLAYER;
590 }
Andreas Huber5bc087c2010-12-23 10:27:40 -0800591
Andreas Hubered8d14f2011-02-16 09:05:38 -0800592 if (strstr(url,"m3u8")) {
593 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800594 }
595 }
596
Andreas Huber2bfdd422011-10-11 15:24:07 -0700597 if (!strncasecmp("rtsp://", url, 7)) {
598 return NU_PLAYER;
599 }
600
Mike J. Chen1a5e6b12011-08-15 13:24:13 -0700601 if (!strncasecmp("aahRX://", url, 8)) {
602 return AAH_RX_PLAYER;
603 }
604
605 if (!strncasecmp("aahTX://", url, 8)) {
606 return AAH_TX_PLAYER;
607 }
608
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 // use MidiFile for MIDI extensions
610 int lenURL = strlen(url);
611 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
612 int len = strlen(FILE_EXTS[i].extension);
613 int start = lenURL - len;
614 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900615 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700616 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 }
618 }
619 }
620
Andreas Huber47f59cf2009-08-07 09:30:32 -0700621 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800622}
623
624static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
625 notify_callback_f notifyFunc)
626{
627 sp<MediaPlayerBase> p;
628 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629 case SONIVOX_PLAYER:
630 LOGV(" create MidiFile");
631 p = new MidiFile();
632 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700633 case STAGEFRIGHT_PLAYER:
634 LOGV(" create StagefrightPlayer");
635 p = new StagefrightPlayer;
636 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800637 case NU_PLAYER:
638 LOGV(" create NuPlayer");
639 p = new NuPlayerDriver;
640 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700641 case TEST_PLAYER:
642 LOGV("Create Test Player stub");
643 p = new TestPlayerStub();
644 break;
Mike J. Chen1a5e6b12011-08-15 13:24:13 -0700645 case AAH_RX_PLAYER:
646 LOGV(" create A@H RX Player");
647 p = createAAH_RXPlayer();
648 break;
649 case AAH_TX_PLAYER:
650 LOGV(" create A@H TX Player");
651 p = createAAH_TXPlayer();
652 break;
James Dong30d713a2010-11-10 18:42:40 -0800653 default:
654 LOGE("Unknown player type: %d", playerType);
655 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 }
657 if (p != NULL) {
658 if (p->initCheck() == NO_ERROR) {
659 p->setNotifyCallback(cookie, notifyFunc);
660 } else {
661 p.clear();
662 }
663 }
664 if (p == NULL) {
665 LOGE("Failed to create player object");
666 }
667 return p;
668}
669
670sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
671{
672 // determine if we have the right player type
673 sp<MediaPlayerBase> p = mPlayer;
674 if ((p != NULL) && (p->playerType() != playerType)) {
675 LOGV("delete player");
676 p.clear();
677 }
678 if (p == NULL) {
679 p = android::createPlayer(playerType, this, notify);
680 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700681
Jason Simmonsdb29e522011-08-12 13:46:55 -0700682 if (p != NULL) {
683 p->setUID(mUID);
684 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700685
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800686 return p;
687}
688
Andreas Huber2db84552010-01-28 11:19:57 -0800689status_t MediaPlayerService::Client::setDataSource(
690 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691{
692 LOGV("setDataSource(%s)", url);
693 if (url == NULL)
694 return UNKNOWN_ERROR;
695
Dave Burked681bbb2011-08-30 14:39:17 +0100696 if ((strncmp(url, "http://", 7) == 0) ||
697 (strncmp(url, "https://", 8) == 0) ||
698 (strncmp(url, "rtsp://", 7) == 0)) {
699 if (!checkPermission("android.permission.INTERNET")) {
700 return PERMISSION_DENIED;
701 }
702 }
703
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704 if (strncmp(url, "content://", 10) == 0) {
705 // get a filedescriptor for the content Uri and
706 // pass it to the setDataSource(fd) method
707
708 String16 url16(url);
709 int fd = android::openContentProviderFile(url16);
710 if (fd < 0)
711 {
712 LOGE("Couldn't open fd for %s", url);
713 return UNKNOWN_ERROR;
714 }
715 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
716 close(fd);
717 return mStatus;
718 } else {
719 player_type playerType = getPlayerType(url);
720 LOGV("player type = %d", playerType);
721
722 // create the right type of player
723 sp<MediaPlayerBase> p = createPlayer(playerType);
724 if (p == NULL) return NO_INIT;
725
726 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700727 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
729 }
730
731 // now set data source
732 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800733 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700734 if (mStatus == NO_ERROR) {
735 mPlayer = p;
736 } else {
737 LOGE(" error: %d", mStatus);
738 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739 return mStatus;
740 }
741}
742
743status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
744{
745 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
746 struct stat sb;
747 int ret = fstat(fd, &sb);
748 if (ret != 0) {
749 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
750 return UNKNOWN_ERROR;
751 }
752
753 LOGV("st_dev = %llu", sb.st_dev);
754 LOGV("st_mode = %u", sb.st_mode);
755 LOGV("st_uid = %lu", sb.st_uid);
756 LOGV("st_gid = %lu", sb.st_gid);
757 LOGV("st_size = %llu", sb.st_size);
758
759 if (offset >= sb.st_size) {
760 LOGE("offset error");
761 ::close(fd);
762 return UNKNOWN_ERROR;
763 }
764 if (offset + length > sb.st_size) {
765 length = sb.st_size - offset;
766 LOGV("calculated length = %lld", length);
767 }
768
769 player_type playerType = getPlayerType(fd, offset, length);
770 LOGV("player type = %d", playerType);
771
772 // create the right type of player
773 sp<MediaPlayerBase> p = createPlayer(playerType);
774 if (p == NULL) return NO_INIT;
775
776 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700777 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
779 }
780
781 // now set data source
782 mStatus = p->setDataSource(fd, offset, length);
783 if (mStatus == NO_ERROR) mPlayer = p;
Dave Burked681bbb2011-08-30 14:39:17 +0100784
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785 return mStatus;
786}
787
Andreas Hubere2b10282010-11-23 11:41:34 -0800788status_t MediaPlayerService::Client::setDataSource(
789 const sp<IStreamSource> &source) {
790 // create the right type of player
Andreas Huberf9334412010-12-15 15:17:42 -0800791 sp<MediaPlayerBase> p = createPlayer(NU_PLAYER);
Andreas Hubere2b10282010-11-23 11:41:34 -0800792
793 if (p == NULL) {
794 return NO_INIT;
795 }
796
797 if (!p->hardwareOutput()) {
798 mAudioOutput = new AudioOutput(mAudioSessionId);
799 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
800 }
801
802 // now set data source
803 mStatus = p->setDataSource(source);
804
805 if (mStatus == OK) {
806 mPlayer = p;
807 }
808
809 return mStatus;
810}
811
Andreas Huber5daeb122010-08-16 08:49:37 -0700812status_t MediaPlayerService::Client::setVideoSurface(const sp<Surface>& surface)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813{
814 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
815 sp<MediaPlayerBase> p = getPlayer();
816 if (p == 0) return UNKNOWN_ERROR;
817 return p->setVideoSurface(surface);
818}
819
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700820void MediaPlayerService::Client::disconnectNativeWindow() {
821 if (mConnectedWindow != NULL) {
822 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
823 NATIVE_WINDOW_API_MEDIA);
824
825 if (err != OK) {
826 LOGW("native_window_api_disconnect returned an error: %s (%d)",
827 strerror(-err), err);
828 }
829 }
830 mConnectedWindow.clear();
831}
832
Glenn Kasten11731182011-02-08 17:26:17 -0800833status_t MediaPlayerService::Client::setVideoSurfaceTexture(
834 const sp<ISurfaceTexture>& surfaceTexture)
835{
836 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
837 sp<MediaPlayerBase> p = getPlayer();
838 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700839
840 sp<IBinder> binder(surfaceTexture == NULL ? NULL :
841 surfaceTexture->asBinder());
842 if (mConnectedWindowBinder == binder) {
843 return OK;
844 }
845
846 sp<ANativeWindow> anw;
847 if (surfaceTexture != NULL) {
848 anw = new SurfaceTextureClient(surfaceTexture);
849 status_t err = native_window_api_connect(anw.get(),
850 NATIVE_WINDOW_API_MEDIA);
851
852 if (err != OK) {
853 LOGE("setVideoSurfaceTexture failed: %d", err);
854 // Note that we must do the reset before disconnecting from the ANW.
855 // Otherwise queue/dequeue calls could be made on the disconnected
856 // ANW, which may result in errors.
857 reset();
858
859 disconnectNativeWindow();
860
861 return err;
862 }
863 }
864
865 // Note that we must set the player's new SurfaceTexture before
866 // disconnecting the old one. Otherwise queue/dequeue calls could be made
867 // on the disconnected ANW, which may result in errors.
868 status_t err = p->setVideoSurfaceTexture(surfaceTexture);
869
870 disconnectNativeWindow();
871
872 mConnectedWindow = anw;
873
874 if (err == OK) {
875 mConnectedWindowBinder = binder;
876 } else {
877 disconnectNativeWindow();
878 }
879
880 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800881}
882
Nicolas Catania1d187f12009-05-12 23:25:55 -0700883status_t MediaPlayerService::Client::invoke(const Parcel& request,
884 Parcel *reply)
885{
886 sp<MediaPlayerBase> p = getPlayer();
887 if (p == NULL) return UNKNOWN_ERROR;
888 return p->invoke(request, reply);
889}
890
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700891// This call doesn't need to access the native player.
892status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
893{
894 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700895 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700896
Nicolas Catania48290382009-07-10 13:53:06 -0700897 if (unmarshallFilter(filter, &allow, &status) &&
898 unmarshallFilter(filter, &drop, &status)) {
899 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700900
901 mMetadataAllow = allow;
902 mMetadataDrop = drop;
903 }
904 return status;
905}
906
Nicolas Catania48290382009-07-10 13:53:06 -0700907status_t MediaPlayerService::Client::getMetadata(
908 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700909{
nikoa64c8c72009-07-20 15:07:26 -0700910 sp<MediaPlayerBase> player = getPlayer();
911 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700912
nikod608a812009-07-16 16:39:53 -0700913 status_t status;
914 // Placeholder for the return code, updated by the caller.
915 reply->writeInt32(-1);
916
nikoa64c8c72009-07-20 15:07:26 -0700917 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700918
919 // We don't block notifications while we fetch the data. We clear
920 // mMetadataUpdated first so we don't lose notifications happening
921 // during the rest of this call.
922 {
923 Mutex::Autolock lock(mLock);
924 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700925 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700926 }
927 mMetadataUpdated.clear();
928 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700929
nikoa64c8c72009-07-20 15:07:26 -0700930 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700931
nikoa64c8c72009-07-20 15:07:26 -0700932 metadata.appendHeader();
933 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700934
935 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700936 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700937 LOGE("getMetadata failed %d", status);
938 return status;
939 }
940
941 // FIXME: Implement filtering on the result. Not critical since
942 // filtering takes place on the update notifications already. This
943 // would be when all the metadata are fetch and a filter is set.
944
nikod608a812009-07-16 16:39:53 -0700945 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700946 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700947 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700948}
949
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800950status_t MediaPlayerService::Client::prepareAsync()
951{
952 LOGV("[%d] prepareAsync", mConnId);
953 sp<MediaPlayerBase> p = getPlayer();
954 if (p == 0) return UNKNOWN_ERROR;
955 status_t ret = p->prepareAsync();
956#if CALLBACK_ANTAGONIZER
957 LOGD("start Antagonizer");
958 if (ret == NO_ERROR) mAntagonizer->start();
959#endif
960 return ret;
961}
962
963status_t MediaPlayerService::Client::start()
964{
965 LOGV("[%d] start", mConnId);
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 p->setLooping(mLoop);
969 return p->start();
970}
971
972status_t MediaPlayerService::Client::stop()
973{
974 LOGV("[%d] stop", mConnId);
975 sp<MediaPlayerBase> p = getPlayer();
976 if (p == 0) return UNKNOWN_ERROR;
977 return p->stop();
978}
979
980status_t MediaPlayerService::Client::pause()
981{
982 LOGV("[%d] pause", mConnId);
983 sp<MediaPlayerBase> p = getPlayer();
984 if (p == 0) return UNKNOWN_ERROR;
985 return p->pause();
986}
987
988status_t MediaPlayerService::Client::isPlaying(bool* state)
989{
990 *state = false;
991 sp<MediaPlayerBase> p = getPlayer();
992 if (p == 0) return UNKNOWN_ERROR;
993 *state = p->isPlaying();
994 LOGV("[%d] isPlaying: %d", mConnId, *state);
995 return NO_ERROR;
996}
997
998status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
999{
1000 LOGV("getCurrentPosition");
1001 sp<MediaPlayerBase> p = getPlayer();
1002 if (p == 0) return UNKNOWN_ERROR;
1003 status_t ret = p->getCurrentPosition(msec);
1004 if (ret == NO_ERROR) {
1005 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1006 } else {
1007 LOGE("getCurrentPosition returned %d", ret);
1008 }
1009 return ret;
1010}
1011
1012status_t MediaPlayerService::Client::getDuration(int *msec)
1013{
1014 LOGV("getDuration");
1015 sp<MediaPlayerBase> p = getPlayer();
1016 if (p == 0) return UNKNOWN_ERROR;
1017 status_t ret = p->getDuration(msec);
1018 if (ret == NO_ERROR) {
1019 LOGV("[%d] getDuration = %d", mConnId, *msec);
1020 } else {
1021 LOGE("getDuration returned %d", ret);
1022 }
1023 return ret;
1024}
1025
1026status_t MediaPlayerService::Client::seekTo(int msec)
1027{
1028 LOGV("[%d] seekTo(%d)", mConnId, msec);
1029 sp<MediaPlayerBase> p = getPlayer();
1030 if (p == 0) return UNKNOWN_ERROR;
1031 return p->seekTo(msec);
1032}
1033
1034status_t MediaPlayerService::Client::reset()
1035{
1036 LOGV("[%d] reset", mConnId);
1037 sp<MediaPlayerBase> p = getPlayer();
1038 if (p == 0) return UNKNOWN_ERROR;
1039 return p->reset();
1040}
1041
1042status_t MediaPlayerService::Client::setAudioStreamType(int type)
1043{
1044 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1045 // TODO: for hardware output, call player instead
1046 Mutex::Autolock l(mLock);
1047 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1048 return NO_ERROR;
1049}
1050
1051status_t MediaPlayerService::Client::setLooping(int loop)
1052{
1053 LOGV("[%d] setLooping(%d)", mConnId, loop);
1054 mLoop = loop;
1055 sp<MediaPlayerBase> p = getPlayer();
1056 if (p != 0) return p->setLooping(loop);
1057 return NO_ERROR;
1058}
1059
1060status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1061{
1062 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
Mike J. Chen1a5e6b12011-08-15 13:24:13 -07001063
1064 // for hardware output, call player instead
1065 sp<MediaPlayerBase> p = getPlayer();
1066 {
1067 Mutex::Autolock l(mLock);
1068 if (p != 0 && p->hardwareOutput()) {
1069 MediaPlayerHWInterface* hwp =
1070 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1071 return hwp->setVolume(leftVolume, rightVolume);
1072 } else {
1073 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1074 return NO_ERROR;
1075 }
1076 }
1077
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001078 return NO_ERROR;
1079}
1080
Eric Laurent2beeb502010-07-16 07:43:46 -07001081status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1082{
1083 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1084 Mutex::Autolock l(mLock);
1085 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1086 return NO_ERROR;
1087}
1088
1089status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1090{
1091 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1092 Mutex::Autolock l(mLock);
1093 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1094 return NO_ERROR;
1095}
Nicolas Catania48290382009-07-10 13:53:06 -07001096
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001097status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1098 LOGV("[%d] setParameter(%d)", mConnId, key);
1099 sp<MediaPlayerBase> p = getPlayer();
1100 if (p == 0) return UNKNOWN_ERROR;
1101 return p->setParameter(key, request);
1102}
1103
1104status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1105 LOGV("[%d] getParameter(%d)", mConnId, key);
1106 sp<MediaPlayerBase> p = getPlayer();
1107 if (p == 0) return UNKNOWN_ERROR;
1108 return p->getParameter(key, reply);
1109}
1110
Gloria Wangb483c472011-04-11 17:23:27 -07001111void MediaPlayerService::Client::notify(
1112 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001113{
1114 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001115
1116 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001117 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001118 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001119
1120 if(client->shouldDropMetadata(metadata_type)) {
1121 return;
1122 }
1123
1124 // Update the list of metadata that have changed. getMetadata
1125 // also access mMetadataUpdated and clears it.
1126 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001127 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001128 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001129 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001130}
1131
Nicolas Catania48290382009-07-10 13:53:06 -07001132
nikoa64c8c72009-07-20 15:07:26 -07001133bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001134{
Nicolas Catania48290382009-07-10 13:53:06 -07001135 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001136
Nicolas Catania48290382009-07-10 13:53:06 -07001137 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001138 return true;
1139 }
1140
Nicolas Catania48290382009-07-10 13:53:06 -07001141 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001142 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001143 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001144 return true;
1145 }
1146}
1147
Nicolas Catania48290382009-07-10 13:53:06 -07001148
nikoa64c8c72009-07-20 15:07:26 -07001149void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001150 Mutex::Autolock lock(mLock);
1151 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1152 mMetadataUpdated.add(metadata_type);
1153 }
1154}
1155
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001156#if CALLBACK_ANTAGONIZER
1157const int Antagonizer::interval = 10000; // 10 msecs
1158
1159Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1160 mExit(false), mActive(false), mClient(client), mCb(cb)
1161{
1162 createThread(callbackThread, this);
1163}
1164
1165void Antagonizer::kill()
1166{
1167 Mutex::Autolock _l(mLock);
1168 mActive = false;
1169 mExit = true;
1170 mCondition.wait(mLock);
1171}
1172
1173int Antagonizer::callbackThread(void* user)
1174{
1175 LOGD("Antagonizer started");
1176 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1177 while (!p->mExit) {
1178 if (p->mActive) {
1179 LOGV("send event");
1180 p->mCb(p->mClient, 0, 0, 0);
1181 }
1182 usleep(interval);
1183 }
1184 Mutex::Autolock _l(p->mLock);
1185 p->mCondition.signal();
1186 LOGD("Antagonizer stopped");
1187 return 0;
1188}
1189#endif
1190
1191static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1192
1193sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1194{
1195 LOGV("decode(%s)", url);
1196 sp<MemoryBase> mem;
1197 sp<MediaPlayerBase> player;
1198
1199 // Protect our precious, precious DRMd ringtones by only allowing
1200 // decoding of http, but not filesystem paths or content Uris.
1201 // If the application wants to decode those, it should open a
1202 // filedescriptor for them and use that.
1203 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1204 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1205 return mem;
1206 }
1207
1208 player_type playerType = getPlayerType(url);
1209 LOGV("player type = %d", playerType);
1210
1211 // create the right type of player
1212 sp<AudioCache> cache = new AudioCache(url);
1213 player = android::createPlayer(playerType, cache.get(), cache->notify);
1214 if (player == NULL) goto Exit;
1215 if (player->hardwareOutput()) goto Exit;
1216
1217 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1218
1219 // set data source
1220 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1221
1222 LOGV("prepare");
1223 player->prepareAsync();
1224
1225 LOGV("wait for prepare");
1226 if (cache->wait() != NO_ERROR) goto Exit;
1227
1228 LOGV("start");
1229 player->start();
1230
1231 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001232 cache->wait();
1233 // in case of error, return what was successfully decoded.
1234 if (cache->size() == 0) {
1235 goto Exit;
1236 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001237
1238 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1239 *pSampleRate = cache->sampleRate();
1240 *pNumChannels = cache->channelCount();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001241 *pFormat = (int)cache->format();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001242 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1243
1244Exit:
1245 if (player != 0) player->reset();
1246 return mem;
1247}
1248
1249sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1250{
1251 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1252 sp<MemoryBase> mem;
1253 sp<MediaPlayerBase> player;
1254
1255 player_type playerType = getPlayerType(fd, offset, length);
1256 LOGV("player type = %d", playerType);
1257
1258 // create the right type of player
1259 sp<AudioCache> cache = new AudioCache("decode_fd");
1260 player = android::createPlayer(playerType, cache.get(), cache->notify);
1261 if (player == NULL) goto Exit;
1262 if (player->hardwareOutput()) goto Exit;
1263
1264 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1265
1266 // set data source
1267 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1268
1269 LOGV("prepare");
1270 player->prepareAsync();
1271
1272 LOGV("wait for prepare");
1273 if (cache->wait() != NO_ERROR) goto Exit;
1274
1275 LOGV("start");
1276 player->start();
1277
1278 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001279 cache->wait();
1280 // in case of error, return what was successfully decoded.
1281 if (cache->size() == 0) {
1282 goto Exit;
1283 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001284
1285 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1286 *pSampleRate = cache->sampleRate();
1287 *pNumChannels = cache->channelCount();
1288 *pFormat = cache->format();
1289 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1290
1291Exit:
1292 if (player != 0) player->reset();
1293 ::close(fd);
1294 return mem;
1295}
1296
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001297
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001298#undef LOG_TAG
1299#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001300MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001301 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001302 mCallbackCookie(NULL),
1303 mSessionId(sessionId) {
1304 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001305 mTrack = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -07001306 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307 mLeftVolume = 1.0;
1308 mRightVolume = 1.0;
1309 mLatency = 0;
1310 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001311 mAuxEffectId = 0;
1312 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313 setMinBufferCount();
1314}
1315
1316MediaPlayerService::AudioOutput::~AudioOutput()
1317{
1318 close();
1319}
1320
1321void MediaPlayerService::AudioOutput::setMinBufferCount()
1322{
1323 char value[PROPERTY_VALUE_MAX];
1324 if (property_get("ro.kernel.qemu", value, 0)) {
1325 mIsOnEmulator = true;
1326 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1327 }
1328}
1329
1330bool MediaPlayerService::AudioOutput::isOnEmulator()
1331{
1332 setMinBufferCount();
1333 return mIsOnEmulator;
1334}
1335
1336int MediaPlayerService::AudioOutput::getMinBufferCount()
1337{
1338 setMinBufferCount();
1339 return mMinBufferCount;
1340}
1341
1342ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1343{
1344 if (mTrack == 0) return NO_INIT;
1345 return mTrack->frameCount() * frameSize();
1346}
1347
1348ssize_t MediaPlayerService::AudioOutput::frameCount() const
1349{
1350 if (mTrack == 0) return NO_INIT;
1351 return mTrack->frameCount();
1352}
1353
1354ssize_t MediaPlayerService::AudioOutput::channelCount() const
1355{
1356 if (mTrack == 0) return NO_INIT;
1357 return mTrack->channelCount();
1358}
1359
1360ssize_t MediaPlayerService::AudioOutput::frameSize() const
1361{
1362 if (mTrack == 0) return NO_INIT;
1363 return mTrack->frameSize();
1364}
1365
1366uint32_t MediaPlayerService::AudioOutput::latency () const
1367{
1368 return mLatency;
1369}
1370
1371float MediaPlayerService::AudioOutput::msecsPerFrame() const
1372{
1373 return mMsecsPerFrame;
1374}
1375
Eric Laurent342e9cf2010-01-19 17:37:09 -08001376status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1377{
1378 if (mTrack == 0) return NO_INIT;
1379 return mTrack->getPosition(position);
1380}
1381
Andreas Huber20111aa2009-07-14 16:56:47 -07001382status_t MediaPlayerService::AudioOutput::open(
1383 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1384 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385{
Andreas Huber20111aa2009-07-14 16:56:47 -07001386 mCallback = cb;
1387 mCallbackCookie = cookie;
1388
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389 // Check argument "bufferCount" against the mininum buffer count
1390 if (bufferCount < mMinBufferCount) {
1391 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1392 bufferCount = mMinBufferCount;
1393
1394 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001395 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001396 if (mTrack) close();
1397 int afSampleRate;
1398 int afFrameCount;
1399 int frameCount;
1400
1401 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1402 return NO_INIT;
1403 }
1404 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1405 return NO_INIT;
1406 }
1407
1408 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001409
1410 AudioTrack *t;
1411 if (mCallback != NULL) {
1412 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001413 mStreamType,
1414 sampleRate,
1415 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001416 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001417 frameCount,
1418 0 /* flags */,
1419 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001420 this,
1421 0,
1422 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001423 } else {
1424 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001425 mStreamType,
1426 sampleRate,
1427 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001428 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001429 frameCount,
1430 0,
1431 NULL,
1432 NULL,
1433 0,
1434 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001435 }
1436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1438 LOGE("Unable to create audio track");
1439 delete t;
1440 return NO_INIT;
1441 }
1442
1443 LOGV("setVolume");
1444 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001445
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001446 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001447 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001448 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001449
1450 t->setAuxEffectSendLevel(mSendLevel);
1451 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001452}
1453
1454void MediaPlayerService::AudioOutput::start()
1455{
1456 LOGV("start");
1457 if (mTrack) {
1458 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001459 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001460 mTrack->start();
1461 }
1462}
1463
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001464
1465
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001466ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1467{
Andreas Huber20111aa2009-07-14 16:56:47 -07001468 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1469
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001471 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001472 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001473 return ret;
1474 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001475 return NO_INIT;
1476}
1477
1478void MediaPlayerService::AudioOutput::stop()
1479{
1480 LOGV("stop");
1481 if (mTrack) mTrack->stop();
1482}
1483
1484void MediaPlayerService::AudioOutput::flush()
1485{
1486 LOGV("flush");
1487 if (mTrack) mTrack->flush();
1488}
1489
1490void MediaPlayerService::AudioOutput::pause()
1491{
1492 LOGV("pause");
1493 if (mTrack) mTrack->pause();
1494}
1495
1496void MediaPlayerService::AudioOutput::close()
1497{
1498 LOGV("close");
1499 delete mTrack;
1500 mTrack = 0;
1501}
1502
1503void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1504{
1505 LOGV("setVolume(%f, %f)", left, right);
1506 mLeftVolume = left;
1507 mRightVolume = right;
1508 if (mTrack) {
1509 mTrack->setVolume(left, right);
1510 }
1511}
1512
Eric Laurent2beeb502010-07-16 07:43:46 -07001513status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1514{
1515 LOGV("setAuxEffectSendLevel(%f)", level);
1516 mSendLevel = level;
1517 if (mTrack) {
1518 return mTrack->setAuxEffectSendLevel(level);
1519 }
1520 return NO_ERROR;
1521}
1522
1523status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1524{
1525 LOGV("attachAuxEffect(%d)", effectId);
1526 mAuxEffectId = effectId;
1527 if (mTrack) {
1528 return mTrack->attachAuxEffect(effectId);
1529 }
1530 return NO_ERROR;
1531}
1532
Andreas Huber20111aa2009-07-14 16:56:47 -07001533// static
1534void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001535 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001536 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001537 if (event != AudioTrack::EVENT_MORE_DATA) {
1538 return;
1539 }
1540
1541 AudioOutput *me = (AudioOutput *)cookie;
1542 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1543
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001544 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001545 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001546
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001547 if (actualSize == 0 && buffer->size > 0) {
1548 // We've reached EOS but the audio track is not stopped yet,
1549 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001550
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001551 memset(buffer->raw, 0, buffer->size);
1552 actualSize = buffer->size;
1553 }
1554
1555 buffer->size = actualSize;
Andreas Huber20111aa2009-07-14 16:56:47 -07001556}
1557
Eric Laurent8c563ed2010-10-07 18:23:03 -07001558int MediaPlayerService::AudioOutput::getSessionId()
1559{
1560 return mSessionId;
1561}
1562
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001563#undef LOG_TAG
1564#define LOG_TAG "AudioCache"
1565MediaPlayerService::AudioCache::AudioCache(const char* name) :
1566 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1567 mError(NO_ERROR), mCommandComplete(false)
1568{
1569 // create ashmem heap
1570 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1571}
1572
1573uint32_t MediaPlayerService::AudioCache::latency () const
1574{
1575 return 0;
1576}
1577
1578float MediaPlayerService::AudioCache::msecsPerFrame() const
1579{
1580 return mMsecsPerFrame;
1581}
1582
Eric Laurent342e9cf2010-01-19 17:37:09 -08001583status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1584{
1585 if (position == 0) return BAD_VALUE;
1586 *position = mSize;
1587 return NO_ERROR;
1588}
1589
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001590////////////////////////////////////////////////////////////////////////////////
1591
1592struct CallbackThread : public Thread {
1593 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1594 MediaPlayerBase::AudioSink::AudioCallback cb,
1595 void *cookie);
1596
1597protected:
1598 virtual ~CallbackThread();
1599
1600 virtual bool threadLoop();
1601
1602private:
1603 wp<MediaPlayerBase::AudioSink> mSink;
1604 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1605 void *mCookie;
1606 void *mBuffer;
1607 size_t mBufferSize;
1608
1609 CallbackThread(const CallbackThread &);
1610 CallbackThread &operator=(const CallbackThread &);
1611};
1612
1613CallbackThread::CallbackThread(
1614 const wp<MediaPlayerBase::AudioSink> &sink,
1615 MediaPlayerBase::AudioSink::AudioCallback cb,
1616 void *cookie)
1617 : mSink(sink),
1618 mCallback(cb),
1619 mCookie(cookie),
1620 mBuffer(NULL),
1621 mBufferSize(0) {
1622}
1623
1624CallbackThread::~CallbackThread() {
1625 if (mBuffer) {
1626 free(mBuffer);
1627 mBuffer = NULL;
1628 }
1629}
1630
1631bool CallbackThread::threadLoop() {
1632 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1633 if (sink == NULL) {
1634 return false;
1635 }
1636
1637 if (mBuffer == NULL) {
1638 mBufferSize = sink->bufferSize();
1639 mBuffer = malloc(mBufferSize);
1640 }
1641
1642 size_t actualSize =
1643 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1644
1645 if (actualSize > 0) {
1646 sink->write(mBuffer, actualSize);
1647 }
1648
1649 return true;
1650}
1651
1652////////////////////////////////////////////////////////////////////////////////
1653
Andreas Huber20111aa2009-07-14 16:56:47 -07001654status_t MediaPlayerService::AudioCache::open(
1655 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1656 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001657{
Dave Sparks8eb80112009-12-09 20:20:26 -08001658 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001659 if (mHeap->getHeapID() < 0) {
1660 return NO_INIT;
1661 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001662
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001663 mSampleRate = sampleRate;
1664 mChannelCount = (uint16_t)channelCount;
1665 mFormat = (uint16_t)format;
1666 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001667
1668 if (cb != NULL) {
1669 mCallbackThread = new CallbackThread(this, cb, cookie);
1670 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001671 return NO_ERROR;
1672}
1673
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001674void MediaPlayerService::AudioCache::start() {
1675 if (mCallbackThread != NULL) {
1676 mCallbackThread->run("AudioCache callback");
1677 }
1678}
1679
1680void MediaPlayerService::AudioCache::stop() {
1681 if (mCallbackThread != NULL) {
1682 mCallbackThread->requestExitAndWait();
1683 }
1684}
1685
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1687{
1688 LOGV("write(%p, %u)", buffer, size);
1689 if ((buffer == 0) || (size == 0)) return size;
1690
1691 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1692 if (p == NULL) return NO_INIT;
1693 p += mSize;
1694 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1695 if (mSize + size > mHeap->getSize()) {
1696 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1697 size = mHeap->getSize() - mSize;
1698 }
1699 memcpy(p, buffer, size);
1700 mSize += size;
1701 return size;
1702}
1703
1704// call with lock held
1705status_t MediaPlayerService::AudioCache::wait()
1706{
1707 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001708 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001709 mSignal.wait(mLock);
1710 }
1711 mCommandComplete = false;
1712
1713 if (mError == NO_ERROR) {
1714 LOGV("wait - success");
1715 } else {
1716 LOGV("wait - error");
1717 }
1718 return mError;
1719}
1720
Gloria Wangb483c472011-04-11 17:23:27 -07001721void MediaPlayerService::AudioCache::notify(
1722 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723{
1724 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1725 AudioCache* p = static_cast<AudioCache*>(cookie);
1726
1727 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001728 switch (msg)
1729 {
1730 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001731 LOGE("Error %d, %d occurred", ext1, ext2);
1732 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001733 break;
1734 case MEDIA_PREPARED:
1735 LOGV("prepared");
1736 break;
1737 case MEDIA_PLAYBACK_COMPLETE:
1738 LOGV("playback complete");
1739 break;
1740 default:
1741 LOGV("ignored");
1742 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001743 }
1744
1745 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001746 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001747 p->mCommandComplete = true;
1748 p->mSignal.signal();
1749}
1750
Eric Laurent8c563ed2010-10-07 18:23:03 -07001751int MediaPlayerService::AudioCache::getSessionId()
1752{
1753 return 0;
1754}
1755
Gloria Wang7cf180c2011-02-19 18:37:57 -08001756void MediaPlayerService::addBatteryData(uint32_t params)
1757{
1758 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001759
1760 int32_t time = systemTime() / 1000000L;
1761
1762 // change audio output devices. This notification comes from AudioFlinger
1763 if ((params & kBatteryDataSpeakerOn)
1764 || (params & kBatteryDataOtherAudioDeviceOn)) {
1765
1766 int deviceOn[NUM_AUDIO_DEVICES];
1767 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1768 deviceOn[i] = 0;
1769 }
1770
1771 if ((params & kBatteryDataSpeakerOn)
1772 && (params & kBatteryDataOtherAudioDeviceOn)) {
1773 deviceOn[SPEAKER_AND_OTHER] = 1;
1774 } else if (params & kBatteryDataSpeakerOn) {
1775 deviceOn[SPEAKER] = 1;
1776 } else {
1777 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1778 }
1779
1780 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1781 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1782
1783 if (mBatteryAudio.refCount > 0) { // if playing audio
1784 if (!deviceOn[i]) {
1785 mBatteryAudio.lastTime[i] += time;
1786 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1787 mBatteryAudio.lastTime[i] = 0;
1788 } else {
1789 mBatteryAudio.lastTime[i] = 0 - time;
1790 }
1791 }
1792
1793 mBatteryAudio.deviceOn[i] = deviceOn[i];
1794 }
1795 }
1796 return;
1797 }
1798
1799 // an sudio stream is started
1800 if (params & kBatteryDataAudioFlingerStart) {
1801 // record the start time only if currently no other audio
1802 // is being played
1803 if (mBatteryAudio.refCount == 0) {
1804 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1805 if (mBatteryAudio.deviceOn[i]) {
1806 mBatteryAudio.lastTime[i] -= time;
1807 }
1808 }
1809 }
1810
1811 mBatteryAudio.refCount ++;
1812 return;
1813
1814 } else if (params & kBatteryDataAudioFlingerStop) {
1815 if (mBatteryAudio.refCount <= 0) {
1816 LOGW("Battery track warning: refCount is <= 0");
1817 return;
1818 }
1819
1820 // record the stop time only if currently this is the only
1821 // audio being played
1822 if (mBatteryAudio.refCount == 1) {
1823 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1824 if (mBatteryAudio.deviceOn[i]) {
1825 mBatteryAudio.lastTime[i] += time;
1826 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1827 mBatteryAudio.lastTime[i] = 0;
1828 }
1829 }
1830 }
1831
1832 mBatteryAudio.refCount --;
1833 return;
1834 }
1835
Gloria Wang7cf180c2011-02-19 18:37:57 -08001836 int uid = IPCThreadState::self()->getCallingUid();
1837 if (uid == AID_MEDIA) {
1838 return;
1839 }
1840 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001841
1842 if (index < 0) { // create a new entry for this UID
1843 BatteryUsageInfo info;
1844 info.audioTotalTime = 0;
1845 info.videoTotalTime = 0;
1846 info.audioLastTime = 0;
1847 info.videoLastTime = 0;
1848 info.refCount = 0;
1849
Gloria Wang9ee159b2011-02-24 14:51:45 -08001850 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1851 LOGE("Battery track error: no memory for new app");
1852 return;
1853 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001854 }
1855
1856 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1857
1858 if (params & kBatteryDataCodecStarted) {
1859 if (params & kBatteryDataTrackAudio) {
1860 info.audioLastTime -= time;
1861 info.refCount ++;
1862 }
1863 if (params & kBatteryDataTrackVideo) {
1864 info.videoLastTime -= time;
1865 info.refCount ++;
1866 }
1867 } else {
1868 if (info.refCount == 0) {
1869 LOGW("Battery track warning: refCount is already 0");
1870 return;
1871 } else if (info.refCount < 0) {
1872 LOGE("Battery track error: refCount < 0");
1873 mBatteryData.removeItem(uid);
1874 return;
1875 }
1876
1877 if (params & kBatteryDataTrackAudio) {
1878 info.audioLastTime += time;
1879 info.refCount --;
1880 }
1881 if (params & kBatteryDataTrackVideo) {
1882 info.videoLastTime += time;
1883 info.refCount --;
1884 }
1885
1886 // no stream is being played by this UID
1887 if (info.refCount == 0) {
1888 info.audioTotalTime += info.audioLastTime;
1889 info.audioLastTime = 0;
1890 info.videoTotalTime += info.videoLastTime;
1891 info.videoLastTime = 0;
1892 }
1893 }
1894}
1895
1896status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1897 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001898
1899 // audio output devices usage
1900 int32_t time = systemTime() / 1000000L; //in ms
1901 int32_t totalTime;
1902
1903 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1904 totalTime = mBatteryAudio.totalTime[i];
1905
1906 if (mBatteryAudio.deviceOn[i]
1907 && (mBatteryAudio.lastTime[i] != 0)) {
1908 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1909 totalTime += tmpTime;
1910 }
1911
1912 reply->writeInt32(totalTime);
1913 // reset the total time
1914 mBatteryAudio.totalTime[i] = 0;
1915 }
1916
1917 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001918 BatteryUsageInfo info;
1919 int size = mBatteryData.size();
1920
1921 reply->writeInt32(size);
1922 int i = 0;
1923
1924 while (i < size) {
1925 info = mBatteryData.valueAt(i);
1926
1927 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1928 reply->writeInt32(info.audioTotalTime);
1929 reply->writeInt32(info.videoTotalTime);
1930
1931 info.audioTotalTime = 0;
1932 info.videoTotalTime = 0;
1933
1934 // remove the UID entry where no stream is being played
1935 if (info.refCount <= 0) {
1936 mBatteryData.removeItemsAt(i);
1937 size --;
1938 i --;
1939 }
1940 i++;
1941 }
1942 return NO_ERROR;
1943}
nikoa64c8c72009-07-20 15:07:26 -07001944} // namespace android