blob: 20d6d7ab53379da34ebf90d4a409c3ee5e51b9c3 [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
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Jamie Gennis7dae00b2011-10-26 18:36:31 -070041#include <gui/SurfaceTextureClient.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070045#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080046#include <cutils/properties.h>
47
48#include <media/MediaPlayerInterface.h>
49#include <media/mediarecorder.h>
50#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070051#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070053#include <media/MemoryLeakTrackUtil.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070054#include <media/stagefright/MediaErrors.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055
Dima Zavin64760242011-05-11 14:15:23 -070056#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070057
Gloria Wang7cf180c2011-02-19 18:37:57 -080058#include <private/android_filesystem_config.h>
59
James Dong559bf282012-03-28 10:29:14 -070060#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080061#include "MediaRecorderClient.h"
62#include "MediaPlayerService.h"
63#include "MetadataRetrieverClient.h"
64
65#include "MidiFile.h"
Nicolas Catania14d27472009-07-13 14:37:49 -070066#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070067#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080068#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070069
Andreas Huber20111aa2009-07-14 16:56:47 -070070#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070071
Andreas Hubered3e3e02012-03-26 11:13:27 -070072#include "Crypto.h"
73
John Grossman761defc2012-02-09 15:09:05 -080074namespace android {
75sp<MediaPlayerBase> createAAH_TXPlayer();
76sp<MediaPlayerBase> createAAH_RXPlayer();
77}
78
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070079namespace {
nikoa64c8c72009-07-20 15:07:26 -070080using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070081using android::status_t;
82using android::OK;
83using android::BAD_VALUE;
84using android::NOT_ENOUGH_DATA;
85using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070086
87// Max number of entries in the filter.
88const int kMaxFilterSize = 64; // I pulled that out of thin air.
89
nikoa64c8c72009-07-20 15:07:26 -070090// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070091
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070092
93// Unmarshall a filter from a Parcel.
94// Filter format in a parcel:
95//
96// 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
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// | number of entries (n) |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | metadata type 1 |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// | metadata type 2 |
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// ....
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | metadata type n |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108//
109// @param p Parcel that should start with a filter.
110// @param[out] filter On exit contains the list of metadata type to be
111// filtered.
112// @param[out] status On exit contains the status code to be returned.
113// @return true if the parcel starts with a valid filter.
114bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700115 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700116 status_t *status)
117{
Nicolas Catania48290382009-07-10 13:53:06 -0700118 int32_t val;
119 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700120 {
Steve Block29357bc2012-01-06 19:20:56 +0000121 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700122 *status = NOT_ENOUGH_DATA;
123 return false;
124 }
125
Nicolas Catania48290382009-07-10 13:53:06 -0700126 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 {
Steve Block29357bc2012-01-06 19:20:56 +0000128 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 *status = BAD_VALUE;
130 return false;
131 }
132
Nicolas Catania48290382009-07-10 13:53:06 -0700133 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134
135 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700136 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137
nikoa64c8c72009-07-20 15:07:26 -0700138 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139
Nicolas Catania48290382009-07-10 13:53:06 -0700140
141 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 {
Steve Block29357bc2012-01-06 19:20:56 +0000143 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144 *status = NOT_ENOUGH_DATA;
145 return false;
146 }
147
nikoa64c8c72009-07-20 15:07:26 -0700148 const Metadata::Type *data =
149 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
Nicolas Catania48290382009-07-10 13:53:06 -0700151 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 {
Steve Block29357bc2012-01-06 19:20:56 +0000153 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 *status = BAD_VALUE;
155 return false;
156 }
157
158 // TODO: The stl impl of vector would be more efficient here
159 // because it degenerates into a memcpy on pod types. Try to
160 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700161 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 {
Nicolas Catania48290382009-07-10 13:53:06 -0700163 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 ++data;
165 }
166 *status = OK;
167 return true;
168}
169
Nicolas Catania48290382009-07-10 13:53:06 -0700170// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171// @param val To be searched.
172// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700173bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174{
175 // Deal with empty and ANY right away
176 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700177 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178
Nicolas Catania48290382009-07-10 13:53:06 -0700179 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180}
181
182} // anonymous namespace
183
184
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800185namespace android {
186
Dave Burked681bbb2011-08-30 14:39:17 +0100187static bool checkPermission(const char* permissionString) {
188#ifndef HAVE_ANDROID_OS
189 return true;
190#endif
191 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
192 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000193 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100194 return ok;
195}
196
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800197// TODO: Temp hack until we can register players
198typedef struct {
199 const char *extension;
200 const player_type playertype;
201} extmap;
202extmap FILE_EXTS [] = {
203 {".mid", SONIVOX_PLAYER},
204 {".midi", SONIVOX_PLAYER},
205 {".smf", SONIVOX_PLAYER},
206 {".xmf", SONIVOX_PLAYER},
207 {".imy", SONIVOX_PLAYER},
208 {".rtttl", SONIVOX_PLAYER},
209 {".rtx", SONIVOX_PLAYER},
210 {".ota", SONIVOX_PLAYER},
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800211};
212
213// 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 -0800214/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
215/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
216
217void MediaPlayerService::instantiate() {
218 defaultServiceManager()->addService(
219 String16("media.player"), new MediaPlayerService());
220}
221
222MediaPlayerService::MediaPlayerService()
223{
Steve Block3856b092011-10-20 11:56:00 +0100224 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800225 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800226
227 mBatteryAudio.refCount = 0;
228 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
229 mBatteryAudio.deviceOn[i] = 0;
230 mBatteryAudio.lastTime[i] = 0;
231 mBatteryAudio.totalTime[i] = 0;
232 }
233 // speaker is on by default
234 mBatteryAudio.deviceOn[SPEAKER] = 1;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800235}
236
237MediaPlayerService::~MediaPlayerService()
238{
Steve Block3856b092011-10-20 11:56:00 +0100239 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800240}
241
242sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
243{
Gloria Wangdac6a312009-10-29 15:46:37 -0700244 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
245 wp<MediaRecorderClient> w = recorder;
246 Mutex::Autolock lock(mLock);
247 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100248 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800249 return recorder;
250}
251
Gloria Wangdac6a312009-10-29 15:46:37 -0700252void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
253{
254 Mutex::Autolock lock(mLock);
255 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100256 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700257}
258
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
260{
261 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100262 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263 return retriever;
264}
265
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100267 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800268{
269 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700270
271 sp<Client> c = new Client(
272 this, pid, connId, client, audioSessionId,
273 IPCThreadState::self()->getCallingUid());
274
Steve Block3856b092011-10-20 11:56:00 +0100275 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100276 IPCThreadState::self()->getCallingUid());
277
278 wp<Client> w = c;
279 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280 Mutex::Autolock lock(mLock);
281 mClients.add(w);
282 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800283 return c;
284}
285
Andreas Huber318ad9c2009-10-15 13:46:54 -0700286sp<IOMX> MediaPlayerService::getOMX() {
287 Mutex::Autolock autoLock(mLock);
288
289 if (mOMX.get() == NULL) {
290 mOMX = new OMX;
291 }
292
293 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700294}
295
Andreas Hubered3e3e02012-03-26 11:13:27 -0700296sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700297 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700298}
299
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
301{
302 const size_t SIZE = 256;
303 char buffer[SIZE];
304 String8 result;
305
306 result.append(" AudioCache\n");
307 if (mHeap != 0) {
308 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
309 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
310 result.append(buffer);
311 }
312 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
313 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
314 result.append(buffer);
315 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
316 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
317 result.append(buffer);
318 ::write(fd, result.string(), result.size());
319 return NO_ERROR;
320}
321
322status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
323{
324 const size_t SIZE = 256;
325 char buffer[SIZE];
326 String8 result;
327
328 result.append(" AudioOutput\n");
329 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
330 mStreamType, mLeftVolume, mRightVolume);
331 result.append(buffer);
332 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800333 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800334 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700335 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
336 mAuxEffectId, mSendLevel);
337 result.append(buffer);
338
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800339 ::write(fd, result.string(), result.size());
340 if (mTrack != 0) {
341 mTrack->dump(fd, args);
342 }
343 return NO_ERROR;
344}
345
346status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
347{
348 const size_t SIZE = 256;
349 char buffer[SIZE];
350 String8 result;
351 result.append(" Client\n");
352 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
353 mPid, mConnId, mStatus, mLoop?"true": "false");
354 result.append(buffer);
355 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700356 if (mPlayer != NULL) {
357 mPlayer->dump(fd, args);
358 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800359 if (mAudioOutput != 0) {
360 mAudioOutput->dump(fd, args);
361 }
362 write(fd, "\n", 1);
363 return NO_ERROR;
364}
365
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800366status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
367{
368 const size_t SIZE = 256;
369 char buffer[SIZE];
370 String8 result;
371 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
372 snprintf(buffer, SIZE, "Permission Denial: "
373 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
374 IPCThreadState::self()->getCallingPid(),
375 IPCThreadState::self()->getCallingUid());
376 result.append(buffer);
377 } else {
378 Mutex::Autolock lock(mLock);
379 for (int i = 0, n = mClients.size(); i < n; ++i) {
380 sp<Client> c = mClients[i].promote();
381 if (c != 0) c->dump(fd, args);
382 }
James Dongb9141222010-07-08 11:16:11 -0700383 if (mMediaRecorderClients.size() == 0) {
384 result.append(" No media recorder client\n\n");
385 } else {
386 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
387 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700388 if (c != 0) {
389 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
390 result.append(buffer);
391 write(fd, result.string(), result.size());
392 result = "\n";
393 c->dump(fd, args);
394 }
James Dongb9141222010-07-08 11:16:11 -0700395 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700396 }
397
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800398 result.append(" Files opened and/or mapped:\n");
Glenn Kasten0512ab52011-05-04 17:58:57 -0700399 snprintf(buffer, SIZE, "/proc/%d/maps", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400 FILE *f = fopen(buffer, "r");
401 if (f) {
402 while (!feof(f)) {
403 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700404 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800405 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700406 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407 strstr(buffer, " /system/media/")) {
408 result.append(" ");
409 result.append(buffer);
410 }
411 }
412 fclose(f);
413 } else {
414 result.append("couldn't open ");
415 result.append(buffer);
416 result.append("\n");
417 }
418
Glenn Kasten0512ab52011-05-04 17:58:57 -0700419 snprintf(buffer, SIZE, "/proc/%d/fd", gettid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 DIR *d = opendir(buffer);
421 if (d) {
422 struct dirent *ent;
423 while((ent = readdir(d)) != NULL) {
424 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Glenn Kasten0512ab52011-05-04 17:58:57 -0700425 snprintf(buffer, SIZE, "/proc/%d/fd/%s", gettid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800426 struct stat s;
427 if (lstat(buffer, &s) == 0) {
428 if ((s.st_mode & S_IFMT) == S_IFLNK) {
429 char linkto[256];
430 int len = readlink(buffer, linkto, sizeof(linkto));
431 if(len > 0) {
432 if(len > 255) {
433 linkto[252] = '.';
434 linkto[253] = '.';
435 linkto[254] = '.';
436 linkto[255] = 0;
437 } else {
438 linkto[len] = 0;
439 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700440 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800441 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700442 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443 strstr(linkto, "/system/media/") == linkto) {
444 result.append(" ");
445 result.append(buffer);
446 result.append(" -> ");
447 result.append(linkto);
448 result.append("\n");
449 }
450 }
451 } else {
452 result.append(" unexpected type for ");
453 result.append(buffer);
454 result.append("\n");
455 }
456 }
457 }
458 }
459 closedir(d);
460 } else {
461 result.append("couldn't open ");
462 result.append(buffer);
463 result.append("\n");
464 }
465
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 bool dumpMem = false;
467 for (size_t i = 0; i < args.size(); i++) {
468 if (args[i] == String16("-m")) {
469 dumpMem = true;
470 }
471 }
472 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700473 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 }
476 write(fd, result.string(), result.size());
477 return NO_ERROR;
478}
479
480void MediaPlayerService::removeClient(wp<Client> client)
481{
482 Mutex::Autolock lock(mLock);
483 mClients.remove(client);
484}
485
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700486MediaPlayerService::Client::Client(
487 const sp<MediaPlayerService>& service, pid_t pid,
488 int32_t connId, const sp<IMediaPlayerClient>& client,
489 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490{
Steve Block3856b092011-10-20 11:56:00 +0100491 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 mPid = pid;
493 mConnId = connId;
494 mService = service;
495 mClient = client;
496 mLoop = false;
497 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700498 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700499 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800500 mRetransmitEndpointValid = false;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700501
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000503 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800504 mAntagonizer = new Antagonizer(notify, this);
505#endif
506}
507
508MediaPlayerService::Client::~Client()
509{
Steve Block3856b092011-10-20 11:56:00 +0100510 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800511 mAudioOutput.clear();
512 wp<Client> client(this);
513 disconnect();
514 mService->removeClient(client);
515}
516
517void MediaPlayerService::Client::disconnect()
518{
Steve Block3856b092011-10-20 11:56:00 +0100519 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800520 // grab local reference and clear main reference to prevent future
521 // access to object
522 sp<MediaPlayerBase> p;
523 {
524 Mutex::Autolock l(mLock);
525 p = mPlayer;
526 }
Dave Sparks795fa582009-03-24 17:57:12 -0700527 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700528
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 mPlayer.clear();
530
531 // clear the notification to prevent callbacks to dead client
532 // and reset the player. We assume the player will serialize
533 // access to itself if necessary.
534 if (p != 0) {
535 p->setNotifyCallback(0, 0);
536#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000537 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538 mAntagonizer->kill();
539#endif
540 p->reset();
541 }
542
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700543 disconnectNativeWindow();
544
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800545 IPCThreadState::self()->flushCommands();
546}
547
Andreas Huber47f59cf2009-08-07 09:30:32 -0700548static player_type getDefaultPlayerType() {
Andreas Huberafed0e12011-09-20 15:39:58 -0700549 char value[PROPERTY_VALUE_MAX];
550 if (property_get("media.stagefright.use-nuplayer", value, NULL)
551 && (!strcmp("1", value) || !strcasecmp("true", value))) {
552 return NU_PLAYER;
553 }
554
Andreas Huber608d77b2010-06-23 16:40:57 -0700555 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700556}
557
James Dong148c1a22009-09-06 14:29:45 -0700558player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800559{
560 char buf[20];
561 lseek(fd, offset, SEEK_SET);
562 read(fd, buf, sizeof(buf));
563 lseek(fd, offset, SEEK_SET);
564
565 long ident = *((long*)buf);
566
567 // Ogg vorbis?
568 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700569 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800570
571 // Some kind of MIDI?
572 EAS_DATA_HANDLE easdata;
573 if (EAS_Init(&easdata) == EAS_SUCCESS) {
574 EAS_FILE locator;
575 locator.path = NULL;
576 locator.fd = fd;
577 locator.offset = offset;
578 locator.length = length;
579 EAS_HANDLE eashandle;
580 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
581 EAS_CloseFile(easdata, eashandle);
582 EAS_Shutdown(easdata);
583 return SONIVOX_PLAYER;
584 }
585 EAS_Shutdown(easdata);
586 }
587
Andreas Huber47f59cf2009-08-07 09:30:32 -0700588 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800589}
590
James Dong148c1a22009-09-06 14:29:45 -0700591player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592{
Nicolas Catania14d27472009-07-13 14:37:49 -0700593 if (TestPlayerStub::canBeUsed(url)) {
594 return TEST_PLAYER;
595 }
596
Andreas Huber0a73d812011-03-21 16:28:04 -0700597 if (!strncasecmp("http://", url, 7)
598 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-02-16 09:05:38 -0800599 size_t len = strlen(url);
600 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
601 return NU_PLAYER;
602 }
Andreas Huber5bc087c2010-12-23 10:27:40 -0800603
Andreas Hubered8d14f2011-02-16 09:05:38 -0800604 if (strstr(url,"m3u8")) {
605 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800606 }
607 }
608
Andreas Huber2bfdd422011-10-11 15:24:07 -0700609 if (!strncasecmp("rtsp://", url, 7)) {
610 return NU_PLAYER;
611 }
612
John Grossman761defc2012-02-09 15:09:05 -0800613 if (!strncasecmp("aahRX://", url, 8)) {
614 return AAH_RX_PLAYER;
615 }
616
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 // use MidiFile for MIDI extensions
618 int lenURL = strlen(url);
619 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
620 int len = strlen(FILE_EXTS[i].extension);
621 int start = lenURL - len;
622 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900623 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700624 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625 }
626 }
627 }
628
Andreas Huber47f59cf2009-08-07 09:30:32 -0700629 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630}
631
John Grossmanc795b642012-02-22 15:38:35 -0800632player_type MediaPlayerService::Client::getPlayerType(int fd,
633 int64_t offset,
634 int64_t length)
635{
636 // Until re-transmit functionality is added to the existing core android
637 // players, we use the special AAH TX player whenever we were configured
638 // for retransmission.
639 if (mRetransmitEndpointValid) {
640 return AAH_TX_PLAYER;
641 }
642
643 return android::getPlayerType(fd, offset, length);
644}
645
646player_type MediaPlayerService::Client::getPlayerType(const char* url)
647{
648 // Until re-transmit functionality is added to the existing core android
649 // players, we use the special AAH TX player whenever we were configured
650 // for retransmission.
651 if (mRetransmitEndpointValid) {
652 return AAH_TX_PLAYER;
653 }
654
655 return android::getPlayerType(url);
656}
657
658player_type MediaPlayerService::Client::getPlayerType(
659 const sp<IStreamSource> &source) {
660 // Until re-transmit functionality is added to the existing core android
661 // players, we use the special AAH TX player whenever we were configured
662 // for retransmission.
663 if (mRetransmitEndpointValid) {
664 return AAH_TX_PLAYER;
665 }
666
667 return NU_PLAYER;
668}
669
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
671 notify_callback_f notifyFunc)
672{
673 sp<MediaPlayerBase> p;
674 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800675 case SONIVOX_PLAYER:
Steve Block3856b092011-10-20 11:56:00 +0100676 ALOGV(" create MidiFile");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800677 p = new MidiFile();
678 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700679 case STAGEFRIGHT_PLAYER:
Steve Block3856b092011-10-20 11:56:00 +0100680 ALOGV(" create StagefrightPlayer");
Andreas Huber20111aa2009-07-14 16:56:47 -0700681 p = new StagefrightPlayer;
682 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800683 case NU_PLAYER:
Steve Block3856b092011-10-20 11:56:00 +0100684 ALOGV(" create NuPlayer");
Andreas Huberf9334412010-12-15 15:17:42 -0800685 p = new NuPlayerDriver;
686 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700687 case TEST_PLAYER:
Steve Block3856b092011-10-20 11:56:00 +0100688 ALOGV("Create Test Player stub");
Nicolas Catania14d27472009-07-13 14:37:49 -0700689 p = new TestPlayerStub();
690 break;
John Grossman761defc2012-02-09 15:09:05 -0800691 case AAH_RX_PLAYER:
692 ALOGV(" create A@H RX Player");
693 p = createAAH_RXPlayer();
694 break;
695 case AAH_TX_PLAYER:
696 ALOGV(" create A@H TX Player");
697 p = createAAH_TXPlayer();
698 break;
James Dong30d713a2010-11-10 18:42:40 -0800699 default:
Steve Block29357bc2012-01-06 19:20:56 +0000700 ALOGE("Unknown player type: %d", playerType);
James Dong30d713a2010-11-10 18:42:40 -0800701 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800702 }
703 if (p != NULL) {
704 if (p->initCheck() == NO_ERROR) {
705 p->setNotifyCallback(cookie, notifyFunc);
706 } else {
707 p.clear();
708 }
709 }
710 if (p == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000711 ALOGE("Failed to create player object");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800712 }
713 return p;
714}
715
716sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
717{
718 // determine if we have the right player type
719 sp<MediaPlayerBase> p = mPlayer;
720 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100721 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 p.clear();
723 }
724 if (p == NULL) {
725 p = android::createPlayer(playerType, this, notify);
726 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700727
Jason Simmonsdb29e522011-08-12 13:46:55 -0700728 if (p != NULL) {
729 p->setUID(mUID);
730 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700731
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800732 return p;
733}
734
John Grossmanc795b642012-02-22 15:38:35 -0800735sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
736 player_type playerType)
737{
738 ALOGV("player type = %d", playerType);
739
740 // create the right type of player
741 sp<MediaPlayerBase> p = createPlayer(playerType);
742 if (p == NULL) {
743 return p;
744 }
745
746 if (!p->hardwareOutput()) {
747 mAudioOutput = new AudioOutput(mAudioSessionId);
748 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
749 }
750
751 return p;
752}
753
754void MediaPlayerService::Client::setDataSource_post(
755 const sp<MediaPlayerBase>& p,
756 status_t status)
757{
758 ALOGV(" setDataSource");
759 mStatus = status;
760 if (mStatus != OK) {
761 ALOGE(" error: %d", mStatus);
762 return;
763 }
764
765 // Set the re-transmission endpoint if one was chosen.
766 if (mRetransmitEndpointValid) {
767 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
768 if (mStatus != NO_ERROR) {
769 ALOGE("setRetransmitEndpoint error: %d", mStatus);
770 }
771 }
772
773 if (mStatus == OK) {
774 mPlayer = p;
775 }
776}
777
Andreas Huber2db84552010-01-28 11:19:57 -0800778status_t MediaPlayerService::Client::setDataSource(
779 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780{
Steve Block3856b092011-10-20 11:56:00 +0100781 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782 if (url == NULL)
783 return UNKNOWN_ERROR;
784
Dave Burked681bbb2011-08-30 14:39:17 +0100785 if ((strncmp(url, "http://", 7) == 0) ||
786 (strncmp(url, "https://", 8) == 0) ||
787 (strncmp(url, "rtsp://", 7) == 0)) {
788 if (!checkPermission("android.permission.INTERNET")) {
789 return PERMISSION_DENIED;
790 }
791 }
792
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793 if (strncmp(url, "content://", 10) == 0) {
794 // get a filedescriptor for the content Uri and
795 // pass it to the setDataSource(fd) method
796
797 String16 url16(url);
798 int fd = android::openContentProviderFile(url16);
799 if (fd < 0)
800 {
Steve Block29357bc2012-01-06 19:20:56 +0000801 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802 return UNKNOWN_ERROR;
803 }
804 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
805 close(fd);
806 return mStatus;
807 } else {
808 player_type playerType = getPlayerType(url);
John Grossmanc795b642012-02-22 15:38:35 -0800809 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
810 if (p == NULL) {
811 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 }
813
John Grossmanc795b642012-02-22 15:38:35 -0800814 setDataSource_post(p, p->setDataSource(url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815 return mStatus;
816 }
817}
818
819status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
820{
Steve Block3856b092011-10-20 11:56:00 +0100821 ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800822 struct stat sb;
823 int ret = fstat(fd, &sb);
824 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000825 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 return UNKNOWN_ERROR;
827 }
828
Steve Block3856b092011-10-20 11:56:00 +0100829 ALOGV("st_dev = %llu", sb.st_dev);
830 ALOGV("st_mode = %u", sb.st_mode);
831 ALOGV("st_uid = %lu", sb.st_uid);
832 ALOGV("st_gid = %lu", sb.st_gid);
833 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834
835 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000836 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800837 ::close(fd);
838 return UNKNOWN_ERROR;
839 }
840 if (offset + length > sb.st_size) {
841 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100842 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800843 }
844
John Grossmanc795b642012-02-22 15:38:35 -0800845 // Until re-transmit functionality is added to the existing core android
846 // players, we use the special AAH TX player whenever we were configured for
847 // retransmission.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800848 player_type playerType = getPlayerType(fd, offset, length);
John Grossmanc795b642012-02-22 15:38:35 -0800849 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
850 if (p == NULL) {
851 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800852 }
853
854 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800855 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800856 return mStatus;
857}
858
Andreas Hubere2b10282010-11-23 11:41:34 -0800859status_t MediaPlayerService::Client::setDataSource(
860 const sp<IStreamSource> &source) {
861 // create the right type of player
John Grossmanc795b642012-02-22 15:38:35 -0800862 // Until re-transmit functionality is added to the existing core android
863 // players, we use the special AAH TX player whenever we were configured for
864 // retransmission.
865 player_type playerType = getPlayerType(source);
866 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800867 if (p == NULL) {
868 return NO_INIT;
869 }
870
Andreas Hubere2b10282010-11-23 11:41:34 -0800871 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800872 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800873 return mStatus;
874}
875
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700876void MediaPlayerService::Client::disconnectNativeWindow() {
877 if (mConnectedWindow != NULL) {
878 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
879 NATIVE_WINDOW_API_MEDIA);
880
881 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000882 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700883 strerror(-err), err);
884 }
885 }
886 mConnectedWindow.clear();
887}
888
Glenn Kasten11731182011-02-08 17:26:17 -0800889status_t MediaPlayerService::Client::setVideoSurfaceTexture(
890 const sp<ISurfaceTexture>& surfaceTexture)
891{
Steve Block3856b092011-10-20 11:56:00 +0100892 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800893 sp<MediaPlayerBase> p = getPlayer();
894 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700895
896 sp<IBinder> binder(surfaceTexture == NULL ? NULL :
897 surfaceTexture->asBinder());
898 if (mConnectedWindowBinder == binder) {
899 return OK;
900 }
901
902 sp<ANativeWindow> anw;
903 if (surfaceTexture != NULL) {
904 anw = new SurfaceTextureClient(surfaceTexture);
905 status_t err = native_window_api_connect(anw.get(),
906 NATIVE_WINDOW_API_MEDIA);
907
908 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000909 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700910 // Note that we must do the reset before disconnecting from the ANW.
911 // Otherwise queue/dequeue calls could be made on the disconnected
912 // ANW, which may result in errors.
913 reset();
914
915 disconnectNativeWindow();
916
917 return err;
918 }
919 }
920
921 // Note that we must set the player's new SurfaceTexture before
922 // disconnecting the old one. Otherwise queue/dequeue calls could be made
923 // on the disconnected ANW, which may result in errors.
924 status_t err = p->setVideoSurfaceTexture(surfaceTexture);
925
926 disconnectNativeWindow();
927
928 mConnectedWindow = anw;
929
930 if (err == OK) {
931 mConnectedWindowBinder = binder;
932 } else {
933 disconnectNativeWindow();
934 }
935
936 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800937}
938
Nicolas Catania1d187f12009-05-12 23:25:55 -0700939status_t MediaPlayerService::Client::invoke(const Parcel& request,
940 Parcel *reply)
941{
942 sp<MediaPlayerBase> p = getPlayer();
943 if (p == NULL) return UNKNOWN_ERROR;
944 return p->invoke(request, reply);
945}
946
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700947// This call doesn't need to access the native player.
948status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
949{
950 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700951 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700952
Nicolas Catania48290382009-07-10 13:53:06 -0700953 if (unmarshallFilter(filter, &allow, &status) &&
954 unmarshallFilter(filter, &drop, &status)) {
955 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700956
957 mMetadataAllow = allow;
958 mMetadataDrop = drop;
959 }
960 return status;
961}
962
Nicolas Catania48290382009-07-10 13:53:06 -0700963status_t MediaPlayerService::Client::getMetadata(
964 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700965{
nikoa64c8c72009-07-20 15:07:26 -0700966 sp<MediaPlayerBase> player = getPlayer();
967 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700968
nikod608a812009-07-16 16:39:53 -0700969 status_t status;
970 // Placeholder for the return code, updated by the caller.
971 reply->writeInt32(-1);
972
nikoa64c8c72009-07-20 15:07:26 -0700973 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700974
975 // We don't block notifications while we fetch the data. We clear
976 // mMetadataUpdated first so we don't lose notifications happening
977 // during the rest of this call.
978 {
979 Mutex::Autolock lock(mLock);
980 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700981 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700982 }
983 mMetadataUpdated.clear();
984 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700985
nikoa64c8c72009-07-20 15:07:26 -0700986 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700987
nikoa64c8c72009-07-20 15:07:26 -0700988 metadata.appendHeader();
989 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700990
991 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700992 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000993 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700994 return status;
995 }
996
997 // FIXME: Implement filtering on the result. Not critical since
998 // filtering takes place on the update notifications already. This
999 // would be when all the metadata are fetch and a filter is set.
1000
nikod608a812009-07-16 16:39:53 -07001001 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001002 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001003 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001004}
1005
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006status_t MediaPlayerService::Client::prepareAsync()
1007{
Steve Block3856b092011-10-20 11:56:00 +01001008 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001009 sp<MediaPlayerBase> p = getPlayer();
1010 if (p == 0) return UNKNOWN_ERROR;
1011 status_t ret = p->prepareAsync();
1012#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001013 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001014 if (ret == NO_ERROR) mAntagonizer->start();
1015#endif
1016 return ret;
1017}
1018
1019status_t MediaPlayerService::Client::start()
1020{
Steve Block3856b092011-10-20 11:56:00 +01001021 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022 sp<MediaPlayerBase> p = getPlayer();
1023 if (p == 0) return UNKNOWN_ERROR;
1024 p->setLooping(mLoop);
1025 return p->start();
1026}
1027
1028status_t MediaPlayerService::Client::stop()
1029{
Steve Block3856b092011-10-20 11:56:00 +01001030 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001031 sp<MediaPlayerBase> p = getPlayer();
1032 if (p == 0) return UNKNOWN_ERROR;
1033 return p->stop();
1034}
1035
1036status_t MediaPlayerService::Client::pause()
1037{
Steve Block3856b092011-10-20 11:56:00 +01001038 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001039 sp<MediaPlayerBase> p = getPlayer();
1040 if (p == 0) return UNKNOWN_ERROR;
1041 return p->pause();
1042}
1043
1044status_t MediaPlayerService::Client::isPlaying(bool* state)
1045{
1046 *state = false;
1047 sp<MediaPlayerBase> p = getPlayer();
1048 if (p == 0) return UNKNOWN_ERROR;
1049 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001050 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001051 return NO_ERROR;
1052}
1053
1054status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1055{
Steve Block3856b092011-10-20 11:56:00 +01001056 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057 sp<MediaPlayerBase> p = getPlayer();
1058 if (p == 0) return UNKNOWN_ERROR;
1059 status_t ret = p->getCurrentPosition(msec);
1060 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001063 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001064 }
1065 return ret;
1066}
1067
1068status_t MediaPlayerService::Client::getDuration(int *msec)
1069{
Steve Block3856b092011-10-20 11:56:00 +01001070 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071 sp<MediaPlayerBase> p = getPlayer();
1072 if (p == 0) return UNKNOWN_ERROR;
1073 status_t ret = p->getDuration(msec);
1074 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001077 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001078 }
1079 return ret;
1080}
1081
Marco Nelissen6b74d672012-02-28 16:07:44 -08001082status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1083 ALOGV("setNextPlayer");
1084 Mutex::Autolock l(mLock);
1085 sp<Client> c = static_cast<Client*>(player.get());
1086 mNextClient = c;
1087 if (mAudioOutput != NULL && c != NULL) {
1088 mAudioOutput->setNextOutput(c->mAudioOutput);
1089 } else {
1090 ALOGE("no current audio output");
1091 }
1092 return OK;
1093}
1094
1095
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001096status_t MediaPlayerService::Client::seekTo(int msec)
1097{
Steve Block3856b092011-10-20 11:56:00 +01001098 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001099 sp<MediaPlayerBase> p = getPlayer();
1100 if (p == 0) return UNKNOWN_ERROR;
1101 return p->seekTo(msec);
1102}
1103
1104status_t MediaPlayerService::Client::reset()
1105{
Steve Block3856b092011-10-20 11:56:00 +01001106 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001107 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001108 sp<MediaPlayerBase> p = getPlayer();
1109 if (p == 0) return UNKNOWN_ERROR;
1110 return p->reset();
1111}
1112
Glenn Kastenfff6d712012-01-12 16:38:12 -08001113status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001114{
Steve Block3856b092011-10-20 11:56:00 +01001115 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001116 // TODO: for hardware output, call player instead
1117 Mutex::Autolock l(mLock);
1118 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1119 return NO_ERROR;
1120}
1121
1122status_t MediaPlayerService::Client::setLooping(int loop)
1123{
Steve Block3856b092011-10-20 11:56:00 +01001124 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001125 mLoop = loop;
1126 sp<MediaPlayerBase> p = getPlayer();
1127 if (p != 0) return p->setLooping(loop);
1128 return NO_ERROR;
1129}
1130
1131status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1132{
Steve Block3856b092011-10-20 11:56:00 +01001133 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001134
1135 // for hardware output, call player instead
1136 sp<MediaPlayerBase> p = getPlayer();
1137 {
1138 Mutex::Autolock l(mLock);
1139 if (p != 0 && p->hardwareOutput()) {
1140 MediaPlayerHWInterface* hwp =
1141 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1142 return hwp->setVolume(leftVolume, rightVolume);
1143 } else {
1144 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1145 return NO_ERROR;
1146 }
1147 }
1148
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001149 return NO_ERROR;
1150}
1151
Eric Laurent2beeb502010-07-16 07:43:46 -07001152status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1153{
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001155 Mutex::Autolock l(mLock);
1156 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1157 return NO_ERROR;
1158}
1159
1160status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1161{
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001163 Mutex::Autolock l(mLock);
1164 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1165 return NO_ERROR;
1166}
Nicolas Catania48290382009-07-10 13:53:06 -07001167
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001168status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("[%d] setParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001170 sp<MediaPlayerBase> p = getPlayer();
1171 if (p == 0) return UNKNOWN_ERROR;
1172 return p->setParameter(key, request);
1173}
1174
1175status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001176 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001177 sp<MediaPlayerBase> p = getPlayer();
1178 if (p == 0) return UNKNOWN_ERROR;
1179 return p->getParameter(key, reply);
1180}
1181
John Grossmanc795b642012-02-22 15:38:35 -08001182status_t MediaPlayerService::Client::setRetransmitEndpoint(
1183 const struct sockaddr_in* endpoint) {
1184
1185 if (NULL != endpoint) {
1186 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1187 uint16_t p = ntohs(endpoint->sin_port);
1188 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1189 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1190 } else {
1191 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1192 }
1193
1194 sp<MediaPlayerBase> p = getPlayer();
1195
1196 // Right now, the only valid time to set a retransmit endpoint is before
1197 // player selection has been made (since the presence or absence of a
1198 // retransmit endpoint is going to determine which player is selected during
1199 // setDataSource).
1200 if (p != 0) return INVALID_OPERATION;
1201
1202 if (NULL != endpoint) {
1203 mRetransmitEndpoint = *endpoint;
1204 mRetransmitEndpointValid = true;
1205 } else {
1206 mRetransmitEndpointValid = false;
1207 }
1208
1209 return NO_ERROR;
1210}
1211
Gloria Wangb483c472011-04-11 17:23:27 -07001212void MediaPlayerService::Client::notify(
1213 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001214{
1215 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001216
Marco Nelissen6b74d672012-02-28 16:07:44 -08001217 {
1218 Mutex::Autolock l(client->mLock);
1219 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1220 client->mAudioOutput->switchToNextOutput();
1221 client->mNextClient->start();
1222 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1223 }
1224 }
1225
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001226 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001227 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001228 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001229
1230 if(client->shouldDropMetadata(metadata_type)) {
1231 return;
1232 }
1233
1234 // Update the list of metadata that have changed. getMetadata
1235 // also access mMetadataUpdated and clears it.
1236 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001237 }
Steve Block3856b092011-10-20 11:56:00 +01001238 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001239 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240}
1241
Nicolas Catania48290382009-07-10 13:53:06 -07001242
nikoa64c8c72009-07-20 15:07:26 -07001243bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001244{
Nicolas Catania48290382009-07-10 13:53:06 -07001245 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001246
Nicolas Catania48290382009-07-10 13:53:06 -07001247 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001248 return true;
1249 }
1250
Nicolas Catania48290382009-07-10 13:53:06 -07001251 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001252 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001253 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001254 return true;
1255 }
1256}
1257
Nicolas Catania48290382009-07-10 13:53:06 -07001258
nikoa64c8c72009-07-20 15:07:26 -07001259void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001260 Mutex::Autolock lock(mLock);
1261 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1262 mMetadataUpdated.add(metadata_type);
1263 }
1264}
1265
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001266#if CALLBACK_ANTAGONIZER
1267const int Antagonizer::interval = 10000; // 10 msecs
1268
1269Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1270 mExit(false), mActive(false), mClient(client), mCb(cb)
1271{
1272 createThread(callbackThread, this);
1273}
1274
1275void Antagonizer::kill()
1276{
1277 Mutex::Autolock _l(mLock);
1278 mActive = false;
1279 mExit = true;
1280 mCondition.wait(mLock);
1281}
1282
1283int Antagonizer::callbackThread(void* user)
1284{
Steve Blockb8a80522011-12-20 16:23:08 +00001285 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001286 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1287 while (!p->mExit) {
1288 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001289 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001290 p->mCb(p->mClient, 0, 0, 0);
1291 }
1292 usleep(interval);
1293 }
1294 Mutex::Autolock _l(p->mLock);
1295 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001296 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001297 return 0;
1298}
1299#endif
1300
1301static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1302
Glenn Kastene1c39622012-01-04 09:36:37 -08001303sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001304{
Steve Block3856b092011-10-20 11:56:00 +01001305 ALOGV("decode(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306 sp<MemoryBase> mem;
1307 sp<MediaPlayerBase> player;
1308
1309 // Protect our precious, precious DRMd ringtones by only allowing
1310 // decoding of http, but not filesystem paths or content Uris.
1311 // If the application wants to decode those, it should open a
1312 // filedescriptor for them and use that.
1313 if (url != NULL && strncmp(url, "http://", 7) != 0) {
Steve Blockb8a80522011-12-20 16:23:08 +00001314 ALOGD("Can't decode %s by path, use filedescriptor instead", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 return mem;
1316 }
1317
1318 player_type playerType = getPlayerType(url);
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("player type = %d", playerType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320
1321 // create the right type of player
1322 sp<AudioCache> cache = new AudioCache(url);
1323 player = android::createPlayer(playerType, cache.get(), cache->notify);
1324 if (player == NULL) goto Exit;
1325 if (player->hardwareOutput()) goto Exit;
1326
1327 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1328
1329 // set data source
1330 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1331
Steve Block3856b092011-10-20 11:56:00 +01001332 ALOGV("prepare");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001333 player->prepareAsync();
1334
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("wait for prepare");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001336 if (cache->wait() != NO_ERROR) goto Exit;
1337
Steve Block3856b092011-10-20 11:56:00 +01001338 ALOGV("start");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001339 player->start();
1340
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001342 cache->wait();
1343 // in case of error, return what was successfully decoded.
1344 if (cache->size() == 0) {
1345 goto Exit;
1346 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001347
1348 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1349 *pSampleRate = cache->sampleRate();
1350 *pNumChannels = cache->channelCount();
Glenn Kastene1c39622012-01-04 09:36:37 -08001351 *pFormat = cache->format();
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001353
1354Exit:
1355 if (player != 0) player->reset();
1356 return mem;
1357}
1358
Glenn Kastene1c39622012-01-04 09:36:37 -08001359sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001360{
Steve Block3856b092011-10-20 11:56:00 +01001361 ALOGV("decode(%d, %lld, %lld)", fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001362 sp<MemoryBase> mem;
1363 sp<MediaPlayerBase> player;
1364
1365 player_type playerType = getPlayerType(fd, offset, length);
Steve Block3856b092011-10-20 11:56:00 +01001366 ALOGV("player type = %d", playerType);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001367
1368 // create the right type of player
1369 sp<AudioCache> cache = new AudioCache("decode_fd");
1370 player = android::createPlayer(playerType, cache.get(), cache->notify);
1371 if (player == NULL) goto Exit;
1372 if (player->hardwareOutput()) goto Exit;
1373
1374 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1375
1376 // set data source
1377 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1378
Steve Block3856b092011-10-20 11:56:00 +01001379 ALOGV("prepare");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380 player->prepareAsync();
1381
Steve Block3856b092011-10-20 11:56:00 +01001382 ALOGV("wait for prepare");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001383 if (cache->wait() != NO_ERROR) goto Exit;
1384
Steve Block3856b092011-10-20 11:56:00 +01001385 ALOGV("start");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001386 player->start();
1387
Steve Block3856b092011-10-20 11:56:00 +01001388 ALOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001389 cache->wait();
1390 // in case of error, return what was successfully decoded.
1391 if (cache->size() == 0) {
1392 goto Exit;
1393 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394
1395 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1396 *pSampleRate = cache->sampleRate();
1397 *pNumChannels = cache->channelCount();
1398 *pFormat = cache->format();
Steve Block3856b092011-10-20 11:56:00 +01001399 ALOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400
1401Exit:
1402 if (player != 0) player->reset();
1403 ::close(fd);
1404 return mem;
1405}
1406
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001407
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408#undef LOG_TAG
1409#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001410MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001411 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001412 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001413 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001414 mBytesWritten(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001415 mSessionId(sessionId),
1416 mFlags(AUDIO_OUTPUT_FLAG_NONE) {
Steve Block3856b092011-10-20 11:56:00 +01001417 ALOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418 mTrack = 0;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001419 mRecycledTrack = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -07001420 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421 mLeftVolume = 1.0;
1422 mRightVolume = 1.0;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001423 mPlaybackRatePermille = 1000;
1424 mSampleRateHz = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001426 mAuxEffectId = 0;
1427 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428 setMinBufferCount();
1429}
1430
1431MediaPlayerService::AudioOutput::~AudioOutput()
1432{
1433 close();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001434 delete mRecycledTrack;
1435 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436}
1437
1438void MediaPlayerService::AudioOutput::setMinBufferCount()
1439{
1440 char value[PROPERTY_VALUE_MAX];
1441 if (property_get("ro.kernel.qemu", value, 0)) {
1442 mIsOnEmulator = true;
1443 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1444 }
1445}
1446
1447bool MediaPlayerService::AudioOutput::isOnEmulator()
1448{
1449 setMinBufferCount();
1450 return mIsOnEmulator;
1451}
1452
1453int MediaPlayerService::AudioOutput::getMinBufferCount()
1454{
1455 setMinBufferCount();
1456 return mMinBufferCount;
1457}
1458
1459ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1460{
1461 if (mTrack == 0) return NO_INIT;
1462 return mTrack->frameCount() * frameSize();
1463}
1464
1465ssize_t MediaPlayerService::AudioOutput::frameCount() const
1466{
1467 if (mTrack == 0) return NO_INIT;
1468 return mTrack->frameCount();
1469}
1470
1471ssize_t MediaPlayerService::AudioOutput::channelCount() const
1472{
1473 if (mTrack == 0) return NO_INIT;
1474 return mTrack->channelCount();
1475}
1476
1477ssize_t MediaPlayerService::AudioOutput::frameSize() const
1478{
1479 if (mTrack == 0) return NO_INIT;
1480 return mTrack->frameSize();
1481}
1482
1483uint32_t MediaPlayerService::AudioOutput::latency () const
1484{
Eric Laurentdb354e52012-03-05 17:27:11 -08001485 if (mTrack == 0) return 0;
1486 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001487}
1488
1489float MediaPlayerService::AudioOutput::msecsPerFrame() const
1490{
1491 return mMsecsPerFrame;
1492}
1493
Marco Nelissen4110c102012-03-29 09:31:28 -07001494status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001495{
1496 if (mTrack == 0) return NO_INIT;
1497 return mTrack->getPosition(position);
1498}
1499
Marco Nelissen4110c102012-03-29 09:31:28 -07001500status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1501{
1502 if (mTrack == 0) return NO_INIT;
1503 *frameswritten = mBytesWritten / frameSize();
1504 return OK;
1505}
1506
Andreas Huber20111aa2009-07-14 16:56:47 -07001507status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001508 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1509 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001510 AudioCallback cb, void *cookie,
1511 audio_output_flags_t flags)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512{
Andreas Huber20111aa2009-07-14 16:56:47 -07001513 mCallback = cb;
1514 mCallbackCookie = cookie;
1515
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001516 // Check argument "bufferCount" against the mininum buffer count
1517 if (bufferCount < mMinBufferCount) {
Steve Blockb8a80522011-12-20 16:23:08 +00001518 ALOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001519 bufferCount = mMinBufferCount;
1520
1521 }
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001522 ALOGV("open(%u, %d, 0x%x, %d, %d, %d)", sampleRate, channelCount, channelMask,
1523 format, bufferCount, mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001524 int afSampleRate;
1525 int afFrameCount;
Eric Laurent1948eb32012-04-13 16:50:19 -07001526 uint32_t frameCount;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001527
1528 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1529 return NO_INIT;
1530 }
1531 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1532 return NO_INIT;
1533 }
1534
1535 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001536
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001537 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001538 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001539 if (0 == channelMask) {
1540 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1541 return NO_INIT;
1542 }
1543 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001544
Marco Nelissen6b74d672012-02-28 16:07:44 -08001545 if (mRecycledTrack) {
1546 // check if the existing track can be reused as-is, or if a new track needs to be created.
1547
1548 bool reuse = true;
1549 if ((mCallbackData == NULL && mCallback != NULL) ||
1550 (mCallbackData != NULL && mCallback == NULL)) {
1551 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1552 ALOGV("can't chain callback and write");
1553 reuse = false;
1554 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
1555 (mRecycledTrack->channelCount() != channelCount) ||
1556 (mRecycledTrack->frameCount() != frameCount)) {
1557 ALOGV("samplerate, channelcount or framecount differ");
1558 reuse = false;
Eric Laurent1948eb32012-04-13 16:50:19 -07001559 } if (flags != mFlags) {
1560 ALOGV("output flags differ");
1561 reuse = false;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001562 }
1563 if (reuse) {
1564 ALOGV("chaining to next output");
1565 close();
1566 mTrack = mRecycledTrack;
1567 mRecycledTrack = NULL;
1568 if (mCallbackData != NULL) {
1569 mCallbackData->setOutput(this);
1570 }
1571 return OK;
1572 }
1573
1574 // if we're not going to reuse the track, unblock and flush it
1575 if (mCallbackData != NULL) {
1576 mCallbackData->setOutput(NULL);
1577 mCallbackData->endTrackSwitch();
1578 }
1579 mRecycledTrack->flush();
1580 delete mRecycledTrack;
1581 mRecycledTrack = NULL;
1582 delete mCallbackData;
1583 mCallbackData = NULL;
1584 close();
1585 }
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001586
Andreas Huber20111aa2009-07-14 16:56:47 -07001587 AudioTrack *t;
1588 if (mCallback != NULL) {
Marco Nelissen6b74d672012-02-28 16:07:44 -08001589 mCallbackData = new CallbackData(this);
Andreas Huber20111aa2009-07-14 16:56:47 -07001590 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001591 mStreamType,
1592 sampleRate,
1593 format,
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001594 channelMask,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001595 frameCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001596 flags,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001597 CallbackWrapper,
Marco Nelissen6b74d672012-02-28 16:07:44 -08001598 mCallbackData,
Glenn Kasten17a736c2012-02-14 08:52:15 -08001599 0, // notification frames
Eric Laurenta514bdb2010-06-21 09:27:30 -07001600 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001601 } else {
1602 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001603 mStreamType,
1604 sampleRate,
1605 format,
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001606 channelMask,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001607 frameCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001608 flags,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001609 NULL,
1610 NULL,
1611 0,
1612 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001613 }
1614
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001615 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
Steve Block29357bc2012-01-06 19:20:56 +00001616 ALOGE("Unable to create audio track");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617 delete t;
1618 return NO_INIT;
1619 }
1620
Steve Block3856b092011-10-20 11:56:00 +01001621 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001622 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001623
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001624 mSampleRateHz = sampleRate;
Eric Laurent1948eb32012-04-13 16:50:19 -07001625 mFlags = flags;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001626 mMsecsPerFrame = mPlaybackRatePermille / (float) sampleRate;
Marco Nelissen99448602012-04-02 12:16:49 -07001627 uint32_t pos;
1628 if (t->getPosition(&pos) == OK) {
1629 mBytesWritten = uint64_t(pos) * t->frameSize();
1630 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001631 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001632
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001633 status_t res = t->setSampleRate(mPlaybackRatePermille * mSampleRateHz / 1000);
1634 if (res != NO_ERROR) {
1635 return res;
1636 }
Eric Laurent2beeb502010-07-16 07:43:46 -07001637 t->setAuxEffectSendLevel(mSendLevel);
1638 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639}
1640
1641void MediaPlayerService::AudioOutput::start()
1642{
Steve Block3856b092011-10-20 11:56:00 +01001643 ALOGV("start");
Marco Nelissen6b74d672012-02-28 16:07:44 -08001644 if (mCallbackData != NULL) {
1645 mCallbackData->endTrackSwitch();
1646 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001647 if (mTrack) {
1648 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001649 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650 mTrack->start();
1651 }
1652}
1653
Marco Nelissen6b74d672012-02-28 16:07:44 -08001654void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1655 mNextOutput = nextOutput;
1656}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001657
1658
Marco Nelissen6b74d672012-02-28 16:07:44 -08001659void MediaPlayerService::AudioOutput::switchToNextOutput() {
1660 ALOGV("switchToNextOutput");
1661 if (mNextOutput != NULL) {
1662 if (mCallbackData != NULL) {
1663 mCallbackData->beginTrackSwitch();
1664 }
1665 delete mNextOutput->mCallbackData;
1666 mNextOutput->mCallbackData = mCallbackData;
1667 mCallbackData = NULL;
1668 mNextOutput->mRecycledTrack = mTrack;
1669 mTrack = NULL;
1670 mNextOutput->mSampleRateHz = mSampleRateHz;
1671 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Marco Nelissen4110c102012-03-29 09:31:28 -07001672 mNextOutput->mBytesWritten = mBytesWritten;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001673 }
1674}
1675
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001676ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1677{
Andreas Huber20111aa2009-07-14 16:56:47 -07001678 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1679
Steve Block3856b092011-10-20 11:56:00 +01001680 //ALOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001681 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001682 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen4110c102012-03-29 09:31:28 -07001683 mBytesWritten += ret;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001684 return ret;
1685 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686 return NO_INIT;
1687}
1688
1689void MediaPlayerService::AudioOutput::stop()
1690{
Steve Block3856b092011-10-20 11:56:00 +01001691 ALOGV("stop");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001692 if (mTrack) mTrack->stop();
1693}
1694
1695void MediaPlayerService::AudioOutput::flush()
1696{
Steve Block3856b092011-10-20 11:56:00 +01001697 ALOGV("flush");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001698 if (mTrack) mTrack->flush();
1699}
1700
1701void MediaPlayerService::AudioOutput::pause()
1702{
Steve Block3856b092011-10-20 11:56:00 +01001703 ALOGV("pause");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001704 if (mTrack) mTrack->pause();
1705}
1706
1707void MediaPlayerService::AudioOutput::close()
1708{
Steve Block3856b092011-10-20 11:56:00 +01001709 ALOGV("close");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001710 delete mTrack;
1711 mTrack = 0;
1712}
1713
1714void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1715{
Steve Block3856b092011-10-20 11:56:00 +01001716 ALOGV("setVolume(%f, %f)", left, right);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001717 mLeftVolume = left;
1718 mRightVolume = right;
1719 if (mTrack) {
1720 mTrack->setVolume(left, right);
1721 }
1722}
1723
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001724status_t MediaPlayerService::AudioOutput::setPlaybackRatePermille(int32_t ratePermille)
1725{
1726 ALOGV("setPlaybackRatePermille(%d)", ratePermille);
1727 status_t res = NO_ERROR;
1728 if (mTrack) {
1729 res = mTrack->setSampleRate(ratePermille * mSampleRateHz / 1000);
1730 } else {
1731 res = NO_INIT;
1732 }
1733 mPlaybackRatePermille = ratePermille;
1734 if (mSampleRateHz != 0) {
1735 mMsecsPerFrame = mPlaybackRatePermille / (float) mSampleRateHz;
1736 }
1737 return res;
1738}
1739
Eric Laurent2beeb502010-07-16 07:43:46 -07001740status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1741{
Steve Block3856b092011-10-20 11:56:00 +01001742 ALOGV("setAuxEffectSendLevel(%f)", level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001743 mSendLevel = level;
1744 if (mTrack) {
1745 return mTrack->setAuxEffectSendLevel(level);
1746 }
1747 return NO_ERROR;
1748}
1749
1750status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1751{
Steve Block3856b092011-10-20 11:56:00 +01001752 ALOGV("attachAuxEffect(%d)", effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001753 mAuxEffectId = effectId;
1754 if (mTrack) {
1755 return mTrack->attachAuxEffect(effectId);
1756 }
1757 return NO_ERROR;
1758}
1759
Andreas Huber20111aa2009-07-14 16:56:47 -07001760// static
1761void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001762 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01001763 //ALOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001764 if (event != AudioTrack::EVENT_MORE_DATA) {
1765 return;
1766 }
1767
Marco Nelissen6b74d672012-02-28 16:07:44 -08001768 CallbackData *data = (CallbackData*)cookie;
1769 data->lock();
1770 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07001771 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001772 if (me == NULL) {
1773 // no output set, likely because the track was scheduled to be reused
1774 // by another player, but the format turned out to be incompatible.
1775 data->unlock();
1776 buffer->size = 0;
1777 return;
1778 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001779
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001780 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001781 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001782
Marco Nelissen6b74d672012-02-28 16:07:44 -08001783 if (actualSize == 0 && buffer->size > 0 && me->mNextOutput == NULL) {
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001784 // We've reached EOS but the audio track is not stopped yet,
1785 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001786
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001787 memset(buffer->raw, 0, buffer->size);
1788 actualSize = buffer->size;
1789 }
1790
1791 buffer->size = actualSize;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001792 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07001793}
1794
Marco Nelissen4110c102012-03-29 09:31:28 -07001795int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07001796{
1797 return mSessionId;
1798}
1799
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800#undef LOG_TAG
1801#define LOG_TAG "AudioCache"
1802MediaPlayerService::AudioCache::AudioCache(const char* name) :
1803 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1804 mError(NO_ERROR), mCommandComplete(false)
1805{
1806 // create ashmem heap
1807 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1808}
1809
1810uint32_t MediaPlayerService::AudioCache::latency () const
1811{
1812 return 0;
1813}
1814
1815float MediaPlayerService::AudioCache::msecsPerFrame() const
1816{
1817 return mMsecsPerFrame;
1818}
1819
Marco Nelissen4110c102012-03-29 09:31:28 -07001820status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001821{
1822 if (position == 0) return BAD_VALUE;
1823 *position = mSize;
1824 return NO_ERROR;
1825}
1826
Marco Nelissen4110c102012-03-29 09:31:28 -07001827status_t MediaPlayerService::AudioCache::getFramesWritten(uint32_t *written) const
1828{
1829 if (written == 0) return BAD_VALUE;
1830 *written = mSize;
1831 return NO_ERROR;
1832}
1833
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001834////////////////////////////////////////////////////////////////////////////////
1835
1836struct CallbackThread : public Thread {
1837 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1838 MediaPlayerBase::AudioSink::AudioCallback cb,
1839 void *cookie);
1840
1841protected:
1842 virtual ~CallbackThread();
1843
1844 virtual bool threadLoop();
1845
1846private:
1847 wp<MediaPlayerBase::AudioSink> mSink;
1848 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1849 void *mCookie;
1850 void *mBuffer;
1851 size_t mBufferSize;
1852
1853 CallbackThread(const CallbackThread &);
1854 CallbackThread &operator=(const CallbackThread &);
1855};
1856
1857CallbackThread::CallbackThread(
1858 const wp<MediaPlayerBase::AudioSink> &sink,
1859 MediaPlayerBase::AudioSink::AudioCallback cb,
1860 void *cookie)
1861 : mSink(sink),
1862 mCallback(cb),
1863 mCookie(cookie),
1864 mBuffer(NULL),
1865 mBufferSize(0) {
1866}
1867
1868CallbackThread::~CallbackThread() {
1869 if (mBuffer) {
1870 free(mBuffer);
1871 mBuffer = NULL;
1872 }
1873}
1874
1875bool CallbackThread::threadLoop() {
1876 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1877 if (sink == NULL) {
1878 return false;
1879 }
1880
1881 if (mBuffer == NULL) {
1882 mBufferSize = sink->bufferSize();
1883 mBuffer = malloc(mBufferSize);
1884 }
1885
1886 size_t actualSize =
1887 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1888
1889 if (actualSize > 0) {
1890 sink->write(mBuffer, actualSize);
1891 }
1892
1893 return true;
1894}
1895
1896////////////////////////////////////////////////////////////////////////////////
1897
Andreas Huber20111aa2009-07-14 16:56:47 -07001898status_t MediaPlayerService::AudioCache::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001899 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1900 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001901 AudioCallback cb, void *cookie, audio_output_flags_t flags)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001902{
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001903 ALOGV("open(%u, %d, 0x%x, %d, %d)", sampleRate, channelCount, channelMask, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001904 if (mHeap->getHeapID() < 0) {
1905 return NO_INIT;
1906 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001907
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001908 mSampleRate = sampleRate;
1909 mChannelCount = (uint16_t)channelCount;
Glenn Kastene1c39622012-01-04 09:36:37 -08001910 mFormat = format;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001911 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001912
1913 if (cb != NULL) {
1914 mCallbackThread = new CallbackThread(this, cb, cookie);
1915 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001916 return NO_ERROR;
1917}
1918
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001919void MediaPlayerService::AudioCache::start() {
1920 if (mCallbackThread != NULL) {
1921 mCallbackThread->run("AudioCache callback");
1922 }
1923}
1924
1925void MediaPlayerService::AudioCache::stop() {
1926 if (mCallbackThread != NULL) {
1927 mCallbackThread->requestExitAndWait();
1928 }
1929}
1930
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001931ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1932{
Steve Block3856b092011-10-20 11:56:00 +01001933 ALOGV("write(%p, %u)", buffer, size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001934 if ((buffer == 0) || (size == 0)) return size;
1935
1936 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1937 if (p == NULL) return NO_INIT;
1938 p += mSize;
Steve Block3856b092011-10-20 11:56:00 +01001939 ALOGV("memcpy(%p, %p, %u)", p, buffer, size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001940 if (mSize + size > mHeap->getSize()) {
Steve Block29357bc2012-01-06 19:20:56 +00001941 ALOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001942 size = mHeap->getSize() - mSize;
1943 }
1944 memcpy(p, buffer, size);
1945 mSize += size;
1946 return size;
1947}
1948
1949// call with lock held
1950status_t MediaPlayerService::AudioCache::wait()
1951{
1952 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001953 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001954 mSignal.wait(mLock);
1955 }
1956 mCommandComplete = false;
1957
1958 if (mError == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001959 ALOGV("wait - success");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001960 } else {
Steve Block3856b092011-10-20 11:56:00 +01001961 ALOGV("wait - error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001962 }
1963 return mError;
1964}
1965
Gloria Wangb483c472011-04-11 17:23:27 -07001966void MediaPlayerService::AudioCache::notify(
1967 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001968{
Steve Block3856b092011-10-20 11:56:00 +01001969 ALOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001970 AudioCache* p = static_cast<AudioCache*>(cookie);
1971
1972 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001973 switch (msg)
1974 {
1975 case MEDIA_ERROR:
Steve Block29357bc2012-01-06 19:20:56 +00001976 ALOGE("Error %d, %d occurred", ext1, ext2);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001977 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001978 break;
1979 case MEDIA_PREPARED:
Steve Block3856b092011-10-20 11:56:00 +01001980 ALOGV("prepared");
Dave Sparks8eb80112009-12-09 20:20:26 -08001981 break;
1982 case MEDIA_PLAYBACK_COMPLETE:
Steve Block3856b092011-10-20 11:56:00 +01001983 ALOGV("playback complete");
Dave Sparks8eb80112009-12-09 20:20:26 -08001984 break;
1985 default:
Steve Block3856b092011-10-20 11:56:00 +01001986 ALOGV("ignored");
Dave Sparks8eb80112009-12-09 20:20:26 -08001987 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001988 }
1989
1990 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001991 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001992 p->mCommandComplete = true;
1993 p->mSignal.signal();
1994}
1995
Marco Nelissen4110c102012-03-29 09:31:28 -07001996int MediaPlayerService::AudioCache::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07001997{
1998 return 0;
1999}
2000
Gloria Wang7cf180c2011-02-19 18:37:57 -08002001void MediaPlayerService::addBatteryData(uint32_t params)
2002{
2003 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002004
2005 int32_t time = systemTime() / 1000000L;
2006
2007 // change audio output devices. This notification comes from AudioFlinger
2008 if ((params & kBatteryDataSpeakerOn)
2009 || (params & kBatteryDataOtherAudioDeviceOn)) {
2010
2011 int deviceOn[NUM_AUDIO_DEVICES];
2012 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2013 deviceOn[i] = 0;
2014 }
2015
2016 if ((params & kBatteryDataSpeakerOn)
2017 && (params & kBatteryDataOtherAudioDeviceOn)) {
2018 deviceOn[SPEAKER_AND_OTHER] = 1;
2019 } else if (params & kBatteryDataSpeakerOn) {
2020 deviceOn[SPEAKER] = 1;
2021 } else {
2022 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2023 }
2024
2025 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2026 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2027
2028 if (mBatteryAudio.refCount > 0) { // if playing audio
2029 if (!deviceOn[i]) {
2030 mBatteryAudio.lastTime[i] += time;
2031 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2032 mBatteryAudio.lastTime[i] = 0;
2033 } else {
2034 mBatteryAudio.lastTime[i] = 0 - time;
2035 }
2036 }
2037
2038 mBatteryAudio.deviceOn[i] = deviceOn[i];
2039 }
2040 }
2041 return;
2042 }
2043
2044 // an sudio stream is started
2045 if (params & kBatteryDataAudioFlingerStart) {
2046 // record the start time only if currently no other audio
2047 // is being played
2048 if (mBatteryAudio.refCount == 0) {
2049 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2050 if (mBatteryAudio.deviceOn[i]) {
2051 mBatteryAudio.lastTime[i] -= time;
2052 }
2053 }
2054 }
2055
2056 mBatteryAudio.refCount ++;
2057 return;
2058
2059 } else if (params & kBatteryDataAudioFlingerStop) {
2060 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002061 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002062 return;
2063 }
2064
2065 // record the stop time only if currently this is the only
2066 // audio being played
2067 if (mBatteryAudio.refCount == 1) {
2068 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2069 if (mBatteryAudio.deviceOn[i]) {
2070 mBatteryAudio.lastTime[i] += time;
2071 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2072 mBatteryAudio.lastTime[i] = 0;
2073 }
2074 }
2075 }
2076
2077 mBatteryAudio.refCount --;
2078 return;
2079 }
2080
Gloria Wang7cf180c2011-02-19 18:37:57 -08002081 int uid = IPCThreadState::self()->getCallingUid();
2082 if (uid == AID_MEDIA) {
2083 return;
2084 }
2085 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002086
2087 if (index < 0) { // create a new entry for this UID
2088 BatteryUsageInfo info;
2089 info.audioTotalTime = 0;
2090 info.videoTotalTime = 0;
2091 info.audioLastTime = 0;
2092 info.videoLastTime = 0;
2093 info.refCount = 0;
2094
Gloria Wang9ee159b2011-02-24 14:51:45 -08002095 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002096 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002097 return;
2098 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002099 }
2100
2101 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2102
2103 if (params & kBatteryDataCodecStarted) {
2104 if (params & kBatteryDataTrackAudio) {
2105 info.audioLastTime -= time;
2106 info.refCount ++;
2107 }
2108 if (params & kBatteryDataTrackVideo) {
2109 info.videoLastTime -= time;
2110 info.refCount ++;
2111 }
2112 } else {
2113 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002114 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002115 return;
2116 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002117 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002118 mBatteryData.removeItem(uid);
2119 return;
2120 }
2121
2122 if (params & kBatteryDataTrackAudio) {
2123 info.audioLastTime += time;
2124 info.refCount --;
2125 }
2126 if (params & kBatteryDataTrackVideo) {
2127 info.videoLastTime += time;
2128 info.refCount --;
2129 }
2130
2131 // no stream is being played by this UID
2132 if (info.refCount == 0) {
2133 info.audioTotalTime += info.audioLastTime;
2134 info.audioLastTime = 0;
2135 info.videoTotalTime += info.videoLastTime;
2136 info.videoLastTime = 0;
2137 }
2138 }
2139}
2140
2141status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2142 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002143
2144 // audio output devices usage
2145 int32_t time = systemTime() / 1000000L; //in ms
2146 int32_t totalTime;
2147
2148 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2149 totalTime = mBatteryAudio.totalTime[i];
2150
2151 if (mBatteryAudio.deviceOn[i]
2152 && (mBatteryAudio.lastTime[i] != 0)) {
2153 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2154 totalTime += tmpTime;
2155 }
2156
2157 reply->writeInt32(totalTime);
2158 // reset the total time
2159 mBatteryAudio.totalTime[i] = 0;
2160 }
2161
2162 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002163 BatteryUsageInfo info;
2164 int size = mBatteryData.size();
2165
2166 reply->writeInt32(size);
2167 int i = 0;
2168
2169 while (i < size) {
2170 info = mBatteryData.valueAt(i);
2171
2172 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2173 reply->writeInt32(info.audioTotalTime);
2174 reply->writeInt32(info.videoTotalTime);
2175
2176 info.audioTotalTime = 0;
2177 info.videoTotalTime = 0;
2178
2179 // remove the UID entry where no stream is being played
2180 if (info.refCount <= 0) {
2181 mBatteryData.removeItemsAt(i);
2182 size --;
2183 i --;
2184 }
2185 i++;
2186 }
2187 return NO_ERROR;
2188}
nikoa64c8c72009-07-20 15:07:26 -07002189} // namespace android