blob: a4e3601cdf93afecb27b31bf983d5159d8ab7962 [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"
59#include "VorbisPlayer.h"
60#include <media/PVPlayer.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070061#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070062#include "StagefrightPlayer.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070063
Andreas Hubere46b7be2009-07-14 16:56:47 -070064#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066/* desktop Linux needs a little help with gettid() */
67#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
68#define __KERNEL__
69# include <linux/unistd.h>
70#ifdef _syscall0
71_syscall0(pid_t,gettid)
72#else
73pid_t gettid() { return syscall(__NR_gettid);}
74#endif
75#undef __KERNEL__
76#endif
77
Nicolas Cataniab2c69392009-07-08 08:57:42 -070078namespace {
nikobc726922009-07-20 15:07:26 -070079using android::media::Metadata;
Nicolas Cataniab2c69392009-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 Cataniab2c69392009-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
nikobc726922009-07-20 15:07:26 -070089// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070090
Nicolas Cataniab2c69392009-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,
nikobc726922009-07-20 15:07:26 -0700114 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700115 status_t *status)
116{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700117 int32_t val;
118 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-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 Catania4df8b2c2009-07-10 13:53:06 -0700125 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700126 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700127 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700128 *status = BAD_VALUE;
129 return false;
130 }
131
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700132 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700133
134 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700135 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700136
nikobc726922009-07-20 15:07:26 -0700137 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700138
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700139
140 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700141 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700142 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700143 *status = NOT_ENOUGH_DATA;
144 return false;
145 }
146
nikobc726922009-07-20 15:07:26 -0700147 const Metadata::Type *data =
148 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700149
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700150 if (NULL == data)
Nicolas Cataniab2c69392009-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 Catania4df8b2c2009-07-10 13:53:06 -0700160 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700161 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700162 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700163 ++data;
164 }
165 *status = OK;
166 return true;
167}
168
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700169// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700170// @param val To be searched.
171// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700172bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700173{
174 // Deal with empty and ANY right away
175 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700176 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700177
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700178 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700179}
180
181} // anonymous namespace
182
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184namespace android {
185
186// TODO: Temp hack until we can register players
187typedef struct {
188 const char *extension;
189 const player_type playertype;
190} extmap;
191extmap FILE_EXTS [] = {
192 {".mid", SONIVOX_PLAYER},
193 {".midi", SONIVOX_PLAYER},
194 {".smf", SONIVOX_PLAYER},
195 {".xmf", SONIVOX_PLAYER},
196 {".imy", SONIVOX_PLAYER},
197 {".rtttl", SONIVOX_PLAYER},
198 {".rtx", SONIVOX_PLAYER},
199 {".ota", SONIVOX_PLAYER},
200 {".ogg", VORBIS_PLAYER},
201 {".oga", VORBIS_PLAYER},
202};
203
204// 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 -0800205/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
206/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
207
208void MediaPlayerService::instantiate() {
209 defaultServiceManager()->addService(
210 String16("media.player"), new MediaPlayerService());
211}
212
213MediaPlayerService::MediaPlayerService()
214{
215 LOGV("MediaPlayerService created");
216 mNextConnId = 1;
217}
218
219MediaPlayerService::~MediaPlayerService()
220{
221 LOGV("MediaPlayerService destroyed");
222}
223
224sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
225{
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700226#ifndef NO_OPENCORE
Gloria Wang608a2632009-10-29 15:46:37 -0700227 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
228 wp<MediaRecorderClient> w = recorder;
229 Mutex::Autolock lock(mLock);
230 mMediaRecorderClients.add(w);
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700231#else
232 sp<MediaRecorderClient> recorder = NULL;
233#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 LOGV("Create new media recorder client from pid %d", pid);
235 return recorder;
236}
237
Gloria Wang608a2632009-10-29 15:46:37 -0700238void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
239{
240 Mutex::Autolock lock(mLock);
241 mMediaRecorderClients.remove(client);
242 LOGV("Delete media recorder client");
243}
244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
246{
247 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
248 LOGV("Create new media retriever from pid %d", pid);
249 return retriever;
250}
251
252sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url)
253{
254 int32_t connId = android_atomic_inc(&mNextConnId);
255 sp<Client> c = new Client(this, pid, connId, client);
256 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
257 if (NO_ERROR != c->setDataSource(url))
258 {
259 c.clear();
260 return c;
261 }
262 wp<Client> w = c;
263 Mutex::Autolock lock(mLock);
264 mClients.add(w);
265 return c;
266}
267
268sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
269 int fd, int64_t offset, int64_t length)
270{
271 int32_t connId = android_atomic_inc(&mNextConnId);
272 sp<Client> c = new Client(this, pid, connId, client);
273 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
274 connId, pid, fd, offset, length);
275 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
276 c.clear();
277 } else {
278 wp<Client> w = c;
279 Mutex::Autolock lock(mLock);
280 mClients.add(w);
281 }
282 ::close(fd);
283 return c;
284}
285
Andreas Huber784202e2009-10-15 13:46:54 -0700286sp<IOMX> MediaPlayerService::getOMX() {
287 Mutex::Autolock autoLock(mLock);
288
289 if (mOMX.get() == NULL) {
290 mOMX = new OMX;
291 }
292
293 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700294}
295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
297{
298 const size_t SIZE = 256;
299 char buffer[SIZE];
300 String8 result;
301
302 result.append(" AudioCache\n");
303 if (mHeap != 0) {
304 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
305 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
306 result.append(buffer);
307 }
308 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
309 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
310 result.append(buffer);
311 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
312 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
313 result.append(buffer);
314 ::write(fd, result.string(), result.size());
315 return NO_ERROR;
316}
317
318status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
319{
320 const size_t SIZE = 256;
321 char buffer[SIZE];
322 String8 result;
323
324 result.append(" AudioOutput\n");
325 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
326 mStreamType, mLeftVolume, mRightVolume);
327 result.append(buffer);
328 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
329 mMsecsPerFrame, mLatency);
330 result.append(buffer);
331 ::write(fd, result.string(), result.size());
332 if (mTrack != 0) {
333 mTrack->dump(fd, args);
334 }
335 return NO_ERROR;
336}
337
338status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
339{
340 const size_t SIZE = 256;
341 char buffer[SIZE];
342 String8 result;
343 result.append(" Client\n");
344 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
345 mPid, mConnId, mStatus, mLoop?"true": "false");
346 result.append(buffer);
347 write(fd, result.string(), result.size());
348 if (mAudioOutput != 0) {
349 mAudioOutput->dump(fd, args);
350 }
351 write(fd, "\n", 1);
352 return NO_ERROR;
353}
354
355static int myTid() {
356#ifdef HAVE_GETTID
357 return gettid();
358#else
359 return getpid();
360#endif
361}
362
363#if defined(__arm__)
364extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
365 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
366extern "C" void free_malloc_leak_info(uint8_t* info);
367
Andreas Huber27123462009-10-27 15:50:04 -0700368// Use the String-class below instead of String8 to allocate all memory
369// beforehand and not reenter the heap while we are examining it...
370struct MyString8 {
371 static const size_t MAX_SIZE = 256 * 1024;
372
373 MyString8()
374 : mPtr((char *)malloc(MAX_SIZE)) {
375 *mPtr = '\0';
376 }
377
378 ~MyString8() {
379 free(mPtr);
380 }
381
382 void append(const char *s) {
383 strcat(mPtr, s);
384 }
385
386 const char *string() const {
387 return mPtr;
388 }
389
390 size_t size() const {
391 return strlen(mPtr);
392 }
393
394private:
395 char *mPtr;
396
397 MyString8(const MyString8 &);
398 MyString8 &operator=(const MyString8 &);
399};
400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401void memStatus(int fd, const Vector<String16>& args)
402{
403 const size_t SIZE = 256;
404 char buffer[SIZE];
Andreas Huber27123462009-10-27 15:50:04 -0700405 MyString8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
407 typedef struct {
408 size_t size;
409 size_t dups;
410 intptr_t * backtrace;
411 } AllocEntry;
412
413 uint8_t *info = NULL;
414 size_t overallSize = 0;
415 size_t infoSize = 0;
416 size_t totalMemory = 0;
417 size_t backtraceSize = 0;
418
419 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
420 if (info) {
421 uint8_t *ptr = info;
422 size_t count = overallSize / infoSize;
423
424 snprintf(buffer, SIZE, " Allocation count %i\n", count);
425 result.append(buffer);
426
427 AllocEntry * entries = new AllocEntry[count];
428
429 for (size_t i = 0; i < count; i++) {
430 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
431 AllocEntry *e = &entries[i];
432
433 e->size = *reinterpret_cast<size_t *>(ptr);
434 ptr += sizeof(size_t);
435
436 e->dups = *reinterpret_cast<size_t *>(ptr);
437 ptr += sizeof(size_t);
438
439 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
440 ptr += sizeof(intptr_t) * backtraceSize;
441 }
442
443 // Now we need to sort the entries. They come sorted by size but
444 // not by stack trace which causes problems using diff.
445 bool moved;
446 do {
447 moved = false;
448 for (size_t i = 0; i < (count - 1); i++) {
449 AllocEntry *e1 = &entries[i];
450 AllocEntry *e2 = &entries[i+1];
451
452 bool swap = e1->size < e2->size;
453 if (e1->size == e2->size) {
454 for(size_t j = 0; j < backtraceSize; j++) {
455 if (e1->backtrace[j] == e2->backtrace[j]) {
456 continue;
457 }
458 swap = e1->backtrace[j] < e2->backtrace[j];
459 break;
460 }
461 }
462 if (swap) {
463 AllocEntry t = entries[i];
464 entries[i] = entries[i+1];
465 entries[i+1] = t;
466 moved = true;
467 }
468 }
469 } while (moved);
470
471 for (size_t i = 0; i < count; i++) {
472 AllocEntry *e = &entries[i];
473
474 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
475 result.append(buffer);
476 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
477 if (ct) {
478 result.append(", ");
479 }
480 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
481 result.append(buffer);
482 }
483 result.append("\n");
484 }
485
486 delete[] entries;
487 free_malloc_leak_info(info);
488 }
489
490 write(fd, result.string(), result.size());
491}
492#endif
493
494status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
495{
496 const size_t SIZE = 256;
497 char buffer[SIZE];
498 String8 result;
499 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
500 snprintf(buffer, SIZE, "Permission Denial: "
501 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
502 IPCThreadState::self()->getCallingPid(),
503 IPCThreadState::self()->getCallingUid());
504 result.append(buffer);
505 } else {
506 Mutex::Autolock lock(mLock);
507 for (int i = 0, n = mClients.size(); i < n; ++i) {
508 sp<Client> c = mClients[i].promote();
509 if (c != 0) c->dump(fd, args);
510 }
Gloria Wang608a2632009-10-29 15:46:37 -0700511 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
512 result.append(" MediaRecorderClient\n");
513 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
514 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid);
515 result.append(buffer);
516 }
517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 result.append(" Files opened and/or mapped:\n");
519 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
520 FILE *f = fopen(buffer, "r");
521 if (f) {
522 while (!feof(f)) {
523 fgets(buffer, SIZE, f);
524 if (strstr(buffer, " /sdcard/") ||
525 strstr(buffer, " /system/sounds/") ||
526 strstr(buffer, " /system/media/")) {
527 result.append(" ");
528 result.append(buffer);
529 }
530 }
531 fclose(f);
532 } else {
533 result.append("couldn't open ");
534 result.append(buffer);
535 result.append("\n");
536 }
537
538 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
539 DIR *d = opendir(buffer);
540 if (d) {
541 struct dirent *ent;
542 while((ent = readdir(d)) != NULL) {
543 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
544 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
545 struct stat s;
546 if (lstat(buffer, &s) == 0) {
547 if ((s.st_mode & S_IFMT) == S_IFLNK) {
548 char linkto[256];
549 int len = readlink(buffer, linkto, sizeof(linkto));
550 if(len > 0) {
551 if(len > 255) {
552 linkto[252] = '.';
553 linkto[253] = '.';
554 linkto[254] = '.';
555 linkto[255] = 0;
556 } else {
557 linkto[len] = 0;
558 }
559 if (strstr(linkto, "/sdcard/") == linkto ||
560 strstr(linkto, "/system/sounds/") == linkto ||
561 strstr(linkto, "/system/media/") == linkto) {
562 result.append(" ");
563 result.append(buffer);
564 result.append(" -> ");
565 result.append(linkto);
566 result.append("\n");
567 }
568 }
569 } else {
570 result.append(" unexpected type for ");
571 result.append(buffer);
572 result.append("\n");
573 }
574 }
575 }
576 }
577 closedir(d);
578 } else {
579 result.append("couldn't open ");
580 result.append(buffer);
581 result.append("\n");
582 }
583
584#if defined(__arm__)
585 bool dumpMem = false;
586 for (size_t i = 0; i < args.size(); i++) {
587 if (args[i] == String16("-m")) {
588 dumpMem = true;
589 }
590 }
591 if (dumpMem) {
592 memStatus(fd, args);
593 }
594#endif
595 }
596 write(fd, result.string(), result.size());
597 return NO_ERROR;
598}
599
600void MediaPlayerService::removeClient(wp<Client> client)
601{
602 Mutex::Autolock lock(mLock);
603 mClients.remove(client);
604}
605
606MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
607 int32_t connId, const sp<IMediaPlayerClient>& client)
608{
609 LOGV("Client(%d) constructor", connId);
610 mPid = pid;
611 mConnId = connId;
612 mService = service;
613 mClient = client;
614 mLoop = false;
615 mStatus = NO_INIT;
616#if CALLBACK_ANTAGONIZER
617 LOGD("create Antagonizer");
618 mAntagonizer = new Antagonizer(notify, this);
619#endif
620}
621
622MediaPlayerService::Client::~Client()
623{
624 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
625 mAudioOutput.clear();
626 wp<Client> client(this);
627 disconnect();
628 mService->removeClient(client);
629}
630
631void MediaPlayerService::Client::disconnect()
632{
633 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
634 // grab local reference and clear main reference to prevent future
635 // access to object
636 sp<MediaPlayerBase> p;
637 {
638 Mutex::Autolock l(mLock);
639 p = mPlayer;
640 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700641 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 mPlayer.clear();
644
645 // clear the notification to prevent callbacks to dead client
646 // and reset the player. We assume the player will serialize
647 // access to itself if necessary.
648 if (p != 0) {
649 p->setNotifyCallback(0, 0);
650#if CALLBACK_ANTAGONIZER
651 LOGD("kill Antagonizer");
652 mAntagonizer->kill();
653#endif
654 p->reset();
655 }
656
657 IPCThreadState::self()->flushCommands();
658}
659
Andreas Huber0d596d42009-08-07 09:30:32 -0700660static player_type getDefaultPlayerType() {
Andreas Huber2aa39c42009-09-11 09:54:52 -0700661#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber0d596d42009-08-07 09:30:32 -0700662 char value[PROPERTY_VALUE_MAX];
663 if (property_get("media.stagefright.enable-player", value, NULL)
664 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
665 return STAGEFRIGHT_PLAYER;
666 }
Andreas Huber2aa39c42009-09-11 09:54:52 -0700667#endif
Andreas Huber0d596d42009-08-07 09:30:32 -0700668
669 return PV_PLAYER;
670}
671
James Dong392ff3b2009-09-06 14:29:45 -0700672player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673{
674 char buf[20];
675 lseek(fd, offset, SEEK_SET);
676 read(fd, buf, sizeof(buf));
677 lseek(fd, offset, SEEK_SET);
678
679 long ident = *((long*)buf);
680
681 // Ogg vorbis?
682 if (ident == 0x5367674f) // 'OggS'
683 return VORBIS_PLAYER;
684
685 // Some kind of MIDI?
686 EAS_DATA_HANDLE easdata;
687 if (EAS_Init(&easdata) == EAS_SUCCESS) {
688 EAS_FILE locator;
689 locator.path = NULL;
690 locator.fd = fd;
691 locator.offset = offset;
692 locator.length = length;
693 EAS_HANDLE eashandle;
694 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
695 EAS_CloseFile(easdata, eashandle);
696 EAS_Shutdown(easdata);
697 return SONIVOX_PLAYER;
698 }
699 EAS_Shutdown(easdata);
700 }
701
Andreas Huber0d596d42009-08-07 09:30:32 -0700702 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703}
704
James Dong392ff3b2009-09-06 14:29:45 -0700705player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700707 if (TestPlayerStub::canBeUsed(url)) {
708 return TEST_PLAYER;
709 }
710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 // use MidiFile for MIDI extensions
712 int lenURL = strlen(url);
713 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
714 int len = strlen(FILE_EXTS[i].extension);
715 int start = lenURL - len;
716 if (start > 0) {
717 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
718 return FILE_EXTS[i].playertype;
719 }
720 }
721 }
722
Andreas Huber0d596d42009-08-07 09:30:32 -0700723 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724}
725
726static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
727 notify_callback_f notifyFunc)
728{
729 sp<MediaPlayerBase> p;
730 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700731#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 case PV_PLAYER:
733 LOGV(" create PVPlayer");
734 p = new PVPlayer();
735 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700736#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 case SONIVOX_PLAYER:
738 LOGV(" create MidiFile");
739 p = new MidiFile();
740 break;
741 case VORBIS_PLAYER:
742 LOGV(" create VorbisPlayer");
743 p = new VorbisPlayer();
744 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700745#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Hubere46b7be2009-07-14 16:56:47 -0700746 case STAGEFRIGHT_PLAYER:
747 LOGV(" create StagefrightPlayer");
748 p = new StagefrightPlayer;
749 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700750#endif
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700751 case TEST_PLAYER:
752 LOGV("Create Test Player stub");
753 p = new TestPlayerStub();
754 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 }
756 if (p != NULL) {
757 if (p->initCheck() == NO_ERROR) {
758 p->setNotifyCallback(cookie, notifyFunc);
759 } else {
760 p.clear();
761 }
762 }
763 if (p == NULL) {
764 LOGE("Failed to create player object");
765 }
766 return p;
767}
768
769sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
770{
771 // determine if we have the right player type
772 sp<MediaPlayerBase> p = mPlayer;
773 if ((p != NULL) && (p->playerType() != playerType)) {
774 LOGV("delete player");
775 p.clear();
776 }
777 if (p == NULL) {
778 p = android::createPlayer(playerType, this, notify);
779 }
780 return p;
781}
782
783status_t MediaPlayerService::Client::setDataSource(const char *url)
784{
785 LOGV("setDataSource(%s)", url);
786 if (url == NULL)
787 return UNKNOWN_ERROR;
788
789 if (strncmp(url, "content://", 10) == 0) {
790 // get a filedescriptor for the content Uri and
791 // pass it to the setDataSource(fd) method
792
793 String16 url16(url);
794 int fd = android::openContentProviderFile(url16);
795 if (fd < 0)
796 {
797 LOGE("Couldn't open fd for %s", url);
798 return UNKNOWN_ERROR;
799 }
800 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
801 close(fd);
802 return mStatus;
803 } else {
804 player_type playerType = getPlayerType(url);
805 LOGV("player type = %d", playerType);
806
807 // create the right type of player
808 sp<MediaPlayerBase> p = createPlayer(playerType);
809 if (p == NULL) return NO_INIT;
810
811 if (!p->hardwareOutput()) {
812 mAudioOutput = new AudioOutput();
813 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
814 }
815
816 // now set data source
817 LOGV(" setDataSource");
818 mStatus = p->setDataSource(url);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700819 if (mStatus == NO_ERROR) {
820 mPlayer = p;
821 } else {
822 LOGE(" error: %d", mStatus);
823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 return mStatus;
825 }
826}
827
828status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
829{
830 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
831 struct stat sb;
832 int ret = fstat(fd, &sb);
833 if (ret != 0) {
834 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
835 return UNKNOWN_ERROR;
836 }
837
838 LOGV("st_dev = %llu", sb.st_dev);
839 LOGV("st_mode = %u", sb.st_mode);
840 LOGV("st_uid = %lu", sb.st_uid);
841 LOGV("st_gid = %lu", sb.st_gid);
842 LOGV("st_size = %llu", sb.st_size);
843
844 if (offset >= sb.st_size) {
845 LOGE("offset error");
846 ::close(fd);
847 return UNKNOWN_ERROR;
848 }
849 if (offset + length > sb.st_size) {
850 length = sb.st_size - offset;
851 LOGV("calculated length = %lld", length);
852 }
853
854 player_type playerType = getPlayerType(fd, offset, length);
855 LOGV("player type = %d", playerType);
856
857 // create the right type of player
858 sp<MediaPlayerBase> p = createPlayer(playerType);
859 if (p == NULL) return NO_INIT;
860
861 if (!p->hardwareOutput()) {
862 mAudioOutput = new AudioOutput();
863 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
864 }
865
866 // now set data source
867 mStatus = p->setDataSource(fd, offset, length);
868 if (mStatus == NO_ERROR) mPlayer = p;
869 return mStatus;
870}
871
872status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
873{
874 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
875 sp<MediaPlayerBase> p = getPlayer();
876 if (p == 0) return UNKNOWN_ERROR;
877 return p->setVideoSurface(surface);
878}
879
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700880status_t MediaPlayerService::Client::invoke(const Parcel& request,
881 Parcel *reply)
882{
883 sp<MediaPlayerBase> p = getPlayer();
884 if (p == NULL) return UNKNOWN_ERROR;
885 return p->invoke(request, reply);
886}
887
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700888// This call doesn't need to access the native player.
889status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
890{
891 status_t status;
nikobc726922009-07-20 15:07:26 -0700892 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700893
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700894 if (unmarshallFilter(filter, &allow, &status) &&
895 unmarshallFilter(filter, &drop, &status)) {
896 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700897
898 mMetadataAllow = allow;
899 mMetadataDrop = drop;
900 }
901 return status;
902}
903
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700904status_t MediaPlayerService::Client::getMetadata(
905 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700906{
nikobc726922009-07-20 15:07:26 -0700907 sp<MediaPlayerBase> player = getPlayer();
908 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700909
niko89948372009-07-16 16:39:53 -0700910 status_t status;
911 // Placeholder for the return code, updated by the caller.
912 reply->writeInt32(-1);
913
nikobc726922009-07-20 15:07:26 -0700914 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700915
916 // We don't block notifications while we fetch the data. We clear
917 // mMetadataUpdated first so we don't lose notifications happening
918 // during the rest of this call.
919 {
920 Mutex::Autolock lock(mLock);
921 if (update_only) {
niko89948372009-07-16 16:39:53 -0700922 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700923 }
924 mMetadataUpdated.clear();
925 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700926
nikobc726922009-07-20 15:07:26 -0700927 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700928
nikobc726922009-07-20 15:07:26 -0700929 metadata.appendHeader();
930 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700931
932 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700933 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700934 LOGE("getMetadata failed %d", status);
935 return status;
936 }
937
938 // FIXME: Implement filtering on the result. Not critical since
939 // filtering takes place on the update notifications already. This
940 // would be when all the metadata are fetch and a filter is set.
941
niko89948372009-07-16 16:39:53 -0700942 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700943 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700944 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700945}
946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947status_t MediaPlayerService::Client::prepareAsync()
948{
949 LOGV("[%d] prepareAsync", mConnId);
950 sp<MediaPlayerBase> p = getPlayer();
951 if (p == 0) return UNKNOWN_ERROR;
952 status_t ret = p->prepareAsync();
953#if CALLBACK_ANTAGONIZER
954 LOGD("start Antagonizer");
955 if (ret == NO_ERROR) mAntagonizer->start();
956#endif
957 return ret;
958}
959
960status_t MediaPlayerService::Client::start()
961{
962 LOGV("[%d] start", mConnId);
963 sp<MediaPlayerBase> p = getPlayer();
964 if (p == 0) return UNKNOWN_ERROR;
965 p->setLooping(mLoop);
966 return p->start();
967}
968
969status_t MediaPlayerService::Client::stop()
970{
971 LOGV("[%d] stop", mConnId);
972 sp<MediaPlayerBase> p = getPlayer();
973 if (p == 0) return UNKNOWN_ERROR;
974 return p->stop();
975}
976
977status_t MediaPlayerService::Client::pause()
978{
979 LOGV("[%d] pause", mConnId);
980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == 0) return UNKNOWN_ERROR;
982 return p->pause();
983}
984
985status_t MediaPlayerService::Client::isPlaying(bool* state)
986{
987 *state = false;
988 sp<MediaPlayerBase> p = getPlayer();
989 if (p == 0) return UNKNOWN_ERROR;
990 *state = p->isPlaying();
991 LOGV("[%d] isPlaying: %d", mConnId, *state);
992 return NO_ERROR;
993}
994
995status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
996{
997 LOGV("getCurrentPosition");
998 sp<MediaPlayerBase> p = getPlayer();
999 if (p == 0) return UNKNOWN_ERROR;
1000 status_t ret = p->getCurrentPosition(msec);
1001 if (ret == NO_ERROR) {
1002 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1003 } else {
1004 LOGE("getCurrentPosition returned %d", ret);
1005 }
1006 return ret;
1007}
1008
1009status_t MediaPlayerService::Client::getDuration(int *msec)
1010{
1011 LOGV("getDuration");
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 status_t ret = p->getDuration(msec);
1015 if (ret == NO_ERROR) {
1016 LOGV("[%d] getDuration = %d", mConnId, *msec);
1017 } else {
1018 LOGE("getDuration returned %d", ret);
1019 }
1020 return ret;
1021}
1022
1023status_t MediaPlayerService::Client::seekTo(int msec)
1024{
1025 LOGV("[%d] seekTo(%d)", mConnId, msec);
1026 sp<MediaPlayerBase> p = getPlayer();
1027 if (p == 0) return UNKNOWN_ERROR;
1028 return p->seekTo(msec);
1029}
1030
1031status_t MediaPlayerService::Client::reset()
1032{
1033 LOGV("[%d] reset", mConnId);
1034 sp<MediaPlayerBase> p = getPlayer();
1035 if (p == 0) return UNKNOWN_ERROR;
1036 return p->reset();
1037}
1038
1039status_t MediaPlayerService::Client::setAudioStreamType(int type)
1040{
1041 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1042 // TODO: for hardware output, call player instead
1043 Mutex::Autolock l(mLock);
1044 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1045 return NO_ERROR;
1046}
1047
1048status_t MediaPlayerService::Client::setLooping(int loop)
1049{
1050 LOGV("[%d] setLooping(%d)", mConnId, loop);
1051 mLoop = loop;
1052 sp<MediaPlayerBase> p = getPlayer();
1053 if (p != 0) return p->setLooping(loop);
1054 return NO_ERROR;
1055}
1056
1057status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1058{
1059 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1060 // TODO: for hardware output, call player instead
1061 Mutex::Autolock l(mLock);
1062 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1063 return NO_ERROR;
1064}
1065
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1068{
1069 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001070
1071 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001072 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001073 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001074
1075 if(client->shouldDropMetadata(metadata_type)) {
1076 return;
1077 }
1078
1079 // Update the list of metadata that have changed. getMetadata
1080 // also access mMetadataUpdated and clears it.
1081 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1084 client->mClient->notify(msg, ext1, ext2);
1085}
1086
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001087
nikobc726922009-07-20 15:07:26 -07001088bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001089{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001090 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001091
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001092 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001093 return true;
1094 }
1095
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001096 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001097 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001098 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001099 return true;
1100 }
1101}
1102
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001103
nikobc726922009-07-20 15:07:26 -07001104void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001105 Mutex::Autolock lock(mLock);
1106 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1107 mMetadataUpdated.add(metadata_type);
1108 }
1109}
1110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111#if CALLBACK_ANTAGONIZER
1112const int Antagonizer::interval = 10000; // 10 msecs
1113
1114Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1115 mExit(false), mActive(false), mClient(client), mCb(cb)
1116{
1117 createThread(callbackThread, this);
1118}
1119
1120void Antagonizer::kill()
1121{
1122 Mutex::Autolock _l(mLock);
1123 mActive = false;
1124 mExit = true;
1125 mCondition.wait(mLock);
1126}
1127
1128int Antagonizer::callbackThread(void* user)
1129{
1130 LOGD("Antagonizer started");
1131 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1132 while (!p->mExit) {
1133 if (p->mActive) {
1134 LOGV("send event");
1135 p->mCb(p->mClient, 0, 0, 0);
1136 }
1137 usleep(interval);
1138 }
1139 Mutex::Autolock _l(p->mLock);
1140 p->mCondition.signal();
1141 LOGD("Antagonizer stopped");
1142 return 0;
1143}
1144#endif
1145
1146static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1147
1148sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1149{
1150 LOGV("decode(%s)", url);
1151 sp<MemoryBase> mem;
1152 sp<MediaPlayerBase> player;
1153
1154 // Protect our precious, precious DRMd ringtones by only allowing
1155 // decoding of http, but not filesystem paths or content Uris.
1156 // If the application wants to decode those, it should open a
1157 // filedescriptor for them and use that.
1158 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1159 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1160 return mem;
1161 }
1162
1163 player_type playerType = getPlayerType(url);
1164 LOGV("player type = %d", playerType);
1165
1166 // create the right type of player
1167 sp<AudioCache> cache = new AudioCache(url);
1168 player = android::createPlayer(playerType, cache.get(), cache->notify);
1169 if (player == NULL) goto Exit;
1170 if (player->hardwareOutput()) goto Exit;
1171
1172 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1173
1174 // set data source
1175 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1176
1177 LOGV("prepare");
1178 player->prepareAsync();
1179
1180 LOGV("wait for prepare");
1181 if (cache->wait() != NO_ERROR) goto Exit;
1182
1183 LOGV("start");
1184 player->start();
1185
1186 LOGV("wait for playback complete");
1187 if (cache->wait() != NO_ERROR) goto Exit;
1188
1189 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1190 *pSampleRate = cache->sampleRate();
1191 *pNumChannels = cache->channelCount();
1192 *pFormat = cache->format();
1193 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1194
1195Exit:
1196 if (player != 0) player->reset();
1197 return mem;
1198}
1199
1200sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1201{
1202 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1203 sp<MemoryBase> mem;
1204 sp<MediaPlayerBase> player;
1205
1206 player_type playerType = getPlayerType(fd, offset, length);
1207 LOGV("player type = %d", playerType);
1208
1209 // create the right type of player
1210 sp<AudioCache> cache = new AudioCache("decode_fd");
1211 player = android::createPlayer(playerType, cache.get(), cache->notify);
1212 if (player == NULL) goto Exit;
1213 if (player->hardwareOutput()) goto Exit;
1214
1215 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1216
1217 // set data source
1218 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1219
1220 LOGV("prepare");
1221 player->prepareAsync();
1222
1223 LOGV("wait for prepare");
1224 if (cache->wait() != NO_ERROR) goto Exit;
1225
1226 LOGV("start");
1227 player->start();
1228
1229 LOGV("wait for playback complete");
1230 if (cache->wait() != NO_ERROR) goto Exit;
1231
1232 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1233 *pSampleRate = cache->sampleRate();
1234 *pNumChannels = cache->channelCount();
1235 *pFormat = cache->format();
1236 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1237
1238Exit:
1239 if (player != 0) player->reset();
1240 ::close(fd);
1241 return mem;
1242}
1243
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001244/*
1245 * Avert your eyes, ugly hack ahead.
1246 * The following is to support music visualizations.
1247 */
1248
1249static const int NUMVIZBUF = 32;
1250static const int VIZBUFFRAMES = 1024;
1251static const int TOTALBUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1252
1253static bool gotMem = false;
1254static sp<MemoryBase> mem[NUMVIZBUF];
1255static uint64_t timeStamp[NUMVIZBUF];
1256static uint64_t lastReadTime;
1257static uint64_t lastWriteTime;
1258static int writeIdx = 0;
1259
1260static void allocVizBufs() {
1261 if (!gotMem) {
1262 for (int i=0;i<NUMVIZBUF;i++) {
1263 sp<MemoryHeapBase> heap = new MemoryHeapBase(VIZBUFFRAMES*2, 0, "snooper");
1264 mem[i] = new MemoryBase(heap, 0, heap->getSize());
1265 timeStamp[i] = 0;
1266 }
1267 gotMem = true;
1268 }
1269}
1270
1271
1272/*
1273 * Get a buffer of audio data that is about to be played.
1274 * We don't synchronize this because in practice the writer
1275 * is ahead of the reader, and even if we did happen to catch
1276 * a buffer while it's being written, it's just a visualization,
1277 * so no harm done.
1278 */
1279static sp<MemoryBase> getVizBuffer() {
1280
1281 allocVizBufs();
1282
1283 lastReadTime = uptimeMillis() + 100; // account for renderer delay (we shouldn't be doing this here)
1284
1285 // if there is no recent buffer (yet), just return empty handed
1286 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
1287 //LOGI("@@@@ no audio data to look at yet");
1288 return NULL;
1289 }
1290
1291 char buf[200];
1292
1293 int closestIdx = -1;
1294 uint32_t closestTime = 0x7ffffff;
1295
1296 for (int i = 0; i < NUMVIZBUF; i++) {
1297 uint64_t tsi = timeStamp[i];
1298 uint64_t diff = tsi > lastReadTime ? tsi - lastReadTime : lastReadTime - tsi;
1299 if (diff < closestTime) {
1300 closestIdx = i;
1301 closestTime = diff;
1302 }
1303 }
1304
1305
1306 if (closestIdx >= 0) {
1307 //LOGI("@@@ return buffer %d, %d/%d", closestIdx, uint32_t(lastReadTime), uint32_t(timeStamp[closestIdx]));
1308 return mem[closestIdx];
1309 }
1310
1311 // we won't get here, since we either bailed out early, or got a buffer
1312 LOGD("Didn't expect to be here");
1313 return NULL;
1314}
1315
1316static void storeVizBuf(const void *data, int len, uint64_t time) {
1317 // Copy the data in to the visualizer buffer
1318 // Assume a 16 bit stereo source for now.
1319 short *viz = (short*)mem[writeIdx]->pointer();
1320 short *src = (short*)data;
1321 for (int i = 0; i < VIZBUFFRAMES; i++) {
1322 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1323 // This should still be good enough for a visualization
1324 *viz++ = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1325 src += 2;
1326 }
1327 timeStamp[writeIdx++] = time;
1328 if (writeIdx >= NUMVIZBUF) {
1329 writeIdx = 0;
1330 }
1331}
1332
1333static void makeVizBuffers(const char *data, int len, uint64_t time) {
1334
1335 allocVizBufs();
1336
1337 uint64_t startTime = time;
1338 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
1339 while (len >= VIZBUFFRAMES * frameSize) {
1340 storeVizBuf(data, len, time);
1341 data += VIZBUFFRAMES * frameSize;
1342 len -= VIZBUFFRAMES * frameSize;
1343 time += 1000 * VIZBUFFRAMES / 44100;
1344 }
1345 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1346}
1347
1348sp<IMemory> MediaPlayerService::snoop()
1349{
1350 sp<MemoryBase> mem = getVizBuffer();
1351 return mem;
1352}
1353
1354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355#undef LOG_TAG
1356#define LOG_TAG "AudioSink"
1357MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001358 : mCallback(NULL),
1359 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 mTrack = 0;
1361 mStreamType = AudioSystem::MUSIC;
1362 mLeftVolume = 1.0;
1363 mRightVolume = 1.0;
1364 mLatency = 0;
1365 mMsecsPerFrame = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001366 mNumFramesWritten = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 setMinBufferCount();
1368}
1369
1370MediaPlayerService::AudioOutput::~AudioOutput()
1371{
1372 close();
1373}
1374
1375void MediaPlayerService::AudioOutput::setMinBufferCount()
1376{
1377 char value[PROPERTY_VALUE_MAX];
1378 if (property_get("ro.kernel.qemu", value, 0)) {
1379 mIsOnEmulator = true;
1380 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1381 }
1382}
1383
1384bool MediaPlayerService::AudioOutput::isOnEmulator()
1385{
1386 setMinBufferCount();
1387 return mIsOnEmulator;
1388}
1389
1390int MediaPlayerService::AudioOutput::getMinBufferCount()
1391{
1392 setMinBufferCount();
1393 return mMinBufferCount;
1394}
1395
1396ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1397{
1398 if (mTrack == 0) return NO_INIT;
1399 return mTrack->frameCount() * frameSize();
1400}
1401
1402ssize_t MediaPlayerService::AudioOutput::frameCount() const
1403{
1404 if (mTrack == 0) return NO_INIT;
1405 return mTrack->frameCount();
1406}
1407
1408ssize_t MediaPlayerService::AudioOutput::channelCount() const
1409{
1410 if (mTrack == 0) return NO_INIT;
1411 return mTrack->channelCount();
1412}
1413
1414ssize_t MediaPlayerService::AudioOutput::frameSize() const
1415{
1416 if (mTrack == 0) return NO_INIT;
1417 return mTrack->frameSize();
1418}
1419
1420uint32_t MediaPlayerService::AudioOutput::latency () const
1421{
1422 return mLatency;
1423}
1424
1425float MediaPlayerService::AudioOutput::msecsPerFrame() const
1426{
1427 return mMsecsPerFrame;
1428}
1429
Andreas Hubere46b7be2009-07-14 16:56:47 -07001430status_t MediaPlayerService::AudioOutput::open(
1431 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1432 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001434 mCallback = cb;
1435 mCallbackCookie = cookie;
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 // Check argument "bufferCount" against the mininum buffer count
1438 if (bufferCount < mMinBufferCount) {
1439 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1440 bufferCount = mMinBufferCount;
1441
1442 }
1443 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1444 if (mTrack) close();
1445 int afSampleRate;
1446 int afFrameCount;
1447 int frameCount;
1448
1449 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1450 return NO_INIT;
1451 }
1452 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1453 return NO_INIT;
1454 }
1455
1456 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001457
1458 AudioTrack *t;
1459 if (mCallback != NULL) {
1460 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001461 mStreamType,
1462 sampleRate,
1463 format,
1464 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1465 frameCount,
1466 0 /* flags */,
1467 CallbackWrapper,
1468 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001469 } else {
1470 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001471 mStreamType,
1472 sampleRate,
1473 format,
1474 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1475 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001476 }
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1479 LOGE("Unable to create audio track");
1480 delete t;
1481 return NO_INIT;
1482 }
1483
1484 LOGV("setVolume");
1485 t->setVolume(mLeftVolume, mRightVolume);
1486 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001487 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 mTrack = t;
1489 return NO_ERROR;
1490}
1491
1492void MediaPlayerService::AudioOutput::start()
1493{
1494 LOGV("start");
1495 if (mTrack) {
1496 mTrack->setVolume(mLeftVolume, mRightVolume);
1497 mTrack->start();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001498 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500}
1501
1502ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1503{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001504 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001507 if (mTrack) {
1508 // Only make visualization buffers if anyone recently requested visualization data
1509 uint64_t now = uptimeMillis();
1510 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1511 // Based on the current play counter, the number of frames written and
1512 // the current real time we can calculate the approximate real start
1513 // time of the buffer we're about to write.
1514 uint32_t pos;
1515 mTrack->getPosition(&pos);
1516
1517 // we're writing ahead by this many frames:
1518 int ahead = mNumFramesWritten - pos;
1519 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1520 // which is this many milliseconds, assuming 44100 Hz:
1521 ahead /= 44;
1522
1523 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1524 lastWriteTime = now;
1525 }
1526 ssize_t ret = mTrack->write(buffer, size);
1527 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1528 return ret;
1529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 return NO_INIT;
1531}
1532
1533void MediaPlayerService::AudioOutput::stop()
1534{
1535 LOGV("stop");
1536 if (mTrack) mTrack->stop();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001537 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538}
1539
1540void MediaPlayerService::AudioOutput::flush()
1541{
1542 LOGV("flush");
1543 if (mTrack) mTrack->flush();
1544}
1545
1546void MediaPlayerService::AudioOutput::pause()
1547{
1548 LOGV("pause");
1549 if (mTrack) mTrack->pause();
Marco Nelissen758613d2009-11-02 13:52:11 -08001550 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551}
1552
1553void MediaPlayerService::AudioOutput::close()
1554{
1555 LOGV("close");
1556 delete mTrack;
1557 mTrack = 0;
1558}
1559
1560void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1561{
1562 LOGV("setVolume(%f, %f)", left, right);
1563 mLeftVolume = left;
1564 mRightVolume = right;
1565 if (mTrack) {
1566 mTrack->setVolume(left, right);
1567 }
1568}
1569
Andreas Hubere46b7be2009-07-14 16:56:47 -07001570// static
1571void MediaPlayerService::AudioOutput::CallbackWrapper(
1572 int event, void *cookie, void *info) {
1573 if (event != AudioTrack::EVENT_MORE_DATA) {
1574 return;
1575 }
1576
1577 AudioOutput *me = (AudioOutput *)cookie;
1578 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1579
1580 (*me->mCallback)(
1581 me, buffer->raw, buffer->size, me->mCallbackCookie);
1582}
1583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584#undef LOG_TAG
1585#define LOG_TAG "AudioCache"
1586MediaPlayerService::AudioCache::AudioCache(const char* name) :
1587 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1588 mError(NO_ERROR), mCommandComplete(false)
1589{
1590 // create ashmem heap
1591 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1592}
1593
1594uint32_t MediaPlayerService::AudioCache::latency () const
1595{
1596 return 0;
1597}
1598
1599float MediaPlayerService::AudioCache::msecsPerFrame() const
1600{
1601 return mMsecsPerFrame;
1602}
1603
Andreas Hubere46b7be2009-07-14 16:56:47 -07001604status_t MediaPlayerService::AudioCache::open(
1605 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1606 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001608 if (cb != NULL) {
1609 return UNKNOWN_ERROR; // TODO: implement this.
1610 }
1611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1613 if (mHeap->getHeapID() < 0) return NO_INIT;
1614 mSampleRate = sampleRate;
1615 mChannelCount = (uint16_t)channelCount;
1616 mFormat = (uint16_t)format;
1617 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1618 return NO_ERROR;
1619}
1620
1621ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1622{
1623 LOGV("write(%p, %u)", buffer, size);
1624 if ((buffer == 0) || (size == 0)) return size;
1625
1626 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1627 if (p == NULL) return NO_INIT;
1628 p += mSize;
1629 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1630 if (mSize + size > mHeap->getSize()) {
1631 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1632 size = mHeap->getSize() - mSize;
1633 }
1634 memcpy(p, buffer, size);
1635 mSize += size;
1636 return size;
1637}
1638
1639// call with lock held
1640status_t MediaPlayerService::AudioCache::wait()
1641{
1642 Mutex::Autolock lock(mLock);
1643 if (!mCommandComplete) {
1644 mSignal.wait(mLock);
1645 }
1646 mCommandComplete = false;
1647
1648 if (mError == NO_ERROR) {
1649 LOGV("wait - success");
1650 } else {
1651 LOGV("wait - error");
1652 }
1653 return mError;
1654}
1655
1656void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1657{
1658 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1659 AudioCache* p = static_cast<AudioCache*>(cookie);
1660
1661 // ignore buffering messages
1662 if (msg == MEDIA_BUFFERING_UPDATE) return;
1663
1664 // set error condition
1665 if (msg == MEDIA_ERROR) {
1666 LOGE("Error %d, %d occurred", ext1, ext2);
1667 p->mError = ext1;
1668 }
1669
1670 // wake up thread
1671 LOGV("wakeup thread");
1672 p->mCommandComplete = true;
1673 p->mSignal.signal();
1674}
1675
nikobc726922009-07-20 15:07:26 -07001676} // namespace android