blob: 5401ec07c03827e60674ce91a7dc7895c209ba5f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <dirent.h>
27#include <unistd.h>
28
29#include <string.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031#include <cutils/atomic.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070032#include <cutils/properties.h> // for property_get
Mathias Agopiana650aaa2009-06-03 17:32:49 -070033
34#include <utils/misc.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
36#include <android_runtime/ActivityManager.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070037
Mathias Agopian07952722009-05-19 19:08:10 -070038#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
40#include <binder/MemoryHeapBase.h>
41#include <binder/MemoryBase.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissenc39d2e32009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070045#include <utils/Vector.h>
The Android Open Source Project9066cfe2009-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>
nikobc726922009-07-20 15:07:26 -070051#include <media/Metadata.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052#include <media/AudioTrack.h>
53
54#include "MediaRecorderClient.h"
55#include "MediaPlayerService.h"
56#include "MetadataRetrieverClient.h"
57
58#include "MidiFile.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059#include <media/PVPlayer.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070060#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070061#include "StagefrightPlayer.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070062
Andreas Hubere46b7be2009-07-14 16:56:47 -070063#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/* desktop Linux needs a little help with gettid() */
66#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
67#define __KERNEL__
68# include <linux/unistd.h>
69#ifdef _syscall0
70_syscall0(pid_t,gettid)
71#else
72pid_t gettid() { return syscall(__NR_gettid);}
73#endif
74#undef __KERNEL__
75#endif
76
Nicolas Cataniab2c69392009-07-08 08:57:42 -070077namespace {
nikobc726922009-07-20 15:07:26 -070078using android::media::Metadata;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070079using android::status_t;
80using android::OK;
81using android::BAD_VALUE;
82using android::NOT_ENOUGH_DATA;
83using android::Parcel;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070084
85// Max number of entries in the filter.
86const int kMaxFilterSize = 64; // I pulled that out of thin air.
87
nikobc726922009-07-20 15:07:26 -070088// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070089
Nicolas Cataniab2c69392009-07-08 08:57:42 -070090
91// Unmarshall a filter from a Parcel.
92// Filter format in a parcel:
93//
94// 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
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// | number of entries (n) |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// | metadata type 1 |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | metadata type 2 |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// ....
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | metadata type n |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//
107// @param p Parcel that should start with a filter.
108// @param[out] filter On exit contains the list of metadata type to be
109// filtered.
110// @param[out] status On exit contains the status code to be returned.
111// @return true if the parcel starts with a valid filter.
112bool unmarshallFilter(const Parcel& p,
nikobc726922009-07-20 15:07:26 -0700113 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700114 status_t *status)
115{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700116 int32_t val;
117 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700118 {
119 LOGE("Failed to read filter's length");
120 *status = NOT_ENOUGH_DATA;
121 return false;
122 }
123
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700124 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700125 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700126 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700127 *status = BAD_VALUE;
128 return false;
129 }
130
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700131 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700132
133 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700134 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700135
nikobc726922009-07-20 15:07:26 -0700136 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700137
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700138
139 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700140 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700141 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700142 *status = NOT_ENOUGH_DATA;
143 return false;
144 }
145
nikobc726922009-07-20 15:07:26 -0700146 const Metadata::Type *data =
147 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700148
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700149 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700150 {
151 LOGE("Filter had no data");
152 *status = BAD_VALUE;
153 return false;
154 }
155
156 // TODO: The stl impl of vector would be more efficient here
157 // because it degenerates into a memcpy on pod types. Try to
158 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700159 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700160 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700161 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700162 ++data;
163 }
164 *status = OK;
165 return true;
166}
167
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700168// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700169// @param val To be searched.
170// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700172{
173 // Deal with empty and ANY right away
174 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700175 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700176
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700177 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700178}
179
180} // anonymous namespace
181
182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183namespace android {
184
185// TODO: Temp hack until we can register players
186typedef struct {
187 const char *extension;
188 const player_type playertype;
189} extmap;
190extmap FILE_EXTS [] = {
191 {".mid", SONIVOX_PLAYER},
192 {".midi", SONIVOX_PLAYER},
193 {".smf", SONIVOX_PLAYER},
194 {".xmf", SONIVOX_PLAYER},
195 {".imy", SONIVOX_PLAYER},
196 {".rtttl", SONIVOX_PLAYER},
197 {".rtx", SONIVOX_PLAYER},
198 {".ota", SONIVOX_PLAYER},
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800199#ifndef NO_OPENCORE
200 {".wma", PV_PLAYER},
201 {".wmv", PV_PLAYER},
202 {".asf", PV_PLAYER},
203#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204};
205
206// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
208/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
209
210void MediaPlayerService::instantiate() {
211 defaultServiceManager()->addService(
212 String16("media.player"), new MediaPlayerService());
213}
214
215MediaPlayerService::MediaPlayerService()
216{
217 LOGV("MediaPlayerService created");
218 mNextConnId = 1;
219}
220
221MediaPlayerService::~MediaPlayerService()
222{
223 LOGV("MediaPlayerService destroyed");
224}
225
226sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
227{
Gloria Wang608a2632009-10-29 15:46:37 -0700228 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
229 wp<MediaRecorderClient> w = recorder;
230 Mutex::Autolock lock(mLock);
231 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 LOGV("Create new media recorder client from pid %d", pid);
233 return recorder;
234}
235
Gloria Wang608a2632009-10-29 15:46:37 -0700236void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
237{
238 Mutex::Autolock lock(mLock);
239 mMediaRecorderClients.remove(client);
240 LOGV("Delete media recorder client");
241}
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
244{
245 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
246 LOGV("Create new media retriever from pid %d", pid);
247 return retriever;
248}
249
Andreas Huber25643002010-01-28 11:19:57 -0800250sp<IMediaPlayer> MediaPlayerService::create(
251 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
Eric Laurent619346f2010-06-21 09:27:30 -0700252 const KeyedVector<String8, String8> *headers, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253{
254 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurent619346f2010-06-21 09:27:30 -0700255 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
256 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
257 connId, pid, url, connId, audioSessionId);
Andreas Huber25643002010-01-28 11:19:57 -0800258 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 {
260 c.clear();
261 return c;
262 }
263 wp<Client> w = c;
264 Mutex::Autolock lock(mLock);
265 mClients.add(w);
266 return c;
267}
268
269sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Eric Laurent619346f2010-06-21 09:27:30 -0700270 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271{
272 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurent619346f2010-06-21 09:27:30 -0700273 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
274 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
275 connId, pid, fd, offset, length, audioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
277 c.clear();
278 } else {
279 wp<Client> w = c;
280 Mutex::Autolock lock(mLock);
281 mClients.add(w);
282 }
283 ::close(fd);
284 return c;
285}
286
Andreas Huber784202e2009-10-15 13:46:54 -0700287sp<IOMX> MediaPlayerService::getOMX() {
288 Mutex::Autolock autoLock(mLock);
289
290 if (mOMX.get() == NULL) {
291 mOMX = new OMX;
292 }
293
294 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700295}
296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append(" AudioCache\n");
304 if (mHeap != 0) {
305 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
306 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
307 result.append(buffer);
308 }
309 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
310 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
311 result.append(buffer);
312 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
313 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
314 result.append(buffer);
315 ::write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
319status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
320{
321 const size_t SIZE = 256;
322 char buffer[SIZE];
323 String8 result;
324
325 result.append(" AudioOutput\n");
326 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
327 mStreamType, mLeftVolume, mRightVolume);
328 result.append(buffer);
329 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
330 mMsecsPerFrame, mLatency);
331 result.append(buffer);
332 ::write(fd, result.string(), result.size());
333 if (mTrack != 0) {
334 mTrack->dump(fd, args);
335 }
336 return NO_ERROR;
337}
338
339status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
344 result.append(" Client\n");
345 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
346 mPid, mConnId, mStatus, mLoop?"true": "false");
347 result.append(buffer);
348 write(fd, result.string(), result.size());
349 if (mAudioOutput != 0) {
350 mAudioOutput->dump(fd, args);
351 }
352 write(fd, "\n", 1);
353 return NO_ERROR;
354}
355
356static int myTid() {
357#ifdef HAVE_GETTID
358 return gettid();
359#else
360 return getpid();
361#endif
362}
363
364#if defined(__arm__)
365extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
366 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
367extern "C" void free_malloc_leak_info(uint8_t* info);
368
Andreas Huber27123462009-10-27 15:50:04 -0700369// Use the String-class below instead of String8 to allocate all memory
370// beforehand and not reenter the heap while we are examining it...
371struct MyString8 {
372 static const size_t MAX_SIZE = 256 * 1024;
373
374 MyString8()
375 : mPtr((char *)malloc(MAX_SIZE)) {
376 *mPtr = '\0';
377 }
378
379 ~MyString8() {
380 free(mPtr);
381 }
382
383 void append(const char *s) {
384 strcat(mPtr, s);
385 }
386
387 const char *string() const {
388 return mPtr;
389 }
390
391 size_t size() const {
392 return strlen(mPtr);
393 }
394
395private:
396 char *mPtr;
397
398 MyString8(const MyString8 &);
399 MyString8 &operator=(const MyString8 &);
400};
401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402void memStatus(int fd, const Vector<String16>& args)
403{
404 const size_t SIZE = 256;
405 char buffer[SIZE];
Andreas Huber27123462009-10-27 15:50:04 -0700406 MyString8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407
408 typedef struct {
409 size_t size;
410 size_t dups;
411 intptr_t * backtrace;
412 } AllocEntry;
413
414 uint8_t *info = NULL;
415 size_t overallSize = 0;
416 size_t infoSize = 0;
417 size_t totalMemory = 0;
418 size_t backtraceSize = 0;
419
420 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
421 if (info) {
422 uint8_t *ptr = info;
423 size_t count = overallSize / infoSize;
424
425 snprintf(buffer, SIZE, " Allocation count %i\n", count);
426 result.append(buffer);
James Dong3d23a612010-02-25 10:06:32 -0800427 snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
428 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429
430 AllocEntry * entries = new AllocEntry[count];
431
432 for (size_t i = 0; i < count; i++) {
433 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
434 AllocEntry *e = &entries[i];
435
436 e->size = *reinterpret_cast<size_t *>(ptr);
437 ptr += sizeof(size_t);
438
439 e->dups = *reinterpret_cast<size_t *>(ptr);
440 ptr += sizeof(size_t);
441
442 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
443 ptr += sizeof(intptr_t) * backtraceSize;
444 }
445
446 // Now we need to sort the entries. They come sorted by size but
447 // not by stack trace which causes problems using diff.
448 bool moved;
449 do {
450 moved = false;
451 for (size_t i = 0; i < (count - 1); i++) {
452 AllocEntry *e1 = &entries[i];
453 AllocEntry *e2 = &entries[i+1];
454
455 bool swap = e1->size < e2->size;
456 if (e1->size == e2->size) {
457 for(size_t j = 0; j < backtraceSize; j++) {
458 if (e1->backtrace[j] == e2->backtrace[j]) {
459 continue;
460 }
461 swap = e1->backtrace[j] < e2->backtrace[j];
462 break;
463 }
464 }
465 if (swap) {
466 AllocEntry t = entries[i];
467 entries[i] = entries[i+1];
468 entries[i+1] = t;
469 moved = true;
470 }
471 }
472 } while (moved);
473
474 for (size_t i = 0; i < count; i++) {
475 AllocEntry *e = &entries[i];
476
James Dong3d23a612010-02-25 10:06:32 -0800477 snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 result.append(buffer);
479 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
480 if (ct) {
481 result.append(", ");
482 }
483 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
484 result.append(buffer);
485 }
486 result.append("\n");
487 }
488
489 delete[] entries;
490 free_malloc_leak_info(info);
491 }
492
493 write(fd, result.string(), result.size());
494}
495#endif
496
497status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
498{
499 const size_t SIZE = 256;
500 char buffer[SIZE];
501 String8 result;
502 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
503 snprintf(buffer, SIZE, "Permission Denial: "
504 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
505 IPCThreadState::self()->getCallingPid(),
506 IPCThreadState::self()->getCallingUid());
507 result.append(buffer);
508 } else {
509 Mutex::Autolock lock(mLock);
510 for (int i = 0, n = mClients.size(); i < n; ++i) {
511 sp<Client> c = mClients[i].promote();
512 if (c != 0) c->dump(fd, args);
513 }
James Dong929642e2010-07-08 11:16:11 -0700514 if (mMediaRecorderClients.size() == 0) {
515 result.append(" No media recorder client\n\n");
516 } else {
517 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
518 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
519 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
520 result.append(buffer);
521 write(fd, result.string(), result.size());
522 result = "\n";
523 c->dump(fd, args);
524 }
Gloria Wang608a2632009-10-29 15:46:37 -0700525 }
526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 result.append(" Files opened and/or mapped:\n");
528 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
529 FILE *f = fopen(buffer, "r");
530 if (f) {
531 while (!feof(f)) {
532 fgets(buffer, SIZE, f);
533 if (strstr(buffer, " /sdcard/") ||
534 strstr(buffer, " /system/sounds/") ||
535 strstr(buffer, " /system/media/")) {
536 result.append(" ");
537 result.append(buffer);
538 }
539 }
540 fclose(f);
541 } else {
542 result.append("couldn't open ");
543 result.append(buffer);
544 result.append("\n");
545 }
546
547 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
548 DIR *d = opendir(buffer);
549 if (d) {
550 struct dirent *ent;
551 while((ent = readdir(d)) != NULL) {
552 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
553 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
554 struct stat s;
555 if (lstat(buffer, &s) == 0) {
556 if ((s.st_mode & S_IFMT) == S_IFLNK) {
557 char linkto[256];
558 int len = readlink(buffer, linkto, sizeof(linkto));
559 if(len > 0) {
560 if(len > 255) {
561 linkto[252] = '.';
562 linkto[253] = '.';
563 linkto[254] = '.';
564 linkto[255] = 0;
565 } else {
566 linkto[len] = 0;
567 }
568 if (strstr(linkto, "/sdcard/") == linkto ||
569 strstr(linkto, "/system/sounds/") == linkto ||
570 strstr(linkto, "/system/media/") == linkto) {
571 result.append(" ");
572 result.append(buffer);
573 result.append(" -> ");
574 result.append(linkto);
575 result.append("\n");
576 }
577 }
578 } else {
579 result.append(" unexpected type for ");
580 result.append(buffer);
581 result.append("\n");
582 }
583 }
584 }
585 }
586 closedir(d);
587 } else {
588 result.append("couldn't open ");
589 result.append(buffer);
590 result.append("\n");
591 }
592
593#if defined(__arm__)
594 bool dumpMem = false;
595 for (size_t i = 0; i < args.size(); i++) {
596 if (args[i] == String16("-m")) {
597 dumpMem = true;
598 }
599 }
600 if (dumpMem) {
601 memStatus(fd, args);
602 }
603#endif
604 }
605 write(fd, result.string(), result.size());
606 return NO_ERROR;
607}
608
609void MediaPlayerService::removeClient(wp<Client> client)
610{
611 Mutex::Autolock lock(mLock);
612 mClients.remove(client);
613}
614
615MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
Eric Laurent619346f2010-06-21 09:27:30 -0700616 int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617{
618 LOGV("Client(%d) constructor", connId);
619 mPid = pid;
620 mConnId = connId;
621 mService = service;
622 mClient = client;
623 mLoop = false;
624 mStatus = NO_INIT;
Eric Laurent619346f2010-06-21 09:27:30 -0700625 mAudioSessionId = audioSessionId;
626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627#if CALLBACK_ANTAGONIZER
628 LOGD("create Antagonizer");
629 mAntagonizer = new Antagonizer(notify, this);
630#endif
631}
632
633MediaPlayerService::Client::~Client()
634{
635 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
636 mAudioOutput.clear();
637 wp<Client> client(this);
638 disconnect();
639 mService->removeClient(client);
640}
641
642void MediaPlayerService::Client::disconnect()
643{
644 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
645 // grab local reference and clear main reference to prevent future
646 // access to object
647 sp<MediaPlayerBase> p;
648 {
649 Mutex::Autolock l(mLock);
650 p = mPlayer;
651 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700652 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 mPlayer.clear();
655
656 // clear the notification to prevent callbacks to dead client
657 // and reset the player. We assume the player will serialize
658 // access to itself if necessary.
659 if (p != 0) {
660 p->setNotifyCallback(0, 0);
661#if CALLBACK_ANTAGONIZER
662 LOGD("kill Antagonizer");
663 mAntagonizer->kill();
664#endif
665 p->reset();
666 }
667
668 IPCThreadState::self()->flushCommands();
669}
670
Andreas Huber0d596d42009-08-07 09:30:32 -0700671static player_type getDefaultPlayerType() {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700672 return STAGEFRIGHT_PLAYER;
Andreas Huber0d596d42009-08-07 09:30:32 -0700673}
674
James Dong392ff3b2009-09-06 14:29:45 -0700675player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676{
677 char buf[20];
678 lseek(fd, offset, SEEK_SET);
679 read(fd, buf, sizeof(buf));
680 lseek(fd, offset, SEEK_SET);
681
682 long ident = *((long*)buf);
683
684 // Ogg vorbis?
685 if (ident == 0x5367674f) // 'OggS'
Andreas Huber8d65dd22010-06-23 16:40:57 -0700686 return STAGEFRIGHT_PLAYER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800688#ifndef NO_OPENCORE
689 if (ident == 0x75b22630) {
690 // The magic number for .asf files, i.e. wmv and wma content.
691 // These are not currently supported through stagefright.
692 return PV_PLAYER;
693 }
694#endif
695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 // Some kind of MIDI?
697 EAS_DATA_HANDLE easdata;
698 if (EAS_Init(&easdata) == EAS_SUCCESS) {
699 EAS_FILE locator;
700 locator.path = NULL;
701 locator.fd = fd;
702 locator.offset = offset;
703 locator.length = length;
704 EAS_HANDLE eashandle;
705 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
706 EAS_CloseFile(easdata, eashandle);
707 EAS_Shutdown(easdata);
708 return SONIVOX_PLAYER;
709 }
710 EAS_Shutdown(easdata);
711 }
712
Andreas Huber0d596d42009-08-07 09:30:32 -0700713 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714}
715
James Dong392ff3b2009-09-06 14:29:45 -0700716player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700718 if (TestPlayerStub::canBeUsed(url)) {
719 return TEST_PLAYER;
720 }
721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 // use MidiFile for MIDI extensions
723 int lenURL = strlen(url);
724 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
725 int len = strlen(FILE_EXTS[i].extension);
726 int start = lenURL - len;
727 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900728 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber8d65dd22010-06-23 16:40:57 -0700729 return FILE_EXTS[i].playertype;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
731 }
732 }
733
James Dong42d66572010-04-13 21:33:26 -0700734 if (!strncasecmp(url, "rtsp://", 7)) {
Andreas Huber7a747b82010-06-07 15:19:40 -0700735 char value[PROPERTY_VALUE_MAX];
736 if (!property_get("media.stagefright.enable-rtsp", value, NULL)
737 || (strcmp(value, "1") && strcasecmp(value, "true"))) {
738 // For now, we're going to use PV for rtsp-based playback
739 // by default until we can clear up a few more issues.
740 return PV_PLAYER;
741 }
James Dong42d66572010-04-13 21:33:26 -0700742 }
743
Andreas Huber0d596d42009-08-07 09:30:32 -0700744 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745}
746
747static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
748 notify_callback_f notifyFunc)
749{
750 sp<MediaPlayerBase> p;
751 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700752#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 case PV_PLAYER:
754 LOGV(" create PVPlayer");
755 p = new PVPlayer();
756 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700757#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 case SONIVOX_PLAYER:
759 LOGV(" create MidiFile");
760 p = new MidiFile();
761 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700762 case STAGEFRIGHT_PLAYER:
763 LOGV(" create StagefrightPlayer");
764 p = new StagefrightPlayer;
765 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700766 case TEST_PLAYER:
767 LOGV("Create Test Player stub");
768 p = new TestPlayerStub();
769 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
771 if (p != NULL) {
772 if (p->initCheck() == NO_ERROR) {
773 p->setNotifyCallback(cookie, notifyFunc);
774 } else {
775 p.clear();
776 }
777 }
778 if (p == NULL) {
779 LOGE("Failed to create player object");
780 }
781 return p;
782}
783
784sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
785{
786 // determine if we have the right player type
787 sp<MediaPlayerBase> p = mPlayer;
788 if ((p != NULL) && (p->playerType() != playerType)) {
789 LOGV("delete player");
790 p.clear();
791 }
792 if (p == NULL) {
793 p = android::createPlayer(playerType, this, notify);
794 }
795 return p;
796}
797
Andreas Huber25643002010-01-28 11:19:57 -0800798status_t MediaPlayerService::Client::setDataSource(
799 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800{
801 LOGV("setDataSource(%s)", url);
802 if (url == NULL)
803 return UNKNOWN_ERROR;
804
805 if (strncmp(url, "content://", 10) == 0) {
806 // get a filedescriptor for the content Uri and
807 // pass it to the setDataSource(fd) method
808
809 String16 url16(url);
810 int fd = android::openContentProviderFile(url16);
811 if (fd < 0)
812 {
813 LOGE("Couldn't open fd for %s", url);
814 return UNKNOWN_ERROR;
815 }
816 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
817 close(fd);
818 return mStatus;
819 } else {
820 player_type playerType = getPlayerType(url);
821 LOGV("player type = %d", playerType);
822
823 // create the right type of player
824 sp<MediaPlayerBase> p = createPlayer(playerType);
825 if (p == NULL) return NO_INIT;
826
827 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700828 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
830 }
831
832 // now set data source
833 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800834 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700835 if (mStatus == NO_ERROR) {
836 mPlayer = p;
837 } else {
838 LOGE(" error: %d", mStatus);
839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 return mStatus;
841 }
842}
843
844status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
845{
846 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
847 struct stat sb;
848 int ret = fstat(fd, &sb);
849 if (ret != 0) {
850 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
851 return UNKNOWN_ERROR;
852 }
853
854 LOGV("st_dev = %llu", sb.st_dev);
855 LOGV("st_mode = %u", sb.st_mode);
856 LOGV("st_uid = %lu", sb.st_uid);
857 LOGV("st_gid = %lu", sb.st_gid);
858 LOGV("st_size = %llu", sb.st_size);
859
860 if (offset >= sb.st_size) {
861 LOGE("offset error");
862 ::close(fd);
863 return UNKNOWN_ERROR;
864 }
865 if (offset + length > sb.st_size) {
866 length = sb.st_size - offset;
867 LOGV("calculated length = %lld", length);
868 }
869
870 player_type playerType = getPlayerType(fd, offset, length);
871 LOGV("player type = %d", playerType);
872
873 // create the right type of player
874 sp<MediaPlayerBase> p = createPlayer(playerType);
875 if (p == NULL) return NO_INIT;
876
877 if (!p->hardwareOutput()) {
Eric Laurent619346f2010-06-21 09:27:30 -0700878 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
880 }
881
882 // now set data source
883 mStatus = p->setDataSource(fd, offset, length);
884 if (mStatus == NO_ERROR) mPlayer = p;
885 return mStatus;
886}
887
888status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
889{
890 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
891 sp<MediaPlayerBase> p = getPlayer();
892 if (p == 0) return UNKNOWN_ERROR;
893 return p->setVideoSurface(surface);
894}
895
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700896status_t MediaPlayerService::Client::invoke(const Parcel& request,
897 Parcel *reply)
898{
899 sp<MediaPlayerBase> p = getPlayer();
900 if (p == NULL) return UNKNOWN_ERROR;
901 return p->invoke(request, reply);
902}
903
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700904// This call doesn't need to access the native player.
905status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
906{
907 status_t status;
nikobc726922009-07-20 15:07:26 -0700908 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700909
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700910 if (unmarshallFilter(filter, &allow, &status) &&
911 unmarshallFilter(filter, &drop, &status)) {
912 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700913
914 mMetadataAllow = allow;
915 mMetadataDrop = drop;
916 }
917 return status;
918}
919
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700920status_t MediaPlayerService::Client::getMetadata(
921 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700922{
nikobc726922009-07-20 15:07:26 -0700923 sp<MediaPlayerBase> player = getPlayer();
924 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700925
niko89948372009-07-16 16:39:53 -0700926 status_t status;
927 // Placeholder for the return code, updated by the caller.
928 reply->writeInt32(-1);
929
nikobc726922009-07-20 15:07:26 -0700930 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700931
932 // We don't block notifications while we fetch the data. We clear
933 // mMetadataUpdated first so we don't lose notifications happening
934 // during the rest of this call.
935 {
936 Mutex::Autolock lock(mLock);
937 if (update_only) {
niko89948372009-07-16 16:39:53 -0700938 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700939 }
940 mMetadataUpdated.clear();
941 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700942
nikobc726922009-07-20 15:07:26 -0700943 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700944
nikobc726922009-07-20 15:07:26 -0700945 metadata.appendHeader();
946 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700947
948 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700949 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700950 LOGE("getMetadata failed %d", status);
951 return status;
952 }
953
954 // FIXME: Implement filtering on the result. Not critical since
955 // filtering takes place on the update notifications already. This
956 // would be when all the metadata are fetch and a filter is set.
957
niko89948372009-07-16 16:39:53 -0700958 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700959 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700960 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700961}
962
Andreas Huberfbb38852010-02-12 12:35:58 -0800963status_t MediaPlayerService::Client::suspend() {
964 sp<MediaPlayerBase> p = getPlayer();
965 if (p == 0) return UNKNOWN_ERROR;
966
967 return p->suspend();
968}
969
970status_t MediaPlayerService::Client::resume() {
971 sp<MediaPlayerBase> p = getPlayer();
972 if (p == 0) return UNKNOWN_ERROR;
973
974 return p->resume();
975}
976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977status_t MediaPlayerService::Client::prepareAsync()
978{
979 LOGV("[%d] prepareAsync", mConnId);
980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == 0) return UNKNOWN_ERROR;
982 status_t ret = p->prepareAsync();
983#if CALLBACK_ANTAGONIZER
984 LOGD("start Antagonizer");
985 if (ret == NO_ERROR) mAntagonizer->start();
986#endif
987 return ret;
988}
989
990status_t MediaPlayerService::Client::start()
991{
992 LOGV("[%d] start", mConnId);
993 sp<MediaPlayerBase> p = getPlayer();
994 if (p == 0) return UNKNOWN_ERROR;
995 p->setLooping(mLoop);
996 return p->start();
997}
998
999status_t MediaPlayerService::Client::stop()
1000{
1001 LOGV("[%d] stop", mConnId);
1002 sp<MediaPlayerBase> p = getPlayer();
1003 if (p == 0) return UNKNOWN_ERROR;
1004 return p->stop();
1005}
1006
1007status_t MediaPlayerService::Client::pause()
1008{
1009 LOGV("[%d] pause", mConnId);
1010 sp<MediaPlayerBase> p = getPlayer();
1011 if (p == 0) return UNKNOWN_ERROR;
1012 return p->pause();
1013}
1014
1015status_t MediaPlayerService::Client::isPlaying(bool* state)
1016{
1017 *state = false;
1018 sp<MediaPlayerBase> p = getPlayer();
1019 if (p == 0) return UNKNOWN_ERROR;
1020 *state = p->isPlaying();
1021 LOGV("[%d] isPlaying: %d", mConnId, *state);
1022 return NO_ERROR;
1023}
1024
1025status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1026{
1027 LOGV("getCurrentPosition");
1028 sp<MediaPlayerBase> p = getPlayer();
1029 if (p == 0) return UNKNOWN_ERROR;
1030 status_t ret = p->getCurrentPosition(msec);
1031 if (ret == NO_ERROR) {
1032 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1033 } else {
1034 LOGE("getCurrentPosition returned %d", ret);
1035 }
1036 return ret;
1037}
1038
1039status_t MediaPlayerService::Client::getDuration(int *msec)
1040{
1041 LOGV("getDuration");
1042 sp<MediaPlayerBase> p = getPlayer();
1043 if (p == 0) return UNKNOWN_ERROR;
1044 status_t ret = p->getDuration(msec);
1045 if (ret == NO_ERROR) {
1046 LOGV("[%d] getDuration = %d", mConnId, *msec);
1047 } else {
1048 LOGE("getDuration returned %d", ret);
1049 }
1050 return ret;
1051}
1052
1053status_t MediaPlayerService::Client::seekTo(int msec)
1054{
1055 LOGV("[%d] seekTo(%d)", mConnId, msec);
1056 sp<MediaPlayerBase> p = getPlayer();
1057 if (p == 0) return UNKNOWN_ERROR;
1058 return p->seekTo(msec);
1059}
1060
1061status_t MediaPlayerService::Client::reset()
1062{
1063 LOGV("[%d] reset", mConnId);
1064 sp<MediaPlayerBase> p = getPlayer();
1065 if (p == 0) return UNKNOWN_ERROR;
1066 return p->reset();
1067}
1068
1069status_t MediaPlayerService::Client::setAudioStreamType(int type)
1070{
1071 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1072 // TODO: for hardware output, call player instead
1073 Mutex::Autolock l(mLock);
1074 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1075 return NO_ERROR;
1076}
1077
1078status_t MediaPlayerService::Client::setLooping(int loop)
1079{
1080 LOGV("[%d] setLooping(%d)", mConnId, loop);
1081 mLoop = loop;
1082 sp<MediaPlayerBase> p = getPlayer();
1083 if (p != 0) return p->setLooping(loop);
1084 return NO_ERROR;
1085}
1086
1087status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1088{
1089 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1090 // TODO: for hardware output, call player instead
1091 Mutex::Autolock l(mLock);
1092 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1093 return NO_ERROR;
1094}
1095
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1098{
1099 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001100
1101 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001102 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001103 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001104
1105 if(client->shouldDropMetadata(metadata_type)) {
1106 return;
1107 }
1108
1109 // Update the list of metadata that have changed. getMetadata
1110 // also access mMetadataUpdated and clears it.
1111 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1114 client->mClient->notify(msg, ext1, ext2);
1115}
1116
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001117
nikobc726922009-07-20 15:07:26 -07001118bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001119{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001120 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001121
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001122 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001123 return true;
1124 }
1125
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001126 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001127 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001128 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001129 return true;
1130 }
1131}
1132
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001133
nikobc726922009-07-20 15:07:26 -07001134void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001135 Mutex::Autolock lock(mLock);
1136 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1137 mMetadataUpdated.add(metadata_type);
1138 }
1139}
1140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141#if CALLBACK_ANTAGONIZER
1142const int Antagonizer::interval = 10000; // 10 msecs
1143
1144Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1145 mExit(false), mActive(false), mClient(client), mCb(cb)
1146{
1147 createThread(callbackThread, this);
1148}
1149
1150void Antagonizer::kill()
1151{
1152 Mutex::Autolock _l(mLock);
1153 mActive = false;
1154 mExit = true;
1155 mCondition.wait(mLock);
1156}
1157
1158int Antagonizer::callbackThread(void* user)
1159{
1160 LOGD("Antagonizer started");
1161 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1162 while (!p->mExit) {
1163 if (p->mActive) {
1164 LOGV("send event");
1165 p->mCb(p->mClient, 0, 0, 0);
1166 }
1167 usleep(interval);
1168 }
1169 Mutex::Autolock _l(p->mLock);
1170 p->mCondition.signal();
1171 LOGD("Antagonizer stopped");
1172 return 0;
1173}
1174#endif
1175
1176static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1177
1178sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1179{
1180 LOGV("decode(%s)", url);
1181 sp<MemoryBase> mem;
1182 sp<MediaPlayerBase> player;
1183
1184 // Protect our precious, precious DRMd ringtones by only allowing
1185 // decoding of http, but not filesystem paths or content Uris.
1186 // If the application wants to decode those, it should open a
1187 // filedescriptor for them and use that.
1188 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1189 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1190 return mem;
1191 }
1192
1193 player_type playerType = getPlayerType(url);
1194 LOGV("player type = %d", playerType);
1195
1196 // create the right type of player
1197 sp<AudioCache> cache = new AudioCache(url);
1198 player = android::createPlayer(playerType, cache.get(), cache->notify);
1199 if (player == NULL) goto Exit;
1200 if (player->hardwareOutput()) goto Exit;
1201
1202 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1203
1204 // set data source
1205 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1206
1207 LOGV("prepare");
1208 player->prepareAsync();
1209
1210 LOGV("wait for prepare");
1211 if (cache->wait() != NO_ERROR) goto Exit;
1212
1213 LOGV("start");
1214 player->start();
1215
1216 LOGV("wait for playback complete");
1217 if (cache->wait() != NO_ERROR) goto Exit;
1218
1219 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1220 *pSampleRate = cache->sampleRate();
1221 *pNumChannels = cache->channelCount();
1222 *pFormat = cache->format();
1223 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1224
1225Exit:
1226 if (player != 0) player->reset();
1227 return mem;
1228}
1229
1230sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1231{
1232 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1233 sp<MemoryBase> mem;
1234 sp<MediaPlayerBase> player;
1235
1236 player_type playerType = getPlayerType(fd, offset, length);
1237 LOGV("player type = %d", playerType);
1238
1239 // create the right type of player
1240 sp<AudioCache> cache = new AudioCache("decode_fd");
1241 player = android::createPlayer(playerType, cache.get(), cache->notify);
1242 if (player == NULL) goto Exit;
1243 if (player->hardwareOutput()) goto Exit;
1244
1245 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1246
1247 // set data source
1248 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1249
1250 LOGV("prepare");
1251 player->prepareAsync();
1252
1253 LOGV("wait for prepare");
1254 if (cache->wait() != NO_ERROR) goto Exit;
1255
1256 LOGV("start");
1257 player->start();
1258
1259 LOGV("wait for playback complete");
1260 if (cache->wait() != NO_ERROR) goto Exit;
1261
1262 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1263 *pSampleRate = cache->sampleRate();
1264 *pNumChannels = cache->channelCount();
1265 *pFormat = cache->format();
1266 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1267
1268Exit:
1269 if (player != 0) player->reset();
1270 ::close(fd);
1271 return mem;
1272}
1273
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275#undef LOG_TAG
1276#define LOG_TAG "AudioSink"
Eric Laurent619346f2010-06-21 09:27:30 -07001277MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Hubere46b7be2009-07-14 16:56:47 -07001278 : mCallback(NULL),
Eric Laurent619346f2010-06-21 09:27:30 -07001279 mCallbackCookie(NULL),
1280 mSessionId(sessionId) {
1281 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 mTrack = 0;
1283 mStreamType = AudioSystem::MUSIC;
1284 mLeftVolume = 1.0;
1285 mRightVolume = 1.0;
1286 mLatency = 0;
1287 mMsecsPerFrame = 0;
1288 setMinBufferCount();
1289}
1290
1291MediaPlayerService::AudioOutput::~AudioOutput()
1292{
1293 close();
1294}
1295
1296void MediaPlayerService::AudioOutput::setMinBufferCount()
1297{
1298 char value[PROPERTY_VALUE_MAX];
1299 if (property_get("ro.kernel.qemu", value, 0)) {
1300 mIsOnEmulator = true;
1301 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1302 }
1303}
1304
1305bool MediaPlayerService::AudioOutput::isOnEmulator()
1306{
1307 setMinBufferCount();
1308 return mIsOnEmulator;
1309}
1310
1311int MediaPlayerService::AudioOutput::getMinBufferCount()
1312{
1313 setMinBufferCount();
1314 return mMinBufferCount;
1315}
1316
1317ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1318{
1319 if (mTrack == 0) return NO_INIT;
1320 return mTrack->frameCount() * frameSize();
1321}
1322
1323ssize_t MediaPlayerService::AudioOutput::frameCount() const
1324{
1325 if (mTrack == 0) return NO_INIT;
1326 return mTrack->frameCount();
1327}
1328
1329ssize_t MediaPlayerService::AudioOutput::channelCount() const
1330{
1331 if (mTrack == 0) return NO_INIT;
1332 return mTrack->channelCount();
1333}
1334
1335ssize_t MediaPlayerService::AudioOutput::frameSize() const
1336{
1337 if (mTrack == 0) return NO_INIT;
1338 return mTrack->frameSize();
1339}
1340
1341uint32_t MediaPlayerService::AudioOutput::latency () const
1342{
1343 return mLatency;
1344}
1345
1346float MediaPlayerService::AudioOutput::msecsPerFrame() const
1347{
1348 return mMsecsPerFrame;
1349}
1350
Eric Laurent0986e792010-01-19 17:37:09 -08001351status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1352{
1353 if (mTrack == 0) return NO_INIT;
1354 return mTrack->getPosition(position);
1355}
1356
Andreas Hubere46b7be2009-07-14 16:56:47 -07001357status_t MediaPlayerService::AudioOutput::open(
1358 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1359 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001361 mCallback = cb;
1362 mCallbackCookie = cookie;
1363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 // Check argument "bufferCount" against the mininum buffer count
1365 if (bufferCount < mMinBufferCount) {
1366 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1367 bufferCount = mMinBufferCount;
1368
1369 }
Eric Laurent619346f2010-06-21 09:27:30 -07001370 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 if (mTrack) close();
1372 int afSampleRate;
1373 int afFrameCount;
1374 int frameCount;
1375
1376 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1377 return NO_INIT;
1378 }
1379 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1380 return NO_INIT;
1381 }
1382
1383 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001384
1385 AudioTrack *t;
1386 if (mCallback != NULL) {
1387 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001388 mStreamType,
1389 sampleRate,
1390 format,
1391 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1392 frameCount,
1393 0 /* flags */,
1394 CallbackWrapper,
Eric Laurent619346f2010-06-21 09:27:30 -07001395 this,
1396 0,
1397 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001398 } else {
1399 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001400 mStreamType,
1401 sampleRate,
1402 format,
1403 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
Eric Laurent619346f2010-06-21 09:27:30 -07001404 frameCount,
1405 0,
1406 NULL,
1407 NULL,
1408 0,
1409 mSessionId);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1413 LOGE("Unable to create audio track");
1414 delete t;
1415 return NO_INIT;
1416 }
1417
1418 LOGV("setVolume");
1419 t->setVolume(mLeftVolume, mRightVolume);
1420 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001421 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 mTrack = t;
1423 return NO_ERROR;
1424}
1425
1426void MediaPlayerService::AudioOutput::start()
1427{
1428 LOGV("start");
1429 if (mTrack) {
1430 mTrack->setVolume(mLeftVolume, mRightVolume);
1431 mTrack->start();
1432 }
1433}
1434
Marco Nelissene274db12010-01-12 09:23:54 -08001435
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1438{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001439 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001442 if (mTrack) {
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001443 ssize_t ret = mTrack->write(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001444 return ret;
1445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 return NO_INIT;
1447}
1448
1449void MediaPlayerService::AudioOutput::stop()
1450{
1451 LOGV("stop");
1452 if (mTrack) mTrack->stop();
1453}
1454
1455void MediaPlayerService::AudioOutput::flush()
1456{
1457 LOGV("flush");
1458 if (mTrack) mTrack->flush();
1459}
1460
1461void MediaPlayerService::AudioOutput::pause()
1462{
1463 LOGV("pause");
1464 if (mTrack) mTrack->pause();
1465}
1466
1467void MediaPlayerService::AudioOutput::close()
1468{
1469 LOGV("close");
1470 delete mTrack;
1471 mTrack = 0;
1472}
1473
1474void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1475{
1476 LOGV("setVolume(%f, %f)", left, right);
1477 mLeftVolume = left;
1478 mRightVolume = right;
1479 if (mTrack) {
1480 mTrack->setVolume(left, right);
1481 }
1482}
1483
Andreas Hubere46b7be2009-07-14 16:56:47 -07001484// static
1485void MediaPlayerService::AudioOutput::CallbackWrapper(
1486 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001487 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001488 if (event != AudioTrack::EVENT_MORE_DATA) {
1489 return;
1490 }
1491
1492 AudioOutput *me = (AudioOutput *)cookie;
1493 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1494
Andreas Huber6ed937e2010-02-09 16:59:18 -08001495 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001496 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001497
Andreas Huber406a18b2010-02-18 16:45:13 -08001498 buffer->size = actualSize;
1499
Andreas Hubere46b7be2009-07-14 16:56:47 -07001500}
1501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502#undef LOG_TAG
1503#define LOG_TAG "AudioCache"
1504MediaPlayerService::AudioCache::AudioCache(const char* name) :
1505 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1506 mError(NO_ERROR), mCommandComplete(false)
1507{
1508 // create ashmem heap
1509 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1510}
1511
1512uint32_t MediaPlayerService::AudioCache::latency () const
1513{
1514 return 0;
1515}
1516
1517float MediaPlayerService::AudioCache::msecsPerFrame() const
1518{
1519 return mMsecsPerFrame;
1520}
1521
Eric Laurent0986e792010-01-19 17:37:09 -08001522status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1523{
1524 if (position == 0) return BAD_VALUE;
1525 *position = mSize;
1526 return NO_ERROR;
1527}
1528
Andreas Huber6ed937e2010-02-09 16:59:18 -08001529////////////////////////////////////////////////////////////////////////////////
1530
1531struct CallbackThread : public Thread {
1532 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1533 MediaPlayerBase::AudioSink::AudioCallback cb,
1534 void *cookie);
1535
1536protected:
1537 virtual ~CallbackThread();
1538
1539 virtual bool threadLoop();
1540
1541private:
1542 wp<MediaPlayerBase::AudioSink> mSink;
1543 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1544 void *mCookie;
1545 void *mBuffer;
1546 size_t mBufferSize;
1547
1548 CallbackThread(const CallbackThread &);
1549 CallbackThread &operator=(const CallbackThread &);
1550};
1551
1552CallbackThread::CallbackThread(
1553 const wp<MediaPlayerBase::AudioSink> &sink,
1554 MediaPlayerBase::AudioSink::AudioCallback cb,
1555 void *cookie)
1556 : mSink(sink),
1557 mCallback(cb),
1558 mCookie(cookie),
1559 mBuffer(NULL),
1560 mBufferSize(0) {
1561}
1562
1563CallbackThread::~CallbackThread() {
1564 if (mBuffer) {
1565 free(mBuffer);
1566 mBuffer = NULL;
1567 }
1568}
1569
1570bool CallbackThread::threadLoop() {
1571 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1572 if (sink == NULL) {
1573 return false;
1574 }
1575
1576 if (mBuffer == NULL) {
1577 mBufferSize = sink->bufferSize();
1578 mBuffer = malloc(mBufferSize);
1579 }
1580
1581 size_t actualSize =
1582 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1583
1584 if (actualSize > 0) {
1585 sink->write(mBuffer, actualSize);
1586 }
1587
1588 return true;
1589}
1590
1591////////////////////////////////////////////////////////////////////////////////
1592
Andreas Hubere46b7be2009-07-14 16:56:47 -07001593status_t MediaPlayerService::AudioCache::open(
1594 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1595 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596{
Dave Sparks14f89402009-12-09 20:20:26 -08001597 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001598 if (mHeap->getHeapID() < 0) {
1599 return NO_INIT;
1600 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 mSampleRate = sampleRate;
1603 mChannelCount = (uint16_t)channelCount;
1604 mFormat = (uint16_t)format;
1605 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001606
1607 if (cb != NULL) {
1608 mCallbackThread = new CallbackThread(this, cb, cookie);
1609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 return NO_ERROR;
1611}
1612
Andreas Huber6ed937e2010-02-09 16:59:18 -08001613void MediaPlayerService::AudioCache::start() {
1614 if (mCallbackThread != NULL) {
1615 mCallbackThread->run("AudioCache callback");
1616 }
1617}
1618
1619void MediaPlayerService::AudioCache::stop() {
1620 if (mCallbackThread != NULL) {
1621 mCallbackThread->requestExitAndWait();
1622 }
1623}
1624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1626{
1627 LOGV("write(%p, %u)", buffer, size);
1628 if ((buffer == 0) || (size == 0)) return size;
1629
1630 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1631 if (p == NULL) return NO_INIT;
1632 p += mSize;
1633 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1634 if (mSize + size > mHeap->getSize()) {
1635 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1636 size = mHeap->getSize() - mSize;
1637 }
1638 memcpy(p, buffer, size);
1639 mSize += size;
1640 return size;
1641}
1642
1643// call with lock held
1644status_t MediaPlayerService::AudioCache::wait()
1645{
1646 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001647 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 mSignal.wait(mLock);
1649 }
1650 mCommandComplete = false;
1651
1652 if (mError == NO_ERROR) {
1653 LOGV("wait - success");
1654 } else {
1655 LOGV("wait - error");
1656 }
1657 return mError;
1658}
1659
1660void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1661{
1662 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1663 AudioCache* p = static_cast<AudioCache*>(cookie);
1664
1665 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001666 switch (msg)
1667 {
1668 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 LOGE("Error %d, %d occurred", ext1, ext2);
1670 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001671 break;
1672 case MEDIA_PREPARED:
1673 LOGV("prepared");
1674 break;
1675 case MEDIA_PLAYBACK_COMPLETE:
1676 LOGV("playback complete");
1677 break;
1678 default:
1679 LOGV("ignored");
1680 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
1683 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001684 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 p->mCommandComplete = true;
1686 p->mSignal.signal();
1687}
1688
nikobc726922009-07-20 15:07:26 -07001689} // namespace android