blob: 50dad339128f960b6751ea3bb837ab79988e2c63 [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},
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800202#ifndef NO_OPENCORE
203 {".wma", PV_PLAYER},
204 {".wmv", PV_PLAYER},
205 {".asf", PV_PLAYER},
206#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207};
208
209// 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 -0800210/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
211/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
212
213void MediaPlayerService::instantiate() {
214 defaultServiceManager()->addService(
215 String16("media.player"), new MediaPlayerService());
216}
217
218MediaPlayerService::MediaPlayerService()
219{
220 LOGV("MediaPlayerService created");
221 mNextConnId = 1;
222}
223
224MediaPlayerService::~MediaPlayerService()
225{
226 LOGV("MediaPlayerService destroyed");
227}
228
229sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
230{
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700231#ifndef NO_OPENCORE
Gloria Wang608a2632009-10-29 15:46:37 -0700232 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
233 wp<MediaRecorderClient> w = recorder;
234 Mutex::Autolock lock(mLock);
235 mMediaRecorderClients.add(w);
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700236#else
237 sp<MediaRecorderClient> recorder = NULL;
238#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 LOGV("Create new media recorder client from pid %d", pid);
240 return recorder;
241}
242
Gloria Wang608a2632009-10-29 15:46:37 -0700243void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
244{
245 Mutex::Autolock lock(mLock);
246 mMediaRecorderClients.remove(client);
247 LOGV("Delete media recorder client");
248}
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
251{
252 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
253 LOGV("Create new media retriever from pid %d", pid);
254 return retriever;
255}
256
Andreas Huber25643002010-01-28 11:19:57 -0800257sp<IMediaPlayer> MediaPlayerService::create(
258 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
259 const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260{
261 int32_t connId = android_atomic_inc(&mNextConnId);
262 sp<Client> c = new Client(this, pid, connId, client);
263 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
Andreas Huber25643002010-01-28 11:19:57 -0800264 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 {
266 c.clear();
267 return c;
268 }
269 wp<Client> w = c;
270 Mutex::Autolock lock(mLock);
271 mClients.add(w);
272 return c;
273}
274
275sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
276 int fd, int64_t offset, int64_t length)
277{
278 int32_t connId = android_atomic_inc(&mNextConnId);
279 sp<Client> c = new Client(this, pid, connId, client);
280 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
281 connId, pid, fd, offset, length);
282 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
283 c.clear();
284 } else {
285 wp<Client> w = c;
286 Mutex::Autolock lock(mLock);
287 mClients.add(w);
288 }
289 ::close(fd);
290 return c;
291}
292
Andreas Huber784202e2009-10-15 13:46:54 -0700293sp<IOMX> MediaPlayerService::getOMX() {
294 Mutex::Autolock autoLock(mLock);
295
296 if (mOMX.get() == NULL) {
297 mOMX = new OMX;
298 }
299
300 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700301}
302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308
309 result.append(" AudioCache\n");
310 if (mHeap != 0) {
311 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
312 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
313 result.append(buffer);
314 }
315 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
316 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
317 result.append(buffer);
318 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
319 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
320 result.append(buffer);
321 ::write(fd, result.string(), result.size());
322 return NO_ERROR;
323}
324
325status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
326{
327 const size_t SIZE = 256;
328 char buffer[SIZE];
329 String8 result;
330
331 result.append(" AudioOutput\n");
332 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
333 mStreamType, mLeftVolume, mRightVolume);
334 result.append(buffer);
335 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
336 mMsecsPerFrame, mLatency);
337 result.append(buffer);
338 ::write(fd, result.string(), result.size());
339 if (mTrack != 0) {
340 mTrack->dump(fd, args);
341 }
342 return NO_ERROR;
343}
344
345status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
350 result.append(" Client\n");
351 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
352 mPid, mConnId, mStatus, mLoop?"true": "false");
353 result.append(buffer);
354 write(fd, result.string(), result.size());
355 if (mAudioOutput != 0) {
356 mAudioOutput->dump(fd, args);
357 }
358 write(fd, "\n", 1);
359 return NO_ERROR;
360}
361
362static int myTid() {
363#ifdef HAVE_GETTID
364 return gettid();
365#else
366 return getpid();
367#endif
368}
369
370#if defined(__arm__)
371extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
372 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
373extern "C" void free_malloc_leak_info(uint8_t* info);
374
Andreas Huber27123462009-10-27 15:50:04 -0700375// Use the String-class below instead of String8 to allocate all memory
376// beforehand and not reenter the heap while we are examining it...
377struct MyString8 {
378 static const size_t MAX_SIZE = 256 * 1024;
379
380 MyString8()
381 : mPtr((char *)malloc(MAX_SIZE)) {
382 *mPtr = '\0';
383 }
384
385 ~MyString8() {
386 free(mPtr);
387 }
388
389 void append(const char *s) {
390 strcat(mPtr, s);
391 }
392
393 const char *string() const {
394 return mPtr;
395 }
396
397 size_t size() const {
398 return strlen(mPtr);
399 }
400
401private:
402 char *mPtr;
403
404 MyString8(const MyString8 &);
405 MyString8 &operator=(const MyString8 &);
406};
407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408void memStatus(int fd, const Vector<String16>& args)
409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
Andreas Huber27123462009-10-27 15:50:04 -0700412 MyString8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413
414 typedef struct {
415 size_t size;
416 size_t dups;
417 intptr_t * backtrace;
418 } AllocEntry;
419
420 uint8_t *info = NULL;
421 size_t overallSize = 0;
422 size_t infoSize = 0;
423 size_t totalMemory = 0;
424 size_t backtraceSize = 0;
425
426 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
427 if (info) {
428 uint8_t *ptr = info;
429 size_t count = overallSize / infoSize;
430
431 snprintf(buffer, SIZE, " Allocation count %i\n", count);
432 result.append(buffer);
433
434 AllocEntry * entries = new AllocEntry[count];
435
436 for (size_t i = 0; i < count; i++) {
437 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
438 AllocEntry *e = &entries[i];
439
440 e->size = *reinterpret_cast<size_t *>(ptr);
441 ptr += sizeof(size_t);
442
443 e->dups = *reinterpret_cast<size_t *>(ptr);
444 ptr += sizeof(size_t);
445
446 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
447 ptr += sizeof(intptr_t) * backtraceSize;
448 }
449
450 // Now we need to sort the entries. They come sorted by size but
451 // not by stack trace which causes problems using diff.
452 bool moved;
453 do {
454 moved = false;
455 for (size_t i = 0; i < (count - 1); i++) {
456 AllocEntry *e1 = &entries[i];
457 AllocEntry *e2 = &entries[i+1];
458
459 bool swap = e1->size < e2->size;
460 if (e1->size == e2->size) {
461 for(size_t j = 0; j < backtraceSize; j++) {
462 if (e1->backtrace[j] == e2->backtrace[j]) {
463 continue;
464 }
465 swap = e1->backtrace[j] < e2->backtrace[j];
466 break;
467 }
468 }
469 if (swap) {
470 AllocEntry t = entries[i];
471 entries[i] = entries[i+1];
472 entries[i+1] = t;
473 moved = true;
474 }
475 }
476 } while (moved);
477
478 for (size_t i = 0; i < count; i++) {
479 AllocEntry *e = &entries[i];
480
481 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
482 result.append(buffer);
483 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
484 if (ct) {
485 result.append(", ");
486 }
487 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
488 result.append(buffer);
489 }
490 result.append("\n");
491 }
492
493 delete[] entries;
494 free_malloc_leak_info(info);
495 }
496
497 write(fd, result.string(), result.size());
498}
499#endif
500
501status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
502{
503 const size_t SIZE = 256;
504 char buffer[SIZE];
505 String8 result;
506 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
507 snprintf(buffer, SIZE, "Permission Denial: "
508 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
509 IPCThreadState::self()->getCallingPid(),
510 IPCThreadState::self()->getCallingUid());
511 result.append(buffer);
512 } else {
513 Mutex::Autolock lock(mLock);
514 for (int i = 0, n = mClients.size(); i < n; ++i) {
515 sp<Client> c = mClients[i].promote();
516 if (c != 0) c->dump(fd, args);
517 }
Gloria Wang608a2632009-10-29 15:46:37 -0700518 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
519 result.append(" MediaRecorderClient\n");
520 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
521 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid);
522 result.append(buffer);
523 }
524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 result.append(" Files opened and/or mapped:\n");
526 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
527 FILE *f = fopen(buffer, "r");
528 if (f) {
529 while (!feof(f)) {
530 fgets(buffer, SIZE, f);
531 if (strstr(buffer, " /sdcard/") ||
532 strstr(buffer, " /system/sounds/") ||
533 strstr(buffer, " /system/media/")) {
534 result.append(" ");
535 result.append(buffer);
536 }
537 }
538 fclose(f);
539 } else {
540 result.append("couldn't open ");
541 result.append(buffer);
542 result.append("\n");
543 }
544
545 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
546 DIR *d = opendir(buffer);
547 if (d) {
548 struct dirent *ent;
549 while((ent = readdir(d)) != NULL) {
550 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
551 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
552 struct stat s;
553 if (lstat(buffer, &s) == 0) {
554 if ((s.st_mode & S_IFMT) == S_IFLNK) {
555 char linkto[256];
556 int len = readlink(buffer, linkto, sizeof(linkto));
557 if(len > 0) {
558 if(len > 255) {
559 linkto[252] = '.';
560 linkto[253] = '.';
561 linkto[254] = '.';
562 linkto[255] = 0;
563 } else {
564 linkto[len] = 0;
565 }
566 if (strstr(linkto, "/sdcard/") == linkto ||
567 strstr(linkto, "/system/sounds/") == linkto ||
568 strstr(linkto, "/system/media/") == linkto) {
569 result.append(" ");
570 result.append(buffer);
571 result.append(" -> ");
572 result.append(linkto);
573 result.append("\n");
574 }
575 }
576 } else {
577 result.append(" unexpected type for ");
578 result.append(buffer);
579 result.append("\n");
580 }
581 }
582 }
583 }
584 closedir(d);
585 } else {
586 result.append("couldn't open ");
587 result.append(buffer);
588 result.append("\n");
589 }
590
591#if defined(__arm__)
592 bool dumpMem = false;
593 for (size_t i = 0; i < args.size(); i++) {
594 if (args[i] == String16("-m")) {
595 dumpMem = true;
596 }
597 }
598 if (dumpMem) {
599 memStatus(fd, args);
600 }
601#endif
602 }
603 write(fd, result.string(), result.size());
604 return NO_ERROR;
605}
606
607void MediaPlayerService::removeClient(wp<Client> client)
608{
609 Mutex::Autolock lock(mLock);
610 mClients.remove(client);
611}
612
613MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
614 int32_t connId, const sp<IMediaPlayerClient>& client)
615{
616 LOGV("Client(%d) constructor", connId);
617 mPid = pid;
618 mConnId = connId;
619 mService = service;
620 mClient = client;
621 mLoop = false;
622 mStatus = NO_INIT;
623#if CALLBACK_ANTAGONIZER
624 LOGD("create Antagonizer");
625 mAntagonizer = new Antagonizer(notify, this);
626#endif
627}
628
629MediaPlayerService::Client::~Client()
630{
631 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
632 mAudioOutput.clear();
633 wp<Client> client(this);
634 disconnect();
635 mService->removeClient(client);
636}
637
638void MediaPlayerService::Client::disconnect()
639{
640 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
641 // grab local reference and clear main reference to prevent future
642 // access to object
643 sp<MediaPlayerBase> p;
644 {
645 Mutex::Autolock l(mLock);
646 p = mPlayer;
647 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700648 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 mPlayer.clear();
651
652 // clear the notification to prevent callbacks to dead client
653 // and reset the player. We assume the player will serialize
654 // access to itself if necessary.
655 if (p != 0) {
656 p->setNotifyCallback(0, 0);
657#if CALLBACK_ANTAGONIZER
658 LOGD("kill Antagonizer");
659 mAntagonizer->kill();
660#endif
661 p->reset();
662 }
663
664 IPCThreadState::self()->flushCommands();
665}
666
Andreas Huber0d596d42009-08-07 09:30:32 -0700667static player_type getDefaultPlayerType() {
Andreas Huber2aa39c42009-09-11 09:54:52 -0700668#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber0d596d42009-08-07 09:30:32 -0700669 char value[PROPERTY_VALUE_MAX];
670 if (property_get("media.stagefright.enable-player", value, NULL)
671 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
672 return STAGEFRIGHT_PLAYER;
673 }
Andreas Huber2aa39c42009-09-11 09:54:52 -0700674#endif
Andreas Huber0d596d42009-08-07 09:30:32 -0700675
676 return PV_PLAYER;
677}
678
James Dong392ff3b2009-09-06 14:29:45 -0700679player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680{
681 char buf[20];
682 lseek(fd, offset, SEEK_SET);
683 read(fd, buf, sizeof(buf));
684 lseek(fd, offset, SEEK_SET);
685
686 long ident = *((long*)buf);
687
688 // Ogg vorbis?
689 if (ident == 0x5367674f) // 'OggS'
690 return VORBIS_PLAYER;
691
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800692#ifndef NO_OPENCORE
693 if (ident == 0x75b22630) {
694 // The magic number for .asf files, i.e. wmv and wma content.
695 // These are not currently supported through stagefright.
696 return PV_PLAYER;
697 }
698#endif
699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 // Some kind of MIDI?
701 EAS_DATA_HANDLE easdata;
702 if (EAS_Init(&easdata) == EAS_SUCCESS) {
703 EAS_FILE locator;
704 locator.path = NULL;
705 locator.fd = fd;
706 locator.offset = offset;
707 locator.length = length;
708 EAS_HANDLE eashandle;
709 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
710 EAS_CloseFile(easdata, eashandle);
711 EAS_Shutdown(easdata);
712 return SONIVOX_PLAYER;
713 }
714 EAS_Shutdown(easdata);
715 }
716
Andreas Huber0d596d42009-08-07 09:30:32 -0700717 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718}
719
James Dong392ff3b2009-09-06 14:29:45 -0700720player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700722 if (TestPlayerStub::canBeUsed(url)) {
723 return TEST_PLAYER;
724 }
725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 // use MidiFile for MIDI extensions
727 int lenURL = strlen(url);
728 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
729 int len = strlen(FILE_EXTS[i].extension);
730 int start = lenURL - len;
731 if (start > 0) {
732 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
733 return FILE_EXTS[i].playertype;
734 }
735 }
736 }
737
Andreas Huber6a3a0182009-12-17 13:31:13 -0800738 if (!strncasecmp(url, "http://", 7)) {
Andreas Huber67aee052010-01-04 17:27:37 -0800739 char value[PROPERTY_VALUE_MAX];
740 if (!property_get("media.stagefright.enable-http", value, NULL)
741 || (strcmp(value, "1") && strcasecmp(value, "true"))) {
742 // For now, we're going to use PV for http-based playback
743 // by default until we can clear up a few more issues.
744 return PV_PLAYER;
745 }
Andreas Huber6a3a0182009-12-17 13:31:13 -0800746 }
747
Andreas Huber0d596d42009-08-07 09:30:32 -0700748 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749}
750
751static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
752 notify_callback_f notifyFunc)
753{
754 sp<MediaPlayerBase> p;
755 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700756#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 case PV_PLAYER:
758 LOGV(" create PVPlayer");
759 p = new PVPlayer();
760 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700761#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 case SONIVOX_PLAYER:
763 LOGV(" create MidiFile");
764 p = new MidiFile();
765 break;
766 case VORBIS_PLAYER:
767 LOGV(" create VorbisPlayer");
768 p = new VorbisPlayer();
769 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700770#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Hubere46b7be2009-07-14 16:56:47 -0700771 case STAGEFRIGHT_PLAYER:
772 LOGV(" create StagefrightPlayer");
773 p = new StagefrightPlayer;
774 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700775#endif
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700776 case TEST_PLAYER:
777 LOGV("Create Test Player stub");
778 p = new TestPlayerStub();
779 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
781 if (p != NULL) {
782 if (p->initCheck() == NO_ERROR) {
783 p->setNotifyCallback(cookie, notifyFunc);
784 } else {
785 p.clear();
786 }
787 }
788 if (p == NULL) {
789 LOGE("Failed to create player object");
790 }
791 return p;
792}
793
794sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
795{
796 // determine if we have the right player type
797 sp<MediaPlayerBase> p = mPlayer;
798 if ((p != NULL) && (p->playerType() != playerType)) {
799 LOGV("delete player");
800 p.clear();
801 }
802 if (p == NULL) {
803 p = android::createPlayer(playerType, this, notify);
804 }
805 return p;
806}
807
Andreas Huber25643002010-01-28 11:19:57 -0800808status_t MediaPlayerService::Client::setDataSource(
809 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810{
811 LOGV("setDataSource(%s)", url);
812 if (url == NULL)
813 return UNKNOWN_ERROR;
814
815 if (strncmp(url, "content://", 10) == 0) {
816 // get a filedescriptor for the content Uri and
817 // pass it to the setDataSource(fd) method
818
819 String16 url16(url);
820 int fd = android::openContentProviderFile(url16);
821 if (fd < 0)
822 {
823 LOGE("Couldn't open fd for %s", url);
824 return UNKNOWN_ERROR;
825 }
826 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
827 close(fd);
828 return mStatus;
829 } else {
830 player_type playerType = getPlayerType(url);
831 LOGV("player type = %d", playerType);
832
833 // create the right type of player
834 sp<MediaPlayerBase> p = createPlayer(playerType);
835 if (p == NULL) return NO_INIT;
836
837 if (!p->hardwareOutput()) {
838 mAudioOutput = new AudioOutput();
839 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
840 }
841
842 // now set data source
843 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800844 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700845 if (mStatus == NO_ERROR) {
846 mPlayer = p;
847 } else {
848 LOGE(" error: %d", mStatus);
849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 return mStatus;
851 }
852}
853
854status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
855{
856 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
857 struct stat sb;
858 int ret = fstat(fd, &sb);
859 if (ret != 0) {
860 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
861 return UNKNOWN_ERROR;
862 }
863
864 LOGV("st_dev = %llu", sb.st_dev);
865 LOGV("st_mode = %u", sb.st_mode);
866 LOGV("st_uid = %lu", sb.st_uid);
867 LOGV("st_gid = %lu", sb.st_gid);
868 LOGV("st_size = %llu", sb.st_size);
869
870 if (offset >= sb.st_size) {
871 LOGE("offset error");
872 ::close(fd);
873 return UNKNOWN_ERROR;
874 }
875 if (offset + length > sb.st_size) {
876 length = sb.st_size - offset;
877 LOGV("calculated length = %lld", length);
878 }
879
880 player_type playerType = getPlayerType(fd, offset, length);
881 LOGV("player type = %d", playerType);
882
883 // create the right type of player
884 sp<MediaPlayerBase> p = createPlayer(playerType);
885 if (p == NULL) return NO_INIT;
886
887 if (!p->hardwareOutput()) {
888 mAudioOutput = new AudioOutput();
889 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
890 }
891
892 // now set data source
893 mStatus = p->setDataSource(fd, offset, length);
894 if (mStatus == NO_ERROR) mPlayer = p;
895 return mStatus;
896}
897
898status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
899{
900 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
901 sp<MediaPlayerBase> p = getPlayer();
902 if (p == 0) return UNKNOWN_ERROR;
903 return p->setVideoSurface(surface);
904}
905
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700906status_t MediaPlayerService::Client::invoke(const Parcel& request,
907 Parcel *reply)
908{
909 sp<MediaPlayerBase> p = getPlayer();
910 if (p == NULL) return UNKNOWN_ERROR;
911 return p->invoke(request, reply);
912}
913
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700914// This call doesn't need to access the native player.
915status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
916{
917 status_t status;
nikobc726922009-07-20 15:07:26 -0700918 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700919
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700920 if (unmarshallFilter(filter, &allow, &status) &&
921 unmarshallFilter(filter, &drop, &status)) {
922 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700923
924 mMetadataAllow = allow;
925 mMetadataDrop = drop;
926 }
927 return status;
928}
929
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700930status_t MediaPlayerService::Client::getMetadata(
931 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700932{
nikobc726922009-07-20 15:07:26 -0700933 sp<MediaPlayerBase> player = getPlayer();
934 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700935
niko89948372009-07-16 16:39:53 -0700936 status_t status;
937 // Placeholder for the return code, updated by the caller.
938 reply->writeInt32(-1);
939
nikobc726922009-07-20 15:07:26 -0700940 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700941
942 // We don't block notifications while we fetch the data. We clear
943 // mMetadataUpdated first so we don't lose notifications happening
944 // during the rest of this call.
945 {
946 Mutex::Autolock lock(mLock);
947 if (update_only) {
niko89948372009-07-16 16:39:53 -0700948 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700949 }
950 mMetadataUpdated.clear();
951 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700952
nikobc726922009-07-20 15:07:26 -0700953 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700954
nikobc726922009-07-20 15:07:26 -0700955 metadata.appendHeader();
956 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700957
958 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700959 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700960 LOGE("getMetadata failed %d", status);
961 return status;
962 }
963
964 // FIXME: Implement filtering on the result. Not critical since
965 // filtering takes place on the update notifications already. This
966 // would be when all the metadata are fetch and a filter is set.
967
niko89948372009-07-16 16:39:53 -0700968 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700969 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700970 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700971}
972
Andreas Huberfbb38852010-02-12 12:35:58 -0800973status_t MediaPlayerService::Client::suspend() {
974 sp<MediaPlayerBase> p = getPlayer();
975 if (p == 0) return UNKNOWN_ERROR;
976
977 return p->suspend();
978}
979
980status_t MediaPlayerService::Client::resume() {
981 sp<MediaPlayerBase> p = getPlayer();
982 if (p == 0) return UNKNOWN_ERROR;
983
984 return p->resume();
985}
986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987status_t MediaPlayerService::Client::prepareAsync()
988{
989 LOGV("[%d] prepareAsync", mConnId);
990 sp<MediaPlayerBase> p = getPlayer();
991 if (p == 0) return UNKNOWN_ERROR;
992 status_t ret = p->prepareAsync();
993#if CALLBACK_ANTAGONIZER
994 LOGD("start Antagonizer");
995 if (ret == NO_ERROR) mAntagonizer->start();
996#endif
997 return ret;
998}
999
1000status_t MediaPlayerService::Client::start()
1001{
1002 LOGV("[%d] start", mConnId);
1003 sp<MediaPlayerBase> p = getPlayer();
1004 if (p == 0) return UNKNOWN_ERROR;
1005 p->setLooping(mLoop);
1006 return p->start();
1007}
1008
1009status_t MediaPlayerService::Client::stop()
1010{
1011 LOGV("[%d] stop", mConnId);
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 return p->stop();
1015}
1016
1017status_t MediaPlayerService::Client::pause()
1018{
1019 LOGV("[%d] pause", mConnId);
1020 sp<MediaPlayerBase> p = getPlayer();
1021 if (p == 0) return UNKNOWN_ERROR;
1022 return p->pause();
1023}
1024
1025status_t MediaPlayerService::Client::isPlaying(bool* state)
1026{
1027 *state = false;
1028 sp<MediaPlayerBase> p = getPlayer();
1029 if (p == 0) return UNKNOWN_ERROR;
1030 *state = p->isPlaying();
1031 LOGV("[%d] isPlaying: %d", mConnId, *state);
1032 return NO_ERROR;
1033}
1034
1035status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1036{
1037 LOGV("getCurrentPosition");
1038 sp<MediaPlayerBase> p = getPlayer();
1039 if (p == 0) return UNKNOWN_ERROR;
1040 status_t ret = p->getCurrentPosition(msec);
1041 if (ret == NO_ERROR) {
1042 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1043 } else {
1044 LOGE("getCurrentPosition returned %d", ret);
1045 }
1046 return ret;
1047}
1048
1049status_t MediaPlayerService::Client::getDuration(int *msec)
1050{
1051 LOGV("getDuration");
1052 sp<MediaPlayerBase> p = getPlayer();
1053 if (p == 0) return UNKNOWN_ERROR;
1054 status_t ret = p->getDuration(msec);
1055 if (ret == NO_ERROR) {
1056 LOGV("[%d] getDuration = %d", mConnId, *msec);
1057 } else {
1058 LOGE("getDuration returned %d", ret);
1059 }
1060 return ret;
1061}
1062
1063status_t MediaPlayerService::Client::seekTo(int msec)
1064{
1065 LOGV("[%d] seekTo(%d)", mConnId, msec);
1066 sp<MediaPlayerBase> p = getPlayer();
1067 if (p == 0) return UNKNOWN_ERROR;
1068 return p->seekTo(msec);
1069}
1070
1071status_t MediaPlayerService::Client::reset()
1072{
1073 LOGV("[%d] reset", mConnId);
1074 sp<MediaPlayerBase> p = getPlayer();
1075 if (p == 0) return UNKNOWN_ERROR;
1076 return p->reset();
1077}
1078
1079status_t MediaPlayerService::Client::setAudioStreamType(int type)
1080{
1081 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1082 // TODO: for hardware output, call player instead
1083 Mutex::Autolock l(mLock);
1084 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1085 return NO_ERROR;
1086}
1087
1088status_t MediaPlayerService::Client::setLooping(int loop)
1089{
1090 LOGV("[%d] setLooping(%d)", mConnId, loop);
1091 mLoop = loop;
1092 sp<MediaPlayerBase> p = getPlayer();
1093 if (p != 0) return p->setLooping(loop);
1094 return NO_ERROR;
1095}
1096
1097status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1098{
1099 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1100 // TODO: for hardware output, call player instead
1101 Mutex::Autolock l(mLock);
1102 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1103 return NO_ERROR;
1104}
1105
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1108{
1109 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001110
1111 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001112 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001113 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001114
1115 if(client->shouldDropMetadata(metadata_type)) {
1116 return;
1117 }
1118
1119 // Update the list of metadata that have changed. getMetadata
1120 // also access mMetadataUpdated and clears it.
1121 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1124 client->mClient->notify(msg, ext1, ext2);
1125}
1126
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001127
nikobc726922009-07-20 15:07:26 -07001128bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001129{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001130 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001131
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001132 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001133 return true;
1134 }
1135
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001136 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001137 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001138 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001139 return true;
1140 }
1141}
1142
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001143
nikobc726922009-07-20 15:07:26 -07001144void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001145 Mutex::Autolock lock(mLock);
1146 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1147 mMetadataUpdated.add(metadata_type);
1148 }
1149}
1150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151#if CALLBACK_ANTAGONIZER
1152const int Antagonizer::interval = 10000; // 10 msecs
1153
1154Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1155 mExit(false), mActive(false), mClient(client), mCb(cb)
1156{
1157 createThread(callbackThread, this);
1158}
1159
1160void Antagonizer::kill()
1161{
1162 Mutex::Autolock _l(mLock);
1163 mActive = false;
1164 mExit = true;
1165 mCondition.wait(mLock);
1166}
1167
1168int Antagonizer::callbackThread(void* user)
1169{
1170 LOGD("Antagonizer started");
1171 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1172 while (!p->mExit) {
1173 if (p->mActive) {
1174 LOGV("send event");
1175 p->mCb(p->mClient, 0, 0, 0);
1176 }
1177 usleep(interval);
1178 }
1179 Mutex::Autolock _l(p->mLock);
1180 p->mCondition.signal();
1181 LOGD("Antagonizer stopped");
1182 return 0;
1183}
1184#endif
1185
1186static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1187
1188sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1189{
1190 LOGV("decode(%s)", url);
1191 sp<MemoryBase> mem;
1192 sp<MediaPlayerBase> player;
1193
1194 // Protect our precious, precious DRMd ringtones by only allowing
1195 // decoding of http, but not filesystem paths or content Uris.
1196 // If the application wants to decode those, it should open a
1197 // filedescriptor for them and use that.
1198 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1199 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1200 return mem;
1201 }
1202
1203 player_type playerType = getPlayerType(url);
1204 LOGV("player type = %d", playerType);
1205
1206 // create the right type of player
1207 sp<AudioCache> cache = new AudioCache(url);
1208 player = android::createPlayer(playerType, cache.get(), cache->notify);
1209 if (player == NULL) goto Exit;
1210 if (player->hardwareOutput()) goto Exit;
1211
1212 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1213
1214 // set data source
1215 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1216
1217 LOGV("prepare");
1218 player->prepareAsync();
1219
1220 LOGV("wait for prepare");
1221 if (cache->wait() != NO_ERROR) goto Exit;
1222
1223 LOGV("start");
1224 player->start();
1225
1226 LOGV("wait for playback complete");
1227 if (cache->wait() != NO_ERROR) goto Exit;
1228
1229 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1230 *pSampleRate = cache->sampleRate();
1231 *pNumChannels = cache->channelCount();
1232 *pFormat = cache->format();
1233 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1234
1235Exit:
1236 if (player != 0) player->reset();
1237 return mem;
1238}
1239
1240sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1241{
1242 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1243 sp<MemoryBase> mem;
1244 sp<MediaPlayerBase> player;
1245
1246 player_type playerType = getPlayerType(fd, offset, length);
1247 LOGV("player type = %d", playerType);
1248
1249 // create the right type of player
1250 sp<AudioCache> cache = new AudioCache("decode_fd");
1251 player = android::createPlayer(playerType, cache.get(), cache->notify);
1252 if (player == NULL) goto Exit;
1253 if (player->hardwareOutput()) goto Exit;
1254
1255 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1256
1257 // set data source
1258 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1259
1260 LOGV("prepare");
1261 player->prepareAsync();
1262
1263 LOGV("wait for prepare");
1264 if (cache->wait() != NO_ERROR) goto Exit;
1265
1266 LOGV("start");
1267 player->start();
1268
1269 LOGV("wait for playback complete");
1270 if (cache->wait() != NO_ERROR) goto Exit;
1271
1272 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1273 *pSampleRate = cache->sampleRate();
1274 *pNumChannels = cache->channelCount();
1275 *pFormat = cache->format();
1276 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1277
1278Exit:
1279 if (player != 0) player->reset();
1280 ::close(fd);
1281 return mem;
1282}
1283
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001284/*
1285 * Avert your eyes, ugly hack ahead.
1286 * The following is to support music visualizations.
1287 */
1288
1289static const int NUMVIZBUF = 32;
1290static const int VIZBUFFRAMES = 1024;
Marco Nelissene274db12010-01-12 09:23:54 -08001291static const int BUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1292static const int TOTALBUFTIMEMSEC = NUMVIZBUF * BUFTIMEMSEC;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001293
1294static bool gotMem = false;
Marco Nelissene274db12010-01-12 09:23:54 -08001295static sp<MemoryHeapBase> heap;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001296static sp<MemoryBase> mem[NUMVIZBUF];
Marco Nelissene274db12010-01-12 09:23:54 -08001297static uint64_t endTime;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001298static uint64_t lastReadTime;
1299static uint64_t lastWriteTime;
1300static int writeIdx = 0;
1301
1302static void allocVizBufs() {
1303 if (!gotMem) {
Marco Nelissene274db12010-01-12 09:23:54 -08001304 heap = new MemoryHeapBase(NUMVIZBUF * VIZBUFFRAMES * 2, 0, "snooper");
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001305 for (int i=0;i<NUMVIZBUF;i++) {
Marco Nelissene274db12010-01-12 09:23:54 -08001306 mem[i] = new MemoryBase(heap, VIZBUFFRAMES * 2 * i, VIZBUFFRAMES * 2);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001307 }
Marco Nelissene274db12010-01-12 09:23:54 -08001308 endTime = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001309 gotMem = true;
1310 }
1311}
1312
1313
1314/*
1315 * Get a buffer of audio data that is about to be played.
1316 * We don't synchronize this because in practice the writer
1317 * is ahead of the reader, and even if we did happen to catch
1318 * a buffer while it's being written, it's just a visualization,
1319 * so no harm done.
1320 */
1321static sp<MemoryBase> getVizBuffer() {
1322
1323 allocVizBufs();
1324
Marco Nelissene274db12010-01-12 09:23:54 -08001325 lastReadTime = uptimeMillis();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001326
1327 // if there is no recent buffer (yet), just return empty handed
1328 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
Marco Nelissene274db12010-01-12 09:23:54 -08001329 //LOGI("@@@@ no audio data to look at yet: %d + %d < %d", (int)lastWriteTime, TOTALBUFTIMEMSEC, (int)lastReadTime);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001330 return NULL;
1331 }
1332
Marco Nelissene274db12010-01-12 09:23:54 -08001333 int timedelta = endTime - lastReadTime;
1334 if (timedelta < 0) timedelta = 0;
1335 int framedelta = timedelta * 44100 / 1000;
1336 int headIdx = (writeIdx - framedelta) / VIZBUFFRAMES - 1;
1337 while (headIdx < 0) {
1338 headIdx += NUMVIZBUF;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001339 }
Marco Nelissene274db12010-01-12 09:23:54 -08001340 return mem[headIdx];
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001341}
1342
Marco Nelissene274db12010-01-12 09:23:54 -08001343// Append the data to the vizualization buffer
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001344static void makeVizBuffers(const char *data, int len, uint64_t time) {
1345
1346 allocVizBufs();
1347
1348 uint64_t startTime = time;
1349 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
Marco Nelissene274db12010-01-12 09:23:54 -08001350 int offset = writeIdx;
1351 int maxoff = heap->getSize() / 2; // in shorts
1352 short *base = (short*)heap->getBase();
1353 short *src = (short*)data;
1354 while (len > 0) {
1355
1356 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1357 // This should still be good enough for a visualization
1358 base[offset++] = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1359 src += 2;
1360 len -= frameSize;
1361 if (offset >= maxoff) {
1362 offset = 0;
1363 }
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001364 }
Marco Nelissene274db12010-01-12 09:23:54 -08001365 writeIdx = offset;
1366 endTime = time + (len / frameSize) / 44;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001367 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1368}
1369
1370sp<IMemory> MediaPlayerService::snoop()
1371{
1372 sp<MemoryBase> mem = getVizBuffer();
1373 return mem;
1374}
1375
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377#undef LOG_TAG
1378#define LOG_TAG "AudioSink"
1379MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001380 : mCallback(NULL),
1381 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 mTrack = 0;
1383 mStreamType = AudioSystem::MUSIC;
1384 mLeftVolume = 1.0;
1385 mRightVolume = 1.0;
1386 mLatency = 0;
1387 mMsecsPerFrame = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001388 mNumFramesWritten = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 setMinBufferCount();
1390}
1391
1392MediaPlayerService::AudioOutput::~AudioOutput()
1393{
1394 close();
1395}
1396
1397void MediaPlayerService::AudioOutput::setMinBufferCount()
1398{
1399 char value[PROPERTY_VALUE_MAX];
1400 if (property_get("ro.kernel.qemu", value, 0)) {
1401 mIsOnEmulator = true;
1402 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1403 }
1404}
1405
1406bool MediaPlayerService::AudioOutput::isOnEmulator()
1407{
1408 setMinBufferCount();
1409 return mIsOnEmulator;
1410}
1411
1412int MediaPlayerService::AudioOutput::getMinBufferCount()
1413{
1414 setMinBufferCount();
1415 return mMinBufferCount;
1416}
1417
1418ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1419{
1420 if (mTrack == 0) return NO_INIT;
1421 return mTrack->frameCount() * frameSize();
1422}
1423
1424ssize_t MediaPlayerService::AudioOutput::frameCount() const
1425{
1426 if (mTrack == 0) return NO_INIT;
1427 return mTrack->frameCount();
1428}
1429
1430ssize_t MediaPlayerService::AudioOutput::channelCount() const
1431{
1432 if (mTrack == 0) return NO_INIT;
1433 return mTrack->channelCount();
1434}
1435
1436ssize_t MediaPlayerService::AudioOutput::frameSize() const
1437{
1438 if (mTrack == 0) return NO_INIT;
1439 return mTrack->frameSize();
1440}
1441
1442uint32_t MediaPlayerService::AudioOutput::latency () const
1443{
1444 return mLatency;
1445}
1446
1447float MediaPlayerService::AudioOutput::msecsPerFrame() const
1448{
1449 return mMsecsPerFrame;
1450}
1451
Eric Laurent0986e792010-01-19 17:37:09 -08001452status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1453{
1454 if (mTrack == 0) return NO_INIT;
1455 return mTrack->getPosition(position);
1456}
1457
Andreas Hubere46b7be2009-07-14 16:56:47 -07001458status_t MediaPlayerService::AudioOutput::open(
1459 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1460 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001462 mCallback = cb;
1463 mCallbackCookie = cookie;
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 // Check argument "bufferCount" against the mininum buffer count
1466 if (bufferCount < mMinBufferCount) {
1467 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1468 bufferCount = mMinBufferCount;
1469
1470 }
1471 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1472 if (mTrack) close();
1473 int afSampleRate;
1474 int afFrameCount;
1475 int frameCount;
1476
1477 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1478 return NO_INIT;
1479 }
1480 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1481 return NO_INIT;
1482 }
1483
1484 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001485
1486 AudioTrack *t;
1487 if (mCallback != NULL) {
1488 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001489 mStreamType,
1490 sampleRate,
1491 format,
1492 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1493 frameCount,
1494 0 /* flags */,
1495 CallbackWrapper,
1496 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001497 } else {
1498 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001499 mStreamType,
1500 sampleRate,
1501 format,
1502 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1503 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001504 }
1505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1507 LOGE("Unable to create audio track");
1508 delete t;
1509 return NO_INIT;
1510 }
1511
1512 LOGV("setVolume");
1513 t->setVolume(mLeftVolume, mRightVolume);
1514 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001515 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 mTrack = t;
1517 return NO_ERROR;
1518}
1519
1520void MediaPlayerService::AudioOutput::start()
1521{
1522 LOGV("start");
1523 if (mTrack) {
1524 mTrack->setVolume(mLeftVolume, mRightVolume);
1525 mTrack->start();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001526 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528}
1529
Marco Nelissene274db12010-01-12 09:23:54 -08001530void MediaPlayerService::AudioOutput::snoopWrite(const void* buffer, size_t size) {
1531 // Only make visualization buffers if anyone recently requested visualization data
1532 uint64_t now = uptimeMillis();
1533 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1534 // Based on the current play counter, the number of frames written and
1535 // the current real time we can calculate the approximate real start
1536 // time of the buffer we're about to write.
1537 uint32_t pos;
1538 mTrack->getPosition(&pos);
1539
1540 // we're writing ahead by this many frames:
1541 int ahead = mNumFramesWritten - pos;
1542 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1543 // which is this many milliseconds, assuming 44100 Hz:
1544 ahead /= 44;
1545
1546 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1547 lastWriteTime = now;
1548 }
1549}
1550
1551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1553{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001554 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001557 if (mTrack) {
Marco Nelissene274db12010-01-12 09:23:54 -08001558 snoopWrite(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001559 ssize_t ret = mTrack->write(buffer, size);
1560 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1561 return ret;
1562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 return NO_INIT;
1564}
1565
1566void MediaPlayerService::AudioOutput::stop()
1567{
1568 LOGV("stop");
1569 if (mTrack) mTrack->stop();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001570 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571}
1572
1573void MediaPlayerService::AudioOutput::flush()
1574{
1575 LOGV("flush");
1576 if (mTrack) mTrack->flush();
1577}
1578
1579void MediaPlayerService::AudioOutput::pause()
1580{
1581 LOGV("pause");
1582 if (mTrack) mTrack->pause();
Marco Nelissen758613d2009-11-02 13:52:11 -08001583 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584}
1585
1586void MediaPlayerService::AudioOutput::close()
1587{
1588 LOGV("close");
1589 delete mTrack;
1590 mTrack = 0;
1591}
1592
1593void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1594{
1595 LOGV("setVolume(%f, %f)", left, right);
1596 mLeftVolume = left;
1597 mRightVolume = right;
1598 if (mTrack) {
1599 mTrack->setVolume(left, right);
1600 }
1601}
1602
Andreas Hubere46b7be2009-07-14 16:56:47 -07001603// static
1604void MediaPlayerService::AudioOutput::CallbackWrapper(
1605 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001606 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001607 if (event != AudioTrack::EVENT_MORE_DATA) {
1608 return;
1609 }
1610
1611 AudioOutput *me = (AudioOutput *)cookie;
1612 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1613
Andreas Huber6ed937e2010-02-09 16:59:18 -08001614 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001615 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001616
Andreas Huber406a18b2010-02-18 16:45:13 -08001617 buffer->size = actualSize;
1618
Andreas Huber6ed937e2010-02-09 16:59:18 -08001619 if (actualSize > 0) {
1620 me->snoopWrite(buffer->raw, actualSize);
1621 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001622}
1623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624#undef LOG_TAG
1625#define LOG_TAG "AudioCache"
1626MediaPlayerService::AudioCache::AudioCache(const char* name) :
1627 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1628 mError(NO_ERROR), mCommandComplete(false)
1629{
1630 // create ashmem heap
1631 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1632}
1633
1634uint32_t MediaPlayerService::AudioCache::latency () const
1635{
1636 return 0;
1637}
1638
1639float MediaPlayerService::AudioCache::msecsPerFrame() const
1640{
1641 return mMsecsPerFrame;
1642}
1643
Eric Laurent0986e792010-01-19 17:37:09 -08001644status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1645{
1646 if (position == 0) return BAD_VALUE;
1647 *position = mSize;
1648 return NO_ERROR;
1649}
1650
Andreas Huber6ed937e2010-02-09 16:59:18 -08001651////////////////////////////////////////////////////////////////////////////////
1652
1653struct CallbackThread : public Thread {
1654 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1655 MediaPlayerBase::AudioSink::AudioCallback cb,
1656 void *cookie);
1657
1658protected:
1659 virtual ~CallbackThread();
1660
1661 virtual bool threadLoop();
1662
1663private:
1664 wp<MediaPlayerBase::AudioSink> mSink;
1665 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1666 void *mCookie;
1667 void *mBuffer;
1668 size_t mBufferSize;
1669
1670 CallbackThread(const CallbackThread &);
1671 CallbackThread &operator=(const CallbackThread &);
1672};
1673
1674CallbackThread::CallbackThread(
1675 const wp<MediaPlayerBase::AudioSink> &sink,
1676 MediaPlayerBase::AudioSink::AudioCallback cb,
1677 void *cookie)
1678 : mSink(sink),
1679 mCallback(cb),
1680 mCookie(cookie),
1681 mBuffer(NULL),
1682 mBufferSize(0) {
1683}
1684
1685CallbackThread::~CallbackThread() {
1686 if (mBuffer) {
1687 free(mBuffer);
1688 mBuffer = NULL;
1689 }
1690}
1691
1692bool CallbackThread::threadLoop() {
1693 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1694 if (sink == NULL) {
1695 return false;
1696 }
1697
1698 if (mBuffer == NULL) {
1699 mBufferSize = sink->bufferSize();
1700 mBuffer = malloc(mBufferSize);
1701 }
1702
1703 size_t actualSize =
1704 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1705
1706 if (actualSize > 0) {
1707 sink->write(mBuffer, actualSize);
1708 }
1709
1710 return true;
1711}
1712
1713////////////////////////////////////////////////////////////////////////////////
1714
Andreas Hubere46b7be2009-07-14 16:56:47 -07001715status_t MediaPlayerService::AudioCache::open(
1716 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1717 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718{
Dave Sparks14f89402009-12-09 20:20:26 -08001719 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001720 if (mHeap->getHeapID() < 0) {
1721 return NO_INIT;
1722 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 mSampleRate = sampleRate;
1725 mChannelCount = (uint16_t)channelCount;
1726 mFormat = (uint16_t)format;
1727 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001728
1729 if (cb != NULL) {
1730 mCallbackThread = new CallbackThread(this, cb, cookie);
1731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 return NO_ERROR;
1733}
1734
Andreas Huber6ed937e2010-02-09 16:59:18 -08001735void MediaPlayerService::AudioCache::start() {
1736 if (mCallbackThread != NULL) {
1737 mCallbackThread->run("AudioCache callback");
1738 }
1739}
1740
1741void MediaPlayerService::AudioCache::stop() {
1742 if (mCallbackThread != NULL) {
1743 mCallbackThread->requestExitAndWait();
1744 }
1745}
1746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1748{
1749 LOGV("write(%p, %u)", buffer, size);
1750 if ((buffer == 0) || (size == 0)) return size;
1751
1752 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1753 if (p == NULL) return NO_INIT;
1754 p += mSize;
1755 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1756 if (mSize + size > mHeap->getSize()) {
1757 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1758 size = mHeap->getSize() - mSize;
1759 }
1760 memcpy(p, buffer, size);
1761 mSize += size;
1762 return size;
1763}
1764
1765// call with lock held
1766status_t MediaPlayerService::AudioCache::wait()
1767{
1768 Mutex::Autolock lock(mLock);
1769 if (!mCommandComplete) {
1770 mSignal.wait(mLock);
1771 }
1772 mCommandComplete = false;
1773
1774 if (mError == NO_ERROR) {
1775 LOGV("wait - success");
1776 } else {
1777 LOGV("wait - error");
1778 }
1779 return mError;
1780}
1781
1782void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1783{
1784 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1785 AudioCache* p = static_cast<AudioCache*>(cookie);
1786
1787 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001788 switch (msg)
1789 {
1790 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 LOGE("Error %d, %d occurred", ext1, ext2);
1792 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001793 break;
1794 case MEDIA_PREPARED:
1795 LOGV("prepared");
1796 break;
1797 case MEDIA_PLAYBACK_COMPLETE:
1798 LOGV("playback complete");
1799 break;
1800 default:
1801 LOGV("ignored");
1802 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804
1805 // wake up thread
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 p->mCommandComplete = true;
1807 p->mSignal.signal();
1808}
1809
nikobc726922009-07-20 15:07:26 -07001810} // namespace android