blob: 3b0508542cb66468a271689af24b25aca6a29e50 [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;
John Grossman68f09452012-02-22 15:38:35 -0800495 mRetransmitEndpointValid = false;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700496
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497#if CALLBACK_ANTAGONIZER
498 LOGD("create Antagonizer");
499 mAntagonizer = new Antagonizer(notify, this);
500#endif
501}
502
503MediaPlayerService::Client::~Client()
504{
505 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
506 mAudioOutput.clear();
507 wp<Client> client(this);
508 disconnect();
509 mService->removeClient(client);
510}
511
512void MediaPlayerService::Client::disconnect()
513{
514 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
515 // grab local reference and clear main reference to prevent future
516 // access to object
517 sp<MediaPlayerBase> p;
518 {
519 Mutex::Autolock l(mLock);
520 p = mPlayer;
521 }
Dave Sparks795fa582009-03-24 17:57:12 -0700522 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700523
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524 mPlayer.clear();
525
526 // clear the notification to prevent callbacks to dead client
527 // and reset the player. We assume the player will serialize
528 // access to itself if necessary.
529 if (p != 0) {
530 p->setNotifyCallback(0, 0);
531#if CALLBACK_ANTAGONIZER
532 LOGD("kill Antagonizer");
533 mAntagonizer->kill();
534#endif
535 p->reset();
536 }
537
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700538 disconnectNativeWindow();
539
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540 IPCThreadState::self()->flushCommands();
541}
542
Andreas Huber47f59cf2009-08-07 09:30:32 -0700543static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700544 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700545}
546
James Dong148c1a22009-09-06 14:29:45 -0700547player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548{
549 char buf[20];
550 lseek(fd, offset, SEEK_SET);
551 read(fd, buf, sizeof(buf));
552 lseek(fd, offset, SEEK_SET);
553
554 long ident = *((long*)buf);
555
556 // Ogg vorbis?
557 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700558 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800559
560 // Some kind of MIDI?
561 EAS_DATA_HANDLE easdata;
562 if (EAS_Init(&easdata) == EAS_SUCCESS) {
563 EAS_FILE locator;
564 locator.path = NULL;
565 locator.fd = fd;
566 locator.offset = offset;
567 locator.length = length;
568 EAS_HANDLE eashandle;
569 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
570 EAS_CloseFile(easdata, eashandle);
571 EAS_Shutdown(easdata);
572 return SONIVOX_PLAYER;
573 }
574 EAS_Shutdown(easdata);
575 }
576
Andreas Huber47f59cf2009-08-07 09:30:32 -0700577 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578}
579
James Dong148c1a22009-09-06 14:29:45 -0700580player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581{
Nicolas Catania14d27472009-07-13 14:37:49 -0700582 if (TestPlayerStub::canBeUsed(url)) {
583 return TEST_PLAYER;
584 }
585
Andreas Huber0a73d812011-03-21 16:28:04 -0700586 if (!strncasecmp("http://", url, 7)
587 || !strncasecmp("https://", url, 8)) {
Andreas Hubered8d14f2011-02-16 09:05:38 -0800588 size_t len = strlen(url);
589 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
590 return NU_PLAYER;
591 }
Andreas Huber5bc087c2010-12-23 10:27:40 -0800592
Andreas Hubered8d14f2011-02-16 09:05:38 -0800593 if (strstr(url,"m3u8")) {
594 return NU_PLAYER;
Andreas Huber5bc087c2010-12-23 10:27:40 -0800595 }
596 }
597
Andreas Huber2bfdd422011-10-11 15:24:07 -0700598 if (!strncasecmp("rtsp://", url, 7)) {
599 return NU_PLAYER;
600 }
601
Mike J. Chen1a5e6b12011-08-15 13:24:13 -0700602 if (!strncasecmp("aahRX://", url, 8)) {
603 return AAH_RX_PLAYER;
604 }
605
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 // use MidiFile for MIDI extensions
607 int lenURL = strlen(url);
608 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
609 int len = strlen(FILE_EXTS[i].extension);
610 int start = lenURL - len;
611 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900612 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700613 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614 }
615 }
616 }
617
Andreas Huber47f59cf2009-08-07 09:30:32 -0700618 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800619}
620
621static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
622 notify_callback_f notifyFunc)
623{
624 sp<MediaPlayerBase> p;
625 switch (playerType) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 case SONIVOX_PLAYER:
627 LOGV(" create MidiFile");
628 p = new MidiFile();
629 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700630 case STAGEFRIGHT_PLAYER:
631 LOGV(" create StagefrightPlayer");
632 p = new StagefrightPlayer;
633 break;
Andreas Huberf9334412010-12-15 15:17:42 -0800634 case NU_PLAYER:
635 LOGV(" create NuPlayer");
636 p = new NuPlayerDriver;
637 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700638 case TEST_PLAYER:
639 LOGV("Create Test Player stub");
640 p = new TestPlayerStub();
641 break;
Mike J. Chen1a5e6b12011-08-15 13:24:13 -0700642 case AAH_RX_PLAYER:
643 LOGV(" create A@H RX Player");
644 p = createAAH_RXPlayer();
645 break;
646 case AAH_TX_PLAYER:
647 LOGV(" create A@H TX Player");
648 p = createAAH_TXPlayer();
649 break;
James Dong30d713a2010-11-10 18:42:40 -0800650 default:
651 LOGE("Unknown player type: %d", playerType);
652 return NULL;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800653 }
654 if (p != NULL) {
655 if (p->initCheck() == NO_ERROR) {
656 p->setNotifyCallback(cookie, notifyFunc);
657 } else {
658 p.clear();
659 }
660 }
661 if (p == NULL) {
662 LOGE("Failed to create player object");
663 }
664 return p;
665}
666
667sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
668{
669 // determine if we have the right player type
670 sp<MediaPlayerBase> p = mPlayer;
671 if ((p != NULL) && (p->playerType() != playerType)) {
672 LOGV("delete player");
673 p.clear();
674 }
675 if (p == NULL) {
676 p = android::createPlayer(playerType, this, notify);
677 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700678
Jason Simmonsdb29e522011-08-12 13:46:55 -0700679 if (p != NULL) {
680 p->setUID(mUID);
681 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700682
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800683 return p;
684}
685
Andreas Huber2db84552010-01-28 11:19:57 -0800686status_t MediaPlayerService::Client::setDataSource(
687 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800688{
689 LOGV("setDataSource(%s)", url);
690 if (url == NULL)
691 return UNKNOWN_ERROR;
692
Dave Burked681bbb2011-08-30 14:39:17 +0100693 if ((strncmp(url, "http://", 7) == 0) ||
694 (strncmp(url, "https://", 8) == 0) ||
695 (strncmp(url, "rtsp://", 7) == 0)) {
696 if (!checkPermission("android.permission.INTERNET")) {
697 return PERMISSION_DENIED;
698 }
699 }
700
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800701 if (strncmp(url, "content://", 10) == 0) {
702 // get a filedescriptor for the content Uri and
703 // pass it to the setDataSource(fd) method
704
705 String16 url16(url);
706 int fd = android::openContentProviderFile(url16);
707 if (fd < 0)
708 {
709 LOGE("Couldn't open fd for %s", url);
710 return UNKNOWN_ERROR;
711 }
712 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
713 close(fd);
714 return mStatus;
715 } else {
John Grossman68f09452012-02-22 15:38:35 -0800716 // Until re-transmit functionality is added to the existing core android
717 // players, we use the special AAH TX player whenever we were configured
718 // for retransmission.
719 player_type playerType = mRetransmitEndpointValid
720 ? AAH_TX_PLAYER
721 : getPlayerType(url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800722 LOGV("player type = %d", playerType);
723
724 // create the right type of player
725 sp<MediaPlayerBase> p = createPlayer(playerType);
726 if (p == NULL) return NO_INIT;
727
728 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700729 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
731 }
732
733 // now set data source
734 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800735 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700736 if (mStatus == NO_ERROR) {
John Grossman68f09452012-02-22 15:38:35 -0800737 // Set the re-transmission endpoint if one was chosen.
738 if (mRetransmitEndpointValid) {
739 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
740 if (mStatus != NO_ERROR) {
741 LOGE("setRetransmitEndpoint error: %d", mStatus);
742 return mStatus;
743 }
744 }
745
Nicolas Catania14d27472009-07-13 14:37:49 -0700746 mPlayer = p;
747 } else {
748 LOGE(" error: %d", mStatus);
749 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750 return mStatus;
751 }
752}
753
754status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
755{
756 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
757 struct stat sb;
758 int ret = fstat(fd, &sb);
759 if (ret != 0) {
760 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
761 return UNKNOWN_ERROR;
762 }
763
764 LOGV("st_dev = %llu", sb.st_dev);
765 LOGV("st_mode = %u", sb.st_mode);
766 LOGV("st_uid = %lu", sb.st_uid);
767 LOGV("st_gid = %lu", sb.st_gid);
768 LOGV("st_size = %llu", sb.st_size);
769
770 if (offset >= sb.st_size) {
771 LOGE("offset error");
772 ::close(fd);
773 return UNKNOWN_ERROR;
774 }
775 if (offset + length > sb.st_size) {
776 length = sb.st_size - offset;
777 LOGV("calculated length = %lld", length);
778 }
779
John Grossman68f09452012-02-22 15:38:35 -0800780 // Until re-transmit functionality is added to the existing core android
781 // players, we use the special AAH TX player whenever we were configured for
782 // retransmission.
783 player_type playerType = mRetransmitEndpointValid
784 ? AAH_TX_PLAYER
785 : getPlayerType(fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800786 LOGV("player type = %d", playerType);
787
788 // create the right type of player
789 sp<MediaPlayerBase> p = createPlayer(playerType);
790 if (p == NULL) return NO_INIT;
791
792 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700793 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800794 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
795 }
796
797 // now set data source
798 mStatus = p->setDataSource(fd, offset, length);
John Grossman68f09452012-02-22 15:38:35 -0800799 if (mStatus == NO_ERROR) {
800 // Set the re-transmission endpoint if one was chosen.
801 if (mRetransmitEndpointValid) {
802 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
803 if (mStatus != NO_ERROR) {
804 LOGE("setRetransmitEndpoint error: %d", mStatus);
805 return mStatus;
806 }
807 }
808
809 mPlayer = p;
810 }
Dave Burked681bbb2011-08-30 14:39:17 +0100811
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 return mStatus;
813}
814
Andreas Hubere2b10282010-11-23 11:41:34 -0800815status_t MediaPlayerService::Client::setDataSource(
816 const sp<IStreamSource> &source) {
817 // create the right type of player
John Grossman68f09452012-02-22 15:38:35 -0800818 // Until re-transmit functionality is added to the existing core android
819 // players, we use the special AAH TX player whenever we were configured for
820 // retransmission.
821 player_type playerType = mRetransmitEndpointValid
822 ? AAH_TX_PLAYER
823 : NU_PLAYER;
824 LOGV("player type = %d", playerType);
825 sp<MediaPlayerBase> p = createPlayer(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800826
827 if (p == NULL) {
828 return NO_INIT;
829 }
830
831 if (!p->hardwareOutput()) {
832 mAudioOutput = new AudioOutput(mAudioSessionId);
833 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
834 }
835
836 // now set data source
837 mStatus = p->setDataSource(source);
838
839 if (mStatus == OK) {
John Grossman68f09452012-02-22 15:38:35 -0800840 // Set the re-transmission endpoint if one was chosen.
841 if (mRetransmitEndpointValid) {
842 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
843 if (mStatus != NO_ERROR) {
844 LOGE("setRetransmitEndpoint error: %d", mStatus);
845 return mStatus;
846 }
847 }
848
Andreas Hubere2b10282010-11-23 11:41:34 -0800849 mPlayer = p;
850 }
851
852 return mStatus;
853}
854
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700855void MediaPlayerService::Client::disconnectNativeWindow() {
856 if (mConnectedWindow != NULL) {
857 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
858 NATIVE_WINDOW_API_MEDIA);
859
860 if (err != OK) {
861 LOGW("native_window_api_disconnect returned an error: %s (%d)",
862 strerror(-err), err);
863 }
864 }
865 mConnectedWindow.clear();
866}
867
Glenn Kasten11731182011-02-08 17:26:17 -0800868status_t MediaPlayerService::Client::setVideoSurfaceTexture(
869 const sp<ISurfaceTexture>& surfaceTexture)
870{
871 LOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, surfaceTexture.get());
872 sp<MediaPlayerBase> p = getPlayer();
873 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700874
875 sp<IBinder> binder(surfaceTexture == NULL ? NULL :
876 surfaceTexture->asBinder());
877 if (mConnectedWindowBinder == binder) {
878 return OK;
879 }
880
881 sp<ANativeWindow> anw;
882 if (surfaceTexture != NULL) {
883 anw = new SurfaceTextureClient(surfaceTexture);
884 status_t err = native_window_api_connect(anw.get(),
885 NATIVE_WINDOW_API_MEDIA);
886
887 if (err != OK) {
888 LOGE("setVideoSurfaceTexture failed: %d", err);
889 // Note that we must do the reset before disconnecting from the ANW.
890 // Otherwise queue/dequeue calls could be made on the disconnected
891 // ANW, which may result in errors.
892 reset();
893
894 disconnectNativeWindow();
895
896 return err;
897 }
898 }
899
900 // Note that we must set the player's new SurfaceTexture before
901 // disconnecting the old one. Otherwise queue/dequeue calls could be made
902 // on the disconnected ANW, which may result in errors.
903 status_t err = p->setVideoSurfaceTexture(surfaceTexture);
904
905 disconnectNativeWindow();
906
907 mConnectedWindow = anw;
908
909 if (err == OK) {
910 mConnectedWindowBinder = binder;
911 } else {
912 disconnectNativeWindow();
913 }
914
915 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800916}
917
Nicolas Catania1d187f12009-05-12 23:25:55 -0700918status_t MediaPlayerService::Client::invoke(const Parcel& request,
919 Parcel *reply)
920{
921 sp<MediaPlayerBase> p = getPlayer();
922 if (p == NULL) return UNKNOWN_ERROR;
923 return p->invoke(request, reply);
924}
925
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700926// This call doesn't need to access the native player.
927status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
928{
929 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700930 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700931
Nicolas Catania48290382009-07-10 13:53:06 -0700932 if (unmarshallFilter(filter, &allow, &status) &&
933 unmarshallFilter(filter, &drop, &status)) {
934 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700935
936 mMetadataAllow = allow;
937 mMetadataDrop = drop;
938 }
939 return status;
940}
941
Nicolas Catania48290382009-07-10 13:53:06 -0700942status_t MediaPlayerService::Client::getMetadata(
943 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700944{
nikoa64c8c72009-07-20 15:07:26 -0700945 sp<MediaPlayerBase> player = getPlayer();
946 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700947
nikod608a812009-07-16 16:39:53 -0700948 status_t status;
949 // Placeholder for the return code, updated by the caller.
950 reply->writeInt32(-1);
951
nikoa64c8c72009-07-20 15:07:26 -0700952 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700953
954 // We don't block notifications while we fetch the data. We clear
955 // mMetadataUpdated first so we don't lose notifications happening
956 // during the rest of this call.
957 {
958 Mutex::Autolock lock(mLock);
959 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700960 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700961 }
962 mMetadataUpdated.clear();
963 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700964
nikoa64c8c72009-07-20 15:07:26 -0700965 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700966
nikoa64c8c72009-07-20 15:07:26 -0700967 metadata.appendHeader();
968 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700969
970 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700971 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700972 LOGE("getMetadata failed %d", status);
973 return status;
974 }
975
976 // FIXME: Implement filtering on the result. Not critical since
977 // filtering takes place on the update notifications already. This
978 // would be when all the metadata are fetch and a filter is set.
979
nikod608a812009-07-16 16:39:53 -0700980 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700981 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700982 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700983}
984
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800985status_t MediaPlayerService::Client::prepareAsync()
986{
987 LOGV("[%d] prepareAsync", mConnId);
988 sp<MediaPlayerBase> p = getPlayer();
989 if (p == 0) return UNKNOWN_ERROR;
990 status_t ret = p->prepareAsync();
991#if CALLBACK_ANTAGONIZER
992 LOGD("start Antagonizer");
993 if (ret == NO_ERROR) mAntagonizer->start();
994#endif
995 return ret;
996}
997
998status_t MediaPlayerService::Client::start()
999{
1000 LOGV("[%d] start", mConnId);
1001 sp<MediaPlayerBase> p = getPlayer();
1002 if (p == 0) return UNKNOWN_ERROR;
1003 p->setLooping(mLoop);
1004 return p->start();
1005}
1006
1007status_t MediaPlayerService::Client::stop()
1008{
1009 LOGV("[%d] stop", mConnId);
1010 sp<MediaPlayerBase> p = getPlayer();
1011 if (p == 0) return UNKNOWN_ERROR;
1012 return p->stop();
1013}
1014
1015status_t MediaPlayerService::Client::pause()
1016{
1017 LOGV("[%d] pause", mConnId);
1018 sp<MediaPlayerBase> p = getPlayer();
1019 if (p == 0) return UNKNOWN_ERROR;
1020 return p->pause();
1021}
1022
1023status_t MediaPlayerService::Client::isPlaying(bool* state)
1024{
1025 *state = false;
1026 sp<MediaPlayerBase> p = getPlayer();
1027 if (p == 0) return UNKNOWN_ERROR;
1028 *state = p->isPlaying();
1029 LOGV("[%d] isPlaying: %d", mConnId, *state);
1030 return NO_ERROR;
1031}
1032
1033status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1034{
1035 LOGV("getCurrentPosition");
1036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 status_t ret = p->getCurrentPosition(msec);
1039 if (ret == NO_ERROR) {
1040 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1041 } else {
1042 LOGE("getCurrentPosition returned %d", ret);
1043 }
1044 return ret;
1045}
1046
1047status_t MediaPlayerService::Client::getDuration(int *msec)
1048{
1049 LOGV("getDuration");
1050 sp<MediaPlayerBase> p = getPlayer();
1051 if (p == 0) return UNKNOWN_ERROR;
1052 status_t ret = p->getDuration(msec);
1053 if (ret == NO_ERROR) {
1054 LOGV("[%d] getDuration = %d", mConnId, *msec);
1055 } else {
1056 LOGE("getDuration returned %d", ret);
1057 }
1058 return ret;
1059}
1060
1061status_t MediaPlayerService::Client::seekTo(int msec)
1062{
1063 LOGV("[%d] seekTo(%d)", mConnId, msec);
1064 sp<MediaPlayerBase> p = getPlayer();
1065 if (p == 0) return UNKNOWN_ERROR;
1066 return p->seekTo(msec);
1067}
1068
1069status_t MediaPlayerService::Client::reset()
1070{
1071 LOGV("[%d] reset", mConnId);
John Grossman68f09452012-02-22 15:38:35 -08001072 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 return p->reset();
1076}
1077
1078status_t MediaPlayerService::Client::setAudioStreamType(int type)
1079{
1080 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1081 // TODO: for hardware output, call player instead
1082 Mutex::Autolock l(mLock);
1083 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1084 return NO_ERROR;
1085}
1086
1087status_t MediaPlayerService::Client::setLooping(int loop)
1088{
1089 LOGV("[%d] setLooping(%d)", mConnId, loop);
1090 mLoop = loop;
1091 sp<MediaPlayerBase> p = getPlayer();
1092 if (p != 0) return p->setLooping(loop);
1093 return NO_ERROR;
1094}
1095
1096status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1097{
1098 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
Mike J. Chen1a5e6b12011-08-15 13:24:13 -07001099
1100 // for hardware output, call player instead
1101 sp<MediaPlayerBase> p = getPlayer();
1102 {
1103 Mutex::Autolock l(mLock);
1104 if (p != 0 && p->hardwareOutput()) {
1105 MediaPlayerHWInterface* hwp =
1106 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1107 return hwp->setVolume(leftVolume, rightVolume);
1108 } else {
1109 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1110 return NO_ERROR;
1111 }
1112 }
1113
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001114 return NO_ERROR;
1115}
1116
Eric Laurent2beeb502010-07-16 07:43:46 -07001117status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1118{
1119 LOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1120 Mutex::Autolock l(mLock);
1121 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1122 return NO_ERROR;
1123}
1124
1125status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1126{
1127 LOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1128 Mutex::Autolock l(mLock);
1129 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1130 return NO_ERROR;
1131}
Nicolas Catania48290382009-07-10 13:53:06 -07001132
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001133status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1134 LOGV("[%d] setParameter(%d)", mConnId, key);
1135 sp<MediaPlayerBase> p = getPlayer();
1136 if (p == 0) return UNKNOWN_ERROR;
1137 return p->setParameter(key, request);
1138}
1139
1140status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1141 LOGV("[%d] getParameter(%d)", mConnId, key);
1142 sp<MediaPlayerBase> p = getPlayer();
1143 if (p == 0) return UNKNOWN_ERROR;
1144 return p->getParameter(key, reply);
1145}
1146
John Grossman68f09452012-02-22 15:38:35 -08001147status_t MediaPlayerService::Client::setRetransmitEndpoint(
1148 const struct sockaddr_in* endpoint) {
1149
1150 if (NULL != endpoint) {
1151 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1152 uint16_t p = ntohs(endpoint->sin_port);
1153 LOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1154 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1155 } else {
1156 LOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1157 }
1158
1159 sp<MediaPlayerBase> p = getPlayer();
1160
1161 // Right now, the only valid time to set a retransmit endpoint is before
1162 // player selection has been made (since the presence or absence of a
1163 // retransmit endpoint is going to determine which player is selected during
1164 // setDataSource).
1165 if (p != 0) return INVALID_OPERATION;
1166
1167 if (NULL != endpoint) {
1168 mRetransmitEndpoint = *endpoint;
1169 mRetransmitEndpointValid = true;
1170 } else {
1171 mRetransmitEndpointValid = false;
1172 }
1173
1174 return NO_ERROR;
1175}
1176
Gloria Wangb483c472011-04-11 17:23:27 -07001177void MediaPlayerService::Client::notify(
1178 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001179{
1180 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001181
1182 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001183 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001184 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001185
1186 if(client->shouldDropMetadata(metadata_type)) {
1187 return;
1188 }
1189
1190 // Update the list of metadata that have changed. getMetadata
1191 // also access mMetadataUpdated and clears it.
1192 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001193 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001194 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
Gloria Wangb483c472011-04-11 17:23:27 -07001195 client->mClient->notify(msg, ext1, ext2, obj);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001196}
1197
Nicolas Catania48290382009-07-10 13:53:06 -07001198
nikoa64c8c72009-07-20 15:07:26 -07001199bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001200{
Nicolas Catania48290382009-07-10 13:53:06 -07001201 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001202
Nicolas Catania48290382009-07-10 13:53:06 -07001203 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001204 return true;
1205 }
1206
Nicolas Catania48290382009-07-10 13:53:06 -07001207 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001208 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001209 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001210 return true;
1211 }
1212}
1213
Nicolas Catania48290382009-07-10 13:53:06 -07001214
nikoa64c8c72009-07-20 15:07:26 -07001215void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001216 Mutex::Autolock lock(mLock);
1217 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1218 mMetadataUpdated.add(metadata_type);
1219 }
1220}
1221
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001222#if CALLBACK_ANTAGONIZER
1223const int Antagonizer::interval = 10000; // 10 msecs
1224
1225Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1226 mExit(false), mActive(false), mClient(client), mCb(cb)
1227{
1228 createThread(callbackThread, this);
1229}
1230
1231void Antagonizer::kill()
1232{
1233 Mutex::Autolock _l(mLock);
1234 mActive = false;
1235 mExit = true;
1236 mCondition.wait(mLock);
1237}
1238
1239int Antagonizer::callbackThread(void* user)
1240{
1241 LOGD("Antagonizer started");
1242 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1243 while (!p->mExit) {
1244 if (p->mActive) {
1245 LOGV("send event");
1246 p->mCb(p->mClient, 0, 0, 0);
1247 }
1248 usleep(interval);
1249 }
1250 Mutex::Autolock _l(p->mLock);
1251 p->mCondition.signal();
1252 LOGD("Antagonizer stopped");
1253 return 0;
1254}
1255#endif
1256
1257static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1258
1259sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1260{
1261 LOGV("decode(%s)", url);
1262 sp<MemoryBase> mem;
1263 sp<MediaPlayerBase> player;
1264
1265 // Protect our precious, precious DRMd ringtones by only allowing
1266 // decoding of http, but not filesystem paths or content Uris.
1267 // If the application wants to decode those, it should open a
1268 // filedescriptor for them and use that.
1269 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1270 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1271 return mem;
1272 }
1273
1274 player_type playerType = getPlayerType(url);
1275 LOGV("player type = %d", playerType);
1276
1277 // create the right type of player
1278 sp<AudioCache> cache = new AudioCache(url);
1279 player = android::createPlayer(playerType, cache.get(), cache->notify);
1280 if (player == NULL) goto Exit;
1281 if (player->hardwareOutput()) goto Exit;
1282
1283 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1284
1285 // set data source
1286 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1287
1288 LOGV("prepare");
1289 player->prepareAsync();
1290
1291 LOGV("wait for prepare");
1292 if (cache->wait() != NO_ERROR) goto Exit;
1293
1294 LOGV("start");
1295 player->start();
1296
1297 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001298 cache->wait();
1299 // in case of error, return what was successfully decoded.
1300 if (cache->size() == 0) {
1301 goto Exit;
1302 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001303
1304 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1305 *pSampleRate = cache->sampleRate();
1306 *pNumChannels = cache->channelCount();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001307 *pFormat = (int)cache->format();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1309
1310Exit:
1311 if (player != 0) player->reset();
1312 return mem;
1313}
1314
1315sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1316{
1317 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1318 sp<MemoryBase> mem;
1319 sp<MediaPlayerBase> player;
1320
1321 player_type playerType = getPlayerType(fd, offset, length);
1322 LOGV("player type = %d", playerType);
1323
1324 // create the right type of player
1325 sp<AudioCache> cache = new AudioCache("decode_fd");
1326 player = android::createPlayer(playerType, cache.get(), cache->notify);
1327 if (player == NULL) goto Exit;
1328 if (player->hardwareOutput()) goto Exit;
1329
1330 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1331
1332 // set data source
1333 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1334
1335 LOGV("prepare");
1336 player->prepareAsync();
1337
1338 LOGV("wait for prepare");
1339 if (cache->wait() != NO_ERROR) goto Exit;
1340
1341 LOGV("start");
1342 player->start();
1343
1344 LOGV("wait for playback complete");
Eric Laurent9cb839a2011-09-27 09:48:56 -07001345 cache->wait();
1346 // in case of error, return what was successfully decoded.
1347 if (cache->size() == 0) {
1348 goto Exit;
1349 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350
1351 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1352 *pSampleRate = cache->sampleRate();
1353 *pNumChannels = cache->channelCount();
1354 *pFormat = cache->format();
1355 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1356
1357Exit:
1358 if (player != 0) player->reset();
1359 ::close(fd);
1360 return mem;
1361}
1362
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001363
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364#undef LOG_TAG
1365#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001366MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001367 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001368 mCallbackCookie(NULL),
1369 mSessionId(sessionId) {
1370 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001371 mTrack = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -07001372 mStreamType = AUDIO_STREAM_MUSIC;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 mLeftVolume = 1.0;
1374 mRightVolume = 1.0;
1375 mLatency = 0;
1376 mMsecsPerFrame = 0;
Eric Laurent2beeb502010-07-16 07:43:46 -07001377 mAuxEffectId = 0;
1378 mSendLevel = 0.0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001379 setMinBufferCount();
1380}
1381
1382MediaPlayerService::AudioOutput::~AudioOutput()
1383{
1384 close();
1385}
1386
1387void MediaPlayerService::AudioOutput::setMinBufferCount()
1388{
1389 char value[PROPERTY_VALUE_MAX];
1390 if (property_get("ro.kernel.qemu", value, 0)) {
1391 mIsOnEmulator = true;
1392 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1393 }
1394}
1395
1396bool MediaPlayerService::AudioOutput::isOnEmulator()
1397{
1398 setMinBufferCount();
1399 return mIsOnEmulator;
1400}
1401
1402int MediaPlayerService::AudioOutput::getMinBufferCount()
1403{
1404 setMinBufferCount();
1405 return mMinBufferCount;
1406}
1407
1408ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1409{
1410 if (mTrack == 0) return NO_INIT;
1411 return mTrack->frameCount() * frameSize();
1412}
1413
1414ssize_t MediaPlayerService::AudioOutput::frameCount() const
1415{
1416 if (mTrack == 0) return NO_INIT;
1417 return mTrack->frameCount();
1418}
1419
1420ssize_t MediaPlayerService::AudioOutput::channelCount() const
1421{
1422 if (mTrack == 0) return NO_INIT;
1423 return mTrack->channelCount();
1424}
1425
1426ssize_t MediaPlayerService::AudioOutput::frameSize() const
1427{
1428 if (mTrack == 0) return NO_INIT;
1429 return mTrack->frameSize();
1430}
1431
1432uint32_t MediaPlayerService::AudioOutput::latency () const
1433{
1434 return mLatency;
1435}
1436
1437float MediaPlayerService::AudioOutput::msecsPerFrame() const
1438{
1439 return mMsecsPerFrame;
1440}
1441
Eric Laurent342e9cf2010-01-19 17:37:09 -08001442status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1443{
1444 if (mTrack == 0) return NO_INIT;
1445 return mTrack->getPosition(position);
1446}
1447
Andreas Huber20111aa2009-07-14 16:56:47 -07001448status_t MediaPlayerService::AudioOutput::open(
1449 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1450 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451{
Andreas Huber20111aa2009-07-14 16:56:47 -07001452 mCallback = cb;
1453 mCallbackCookie = cookie;
1454
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001455 // Check argument "bufferCount" against the mininum buffer count
1456 if (bufferCount < mMinBufferCount) {
1457 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1458 bufferCount = mMinBufferCount;
1459
1460 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001461 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462 if (mTrack) close();
1463 int afSampleRate;
1464 int afFrameCount;
1465 int frameCount;
1466
1467 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1468 return NO_INIT;
1469 }
1470 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1471 return NO_INIT;
1472 }
1473
1474 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001475
1476 AudioTrack *t;
1477 if (mCallback != NULL) {
1478 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001479 mStreamType,
1480 sampleRate,
1481 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001482 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurentc2f1f072009-07-17 12:17:14 -07001483 frameCount,
1484 0 /* flags */,
1485 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001486 this,
1487 0,
1488 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001489 } else {
1490 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001491 mStreamType,
1492 sampleRate,
1493 format,
Dima Zavinfce7a472011-04-19 22:30:36 -07001494 (channelCount == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001495 frameCount,
1496 0,
1497 NULL,
1498 NULL,
1499 0,
1500 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001501 }
1502
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001503 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1504 LOGE("Unable to create audio track");
1505 delete t;
1506 return NO_INIT;
1507 }
1508
1509 LOGV("setVolume");
1510 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001511
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001513 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001514 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001515
1516 t->setAuxEffectSendLevel(mSendLevel);
1517 return t->attachAuxEffect(mAuxEffectId);;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001518}
1519
1520void MediaPlayerService::AudioOutput::start()
1521{
1522 LOGV("start");
1523 if (mTrack) {
1524 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001525 mTrack->setAuxEffectSendLevel(mSendLevel);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001526 mTrack->start();
1527 }
1528}
1529
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001530
1531
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001532ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1533{
Andreas Huber20111aa2009-07-14 16:56:47 -07001534 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1535
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001536 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001537 if (mTrack) {
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001538 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001539 return ret;
1540 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001541 return NO_INIT;
1542}
1543
1544void MediaPlayerService::AudioOutput::stop()
1545{
1546 LOGV("stop");
1547 if (mTrack) mTrack->stop();
1548}
1549
1550void MediaPlayerService::AudioOutput::flush()
1551{
1552 LOGV("flush");
1553 if (mTrack) mTrack->flush();
1554}
1555
1556void MediaPlayerService::AudioOutput::pause()
1557{
1558 LOGV("pause");
1559 if (mTrack) mTrack->pause();
1560}
1561
1562void MediaPlayerService::AudioOutput::close()
1563{
1564 LOGV("close");
1565 delete mTrack;
1566 mTrack = 0;
1567}
1568
1569void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1570{
1571 LOGV("setVolume(%f, %f)", left, right);
1572 mLeftVolume = left;
1573 mRightVolume = right;
1574 if (mTrack) {
1575 mTrack->setVolume(left, right);
1576 }
1577}
1578
Eric Laurent2beeb502010-07-16 07:43:46 -07001579status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1580{
1581 LOGV("setAuxEffectSendLevel(%f)", level);
1582 mSendLevel = level;
1583 if (mTrack) {
1584 return mTrack->setAuxEffectSendLevel(level);
1585 }
1586 return NO_ERROR;
1587}
1588
1589status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1590{
1591 LOGV("attachAuxEffect(%d)", effectId);
1592 mAuxEffectId = effectId;
1593 if (mTrack) {
1594 return mTrack->attachAuxEffect(effectId);
1595 }
1596 return NO_ERROR;
1597}
1598
Andreas Huber20111aa2009-07-14 16:56:47 -07001599// static
1600void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001601 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001602 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001603 if (event != AudioTrack::EVENT_MORE_DATA) {
1604 return;
1605 }
1606
1607 AudioOutput *me = (AudioOutput *)cookie;
1608 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1609
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001610 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001611 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001612
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001613 if (actualSize == 0 && buffer->size > 0) {
1614 // We've reached EOS but the audio track is not stopped yet,
1615 // keep playing silence.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001616
Andreas Huber51c1e0e2011-04-04 11:43:40 -07001617 memset(buffer->raw, 0, buffer->size);
1618 actualSize = buffer->size;
1619 }
1620
1621 buffer->size = actualSize;
Andreas Huber20111aa2009-07-14 16:56:47 -07001622}
1623
Eric Laurent8c563ed2010-10-07 18:23:03 -07001624int MediaPlayerService::AudioOutput::getSessionId()
1625{
1626 return mSessionId;
1627}
1628
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001629#undef LOG_TAG
1630#define LOG_TAG "AudioCache"
1631MediaPlayerService::AudioCache::AudioCache(const char* name) :
1632 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1633 mError(NO_ERROR), mCommandComplete(false)
1634{
1635 // create ashmem heap
1636 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1637}
1638
1639uint32_t MediaPlayerService::AudioCache::latency () const
1640{
1641 return 0;
1642}
1643
1644float MediaPlayerService::AudioCache::msecsPerFrame() const
1645{
1646 return mMsecsPerFrame;
1647}
1648
Eric Laurent342e9cf2010-01-19 17:37:09 -08001649status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1650{
1651 if (position == 0) return BAD_VALUE;
1652 *position = mSize;
1653 return NO_ERROR;
1654}
1655
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001656////////////////////////////////////////////////////////////////////////////////
1657
1658struct CallbackThread : public Thread {
1659 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1660 MediaPlayerBase::AudioSink::AudioCallback cb,
1661 void *cookie);
1662
1663protected:
1664 virtual ~CallbackThread();
1665
1666 virtual bool threadLoop();
1667
1668private:
1669 wp<MediaPlayerBase::AudioSink> mSink;
1670 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1671 void *mCookie;
1672 void *mBuffer;
1673 size_t mBufferSize;
1674
1675 CallbackThread(const CallbackThread &);
1676 CallbackThread &operator=(const CallbackThread &);
1677};
1678
1679CallbackThread::CallbackThread(
1680 const wp<MediaPlayerBase::AudioSink> &sink,
1681 MediaPlayerBase::AudioSink::AudioCallback cb,
1682 void *cookie)
1683 : mSink(sink),
1684 mCallback(cb),
1685 mCookie(cookie),
1686 mBuffer(NULL),
1687 mBufferSize(0) {
1688}
1689
1690CallbackThread::~CallbackThread() {
1691 if (mBuffer) {
1692 free(mBuffer);
1693 mBuffer = NULL;
1694 }
1695}
1696
1697bool CallbackThread::threadLoop() {
1698 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1699 if (sink == NULL) {
1700 return false;
1701 }
1702
1703 if (mBuffer == NULL) {
1704 mBufferSize = sink->bufferSize();
1705 mBuffer = malloc(mBufferSize);
1706 }
1707
1708 size_t actualSize =
1709 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1710
1711 if (actualSize > 0) {
1712 sink->write(mBuffer, actualSize);
1713 }
1714
1715 return true;
1716}
1717
1718////////////////////////////////////////////////////////////////////////////////
1719
Andreas Huber20111aa2009-07-14 16:56:47 -07001720status_t MediaPlayerService::AudioCache::open(
1721 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1722 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001723{
Dave Sparks8eb80112009-12-09 20:20:26 -08001724 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001725 if (mHeap->getHeapID() < 0) {
1726 return NO_INIT;
1727 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001728
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001729 mSampleRate = sampleRate;
1730 mChannelCount = (uint16_t)channelCount;
1731 mFormat = (uint16_t)format;
1732 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001733
1734 if (cb != NULL) {
1735 mCallbackThread = new CallbackThread(this, cb, cookie);
1736 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001737 return NO_ERROR;
1738}
1739
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001740void MediaPlayerService::AudioCache::start() {
1741 if (mCallbackThread != NULL) {
1742 mCallbackThread->run("AudioCache callback");
1743 }
1744}
1745
1746void MediaPlayerService::AudioCache::stop() {
1747 if (mCallbackThread != NULL) {
1748 mCallbackThread->requestExitAndWait();
1749 }
1750}
1751
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001752ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1753{
1754 LOGV("write(%p, %u)", buffer, size);
1755 if ((buffer == 0) || (size == 0)) return size;
1756
1757 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1758 if (p == NULL) return NO_INIT;
1759 p += mSize;
1760 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1761 if (mSize + size > mHeap->getSize()) {
1762 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1763 size = mHeap->getSize() - mSize;
1764 }
1765 memcpy(p, buffer, size);
1766 mSize += size;
1767 return size;
1768}
1769
1770// call with lock held
1771status_t MediaPlayerService::AudioCache::wait()
1772{
1773 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001774 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001775 mSignal.wait(mLock);
1776 }
1777 mCommandComplete = false;
1778
1779 if (mError == NO_ERROR) {
1780 LOGV("wait - success");
1781 } else {
1782 LOGV("wait - error");
1783 }
1784 return mError;
1785}
1786
Gloria Wangb483c472011-04-11 17:23:27 -07001787void MediaPlayerService::AudioCache::notify(
1788 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001789{
1790 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1791 AudioCache* p = static_cast<AudioCache*>(cookie);
1792
1793 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001794 switch (msg)
1795 {
1796 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001797 LOGE("Error %d, %d occurred", ext1, ext2);
1798 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001799 break;
1800 case MEDIA_PREPARED:
1801 LOGV("prepared");
1802 break;
1803 case MEDIA_PLAYBACK_COMPLETE:
1804 LOGV("playback complete");
1805 break;
1806 default:
1807 LOGV("ignored");
1808 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001809 }
1810
1811 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001812 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001813 p->mCommandComplete = true;
1814 p->mSignal.signal();
1815}
1816
Eric Laurent8c563ed2010-10-07 18:23:03 -07001817int MediaPlayerService::AudioCache::getSessionId()
1818{
1819 return 0;
1820}
1821
Gloria Wang7cf180c2011-02-19 18:37:57 -08001822void MediaPlayerService::addBatteryData(uint32_t params)
1823{
1824 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001825
1826 int32_t time = systemTime() / 1000000L;
1827
1828 // change audio output devices. This notification comes from AudioFlinger
1829 if ((params & kBatteryDataSpeakerOn)
1830 || (params & kBatteryDataOtherAudioDeviceOn)) {
1831
1832 int deviceOn[NUM_AUDIO_DEVICES];
1833 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1834 deviceOn[i] = 0;
1835 }
1836
1837 if ((params & kBatteryDataSpeakerOn)
1838 && (params & kBatteryDataOtherAudioDeviceOn)) {
1839 deviceOn[SPEAKER_AND_OTHER] = 1;
1840 } else if (params & kBatteryDataSpeakerOn) {
1841 deviceOn[SPEAKER] = 1;
1842 } else {
1843 deviceOn[OTHER_AUDIO_DEVICE] = 1;
1844 }
1845
1846 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1847 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1848
1849 if (mBatteryAudio.refCount > 0) { // if playing audio
1850 if (!deviceOn[i]) {
1851 mBatteryAudio.lastTime[i] += time;
1852 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1853 mBatteryAudio.lastTime[i] = 0;
1854 } else {
1855 mBatteryAudio.lastTime[i] = 0 - time;
1856 }
1857 }
1858
1859 mBatteryAudio.deviceOn[i] = deviceOn[i];
1860 }
1861 }
1862 return;
1863 }
1864
1865 // an sudio stream is started
1866 if (params & kBatteryDataAudioFlingerStart) {
1867 // record the start time only if currently no other audio
1868 // is being played
1869 if (mBatteryAudio.refCount == 0) {
1870 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1871 if (mBatteryAudio.deviceOn[i]) {
1872 mBatteryAudio.lastTime[i] -= time;
1873 }
1874 }
1875 }
1876
1877 mBatteryAudio.refCount ++;
1878 return;
1879
1880 } else if (params & kBatteryDataAudioFlingerStop) {
1881 if (mBatteryAudio.refCount <= 0) {
1882 LOGW("Battery track warning: refCount is <= 0");
1883 return;
1884 }
1885
1886 // record the stop time only if currently this is the only
1887 // audio being played
1888 if (mBatteryAudio.refCount == 1) {
1889 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1890 if (mBatteryAudio.deviceOn[i]) {
1891 mBatteryAudio.lastTime[i] += time;
1892 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1893 mBatteryAudio.lastTime[i] = 0;
1894 }
1895 }
1896 }
1897
1898 mBatteryAudio.refCount --;
1899 return;
1900 }
1901
Gloria Wang7cf180c2011-02-19 18:37:57 -08001902 int uid = IPCThreadState::self()->getCallingUid();
1903 if (uid == AID_MEDIA) {
1904 return;
1905 }
1906 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08001907
1908 if (index < 0) { // create a new entry for this UID
1909 BatteryUsageInfo info;
1910 info.audioTotalTime = 0;
1911 info.videoTotalTime = 0;
1912 info.audioLastTime = 0;
1913 info.videoLastTime = 0;
1914 info.refCount = 0;
1915
Gloria Wang9ee159b2011-02-24 14:51:45 -08001916 if (mBatteryData.add(uid, info) == NO_MEMORY) {
1917 LOGE("Battery track error: no memory for new app");
1918 return;
1919 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08001920 }
1921
1922 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
1923
1924 if (params & kBatteryDataCodecStarted) {
1925 if (params & kBatteryDataTrackAudio) {
1926 info.audioLastTime -= time;
1927 info.refCount ++;
1928 }
1929 if (params & kBatteryDataTrackVideo) {
1930 info.videoLastTime -= time;
1931 info.refCount ++;
1932 }
1933 } else {
1934 if (info.refCount == 0) {
1935 LOGW("Battery track warning: refCount is already 0");
1936 return;
1937 } else if (info.refCount < 0) {
1938 LOGE("Battery track error: refCount < 0");
1939 mBatteryData.removeItem(uid);
1940 return;
1941 }
1942
1943 if (params & kBatteryDataTrackAudio) {
1944 info.audioLastTime += time;
1945 info.refCount --;
1946 }
1947 if (params & kBatteryDataTrackVideo) {
1948 info.videoLastTime += time;
1949 info.refCount --;
1950 }
1951
1952 // no stream is being played by this UID
1953 if (info.refCount == 0) {
1954 info.audioTotalTime += info.audioLastTime;
1955 info.audioLastTime = 0;
1956 info.videoTotalTime += info.videoLastTime;
1957 info.videoLastTime = 0;
1958 }
1959 }
1960}
1961
1962status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
1963 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08001964
1965 // audio output devices usage
1966 int32_t time = systemTime() / 1000000L; //in ms
1967 int32_t totalTime;
1968
1969 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1970 totalTime = mBatteryAudio.totalTime[i];
1971
1972 if (mBatteryAudio.deviceOn[i]
1973 && (mBatteryAudio.lastTime[i] != 0)) {
1974 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
1975 totalTime += tmpTime;
1976 }
1977
1978 reply->writeInt32(totalTime);
1979 // reset the total time
1980 mBatteryAudio.totalTime[i] = 0;
1981 }
1982
1983 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08001984 BatteryUsageInfo info;
1985 int size = mBatteryData.size();
1986
1987 reply->writeInt32(size);
1988 int i = 0;
1989
1990 while (i < size) {
1991 info = mBatteryData.valueAt(i);
1992
1993 reply->writeInt32(mBatteryData.keyAt(i)); //UID
1994 reply->writeInt32(info.audioTotalTime);
1995 reply->writeInt32(info.videoTotalTime);
1996
1997 info.audioTotalTime = 0;
1998 info.videoTotalTime = 0;
1999
2000 // remove the UID entry where no stream is being played
2001 if (info.refCount <= 0) {
2002 mBatteryData.removeItemsAt(i);
2003 size --;
2004 i --;
2005 }
2006 i++;
2007 }
2008 return NO_ERROR;
2009}
nikoa64c8c72009-07-20 15:07:26 -07002010} // namespace android