blob: 11f30168fdc98d861e1eb1cd6c498fce92cfed4b [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{
Gloria Wang608a2632009-10-29 15:46:37 -0700231 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
232 wp<MediaRecorderClient> w = recorder;
233 Mutex::Autolock lock(mLock);
234 mMediaRecorderClients.add(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 LOGV("Create new media recorder client from pid %d", pid);
236 return recorder;
237}
238
Gloria Wang608a2632009-10-29 15:46:37 -0700239void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
240{
241 Mutex::Autolock lock(mLock);
242 mMediaRecorderClients.remove(client);
243 LOGV("Delete media recorder client");
244}
245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
247{
248 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
249 LOGV("Create new media retriever from pid %d", pid);
250 return retriever;
251}
252
Andreas Huber25643002010-01-28 11:19:57 -0800253sp<IMediaPlayer> MediaPlayerService::create(
254 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
255 const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256{
257 int32_t connId = android_atomic_inc(&mNextConnId);
258 sp<Client> c = new Client(this, pid, connId, client);
259 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
Andreas Huber25643002010-01-28 11:19:57 -0800260 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 {
262 c.clear();
263 return c;
264 }
265 wp<Client> w = c;
266 Mutex::Autolock lock(mLock);
267 mClients.add(w);
268 return c;
269}
270
271sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
272 int fd, int64_t offset, int64_t length)
273{
274 int32_t connId = android_atomic_inc(&mNextConnId);
275 sp<Client> c = new Client(this, pid, connId, client);
276 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
277 connId, pid, fd, offset, length);
278 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
279 c.clear();
280 } else {
281 wp<Client> w = c;
282 Mutex::Autolock lock(mLock);
283 mClients.add(w);
284 }
285 ::close(fd);
286 return c;
287}
288
Andreas Huber784202e2009-10-15 13:46:54 -0700289sp<IOMX> MediaPlayerService::getOMX() {
290 Mutex::Autolock autoLock(mLock);
291
292 if (mOMX.get() == NULL) {
293 mOMX = new OMX;
294 }
295
296 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700297}
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
300{
301 const size_t SIZE = 256;
302 char buffer[SIZE];
303 String8 result;
304
305 result.append(" AudioCache\n");
306 if (mHeap != 0) {
307 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
308 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
309 result.append(buffer);
310 }
311 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
312 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
313 result.append(buffer);
314 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
315 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
316 result.append(buffer);
317 ::write(fd, result.string(), result.size());
318 return NO_ERROR;
319}
320
321status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
322{
323 const size_t SIZE = 256;
324 char buffer[SIZE];
325 String8 result;
326
327 result.append(" AudioOutput\n");
328 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
329 mStreamType, mLeftVolume, mRightVolume);
330 result.append(buffer);
331 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
332 mMsecsPerFrame, mLatency);
333 result.append(buffer);
334 ::write(fd, result.string(), result.size());
335 if (mTrack != 0) {
336 mTrack->dump(fd, args);
337 }
338 return NO_ERROR;
339}
340
341status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
342{
343 const size_t SIZE = 256;
344 char buffer[SIZE];
345 String8 result;
346 result.append(" Client\n");
347 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
348 mPid, mConnId, mStatus, mLoop?"true": "false");
349 result.append(buffer);
350 write(fd, result.string(), result.size());
351 if (mAudioOutput != 0) {
352 mAudioOutput->dump(fd, args);
353 }
354 write(fd, "\n", 1);
355 return NO_ERROR;
356}
357
358static int myTid() {
359#ifdef HAVE_GETTID
360 return gettid();
361#else
362 return getpid();
363#endif
364}
365
366#if defined(__arm__)
367extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
368 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
369extern "C" void free_malloc_leak_info(uint8_t* info);
370
Andreas Huber27123462009-10-27 15:50:04 -0700371// Use the String-class below instead of String8 to allocate all memory
372// beforehand and not reenter the heap while we are examining it...
373struct MyString8 {
374 static const size_t MAX_SIZE = 256 * 1024;
375
376 MyString8()
377 : mPtr((char *)malloc(MAX_SIZE)) {
378 *mPtr = '\0';
379 }
380
381 ~MyString8() {
382 free(mPtr);
383 }
384
385 void append(const char *s) {
386 strcat(mPtr, s);
387 }
388
389 const char *string() const {
390 return mPtr;
391 }
392
393 size_t size() const {
394 return strlen(mPtr);
395 }
396
397private:
398 char *mPtr;
399
400 MyString8(const MyString8 &);
401 MyString8 &operator=(const MyString8 &);
402};
403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404void memStatus(int fd, const Vector<String16>& args)
405{
406 const size_t SIZE = 256;
407 char buffer[SIZE];
Andreas Huber27123462009-10-27 15:50:04 -0700408 MyString8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409
410 typedef struct {
411 size_t size;
412 size_t dups;
413 intptr_t * backtrace;
414 } AllocEntry;
415
416 uint8_t *info = NULL;
417 size_t overallSize = 0;
418 size_t infoSize = 0;
419 size_t totalMemory = 0;
420 size_t backtraceSize = 0;
421
422 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
423 if (info) {
424 uint8_t *ptr = info;
425 size_t count = overallSize / infoSize;
426
427 snprintf(buffer, SIZE, " Allocation count %i\n", count);
428 result.append(buffer);
James Dong3d23a612010-02-25 10:06:32 -0800429 snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
430 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431
432 AllocEntry * entries = new AllocEntry[count];
433
434 for (size_t i = 0; i < count; i++) {
435 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
436 AllocEntry *e = &entries[i];
437
438 e->size = *reinterpret_cast<size_t *>(ptr);
439 ptr += sizeof(size_t);
440
441 e->dups = *reinterpret_cast<size_t *>(ptr);
442 ptr += sizeof(size_t);
443
444 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
445 ptr += sizeof(intptr_t) * backtraceSize;
446 }
447
448 // Now we need to sort the entries. They come sorted by size but
449 // not by stack trace which causes problems using diff.
450 bool moved;
451 do {
452 moved = false;
453 for (size_t i = 0; i < (count - 1); i++) {
454 AllocEntry *e1 = &entries[i];
455 AllocEntry *e2 = &entries[i+1];
456
457 bool swap = e1->size < e2->size;
458 if (e1->size == e2->size) {
459 for(size_t j = 0; j < backtraceSize; j++) {
460 if (e1->backtrace[j] == e2->backtrace[j]) {
461 continue;
462 }
463 swap = e1->backtrace[j] < e2->backtrace[j];
464 break;
465 }
466 }
467 if (swap) {
468 AllocEntry t = entries[i];
469 entries[i] = entries[i+1];
470 entries[i+1] = t;
471 moved = true;
472 }
473 }
474 } while (moved);
475
476 for (size_t i = 0; i < count; i++) {
477 AllocEntry *e = &entries[i];
478
James Dong3d23a612010-02-25 10:06:32 -0800479 snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 result.append(buffer);
481 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
482 if (ct) {
483 result.append(", ");
484 }
485 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
486 result.append(buffer);
487 }
488 result.append("\n");
489 }
490
491 delete[] entries;
492 free_malloc_leak_info(info);
493 }
494
495 write(fd, result.string(), result.size());
496}
497#endif
498
499status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
500{
501 const size_t SIZE = 256;
502 char buffer[SIZE];
503 String8 result;
504 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
505 snprintf(buffer, SIZE, "Permission Denial: "
506 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
507 IPCThreadState::self()->getCallingPid(),
508 IPCThreadState::self()->getCallingUid());
509 result.append(buffer);
510 } else {
511 Mutex::Autolock lock(mLock);
512 for (int i = 0, n = mClients.size(); i < n; ++i) {
513 sp<Client> c = mClients[i].promote();
514 if (c != 0) c->dump(fd, args);
515 }
Gloria Wang608a2632009-10-29 15:46:37 -0700516 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
517 result.append(" MediaRecorderClient\n");
518 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
519 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid);
520 result.append(buffer);
521 }
522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 result.append(" Files opened and/or mapped:\n");
524 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
525 FILE *f = fopen(buffer, "r");
526 if (f) {
527 while (!feof(f)) {
528 fgets(buffer, SIZE, f);
529 if (strstr(buffer, " /sdcard/") ||
530 strstr(buffer, " /system/sounds/") ||
531 strstr(buffer, " /system/media/")) {
532 result.append(" ");
533 result.append(buffer);
534 }
535 }
536 fclose(f);
537 } else {
538 result.append("couldn't open ");
539 result.append(buffer);
540 result.append("\n");
541 }
542
543 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
544 DIR *d = opendir(buffer);
545 if (d) {
546 struct dirent *ent;
547 while((ent = readdir(d)) != NULL) {
548 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
549 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
550 struct stat s;
551 if (lstat(buffer, &s) == 0) {
552 if ((s.st_mode & S_IFMT) == S_IFLNK) {
553 char linkto[256];
554 int len = readlink(buffer, linkto, sizeof(linkto));
555 if(len > 0) {
556 if(len > 255) {
557 linkto[252] = '.';
558 linkto[253] = '.';
559 linkto[254] = '.';
560 linkto[255] = 0;
561 } else {
562 linkto[len] = 0;
563 }
564 if (strstr(linkto, "/sdcard/") == linkto ||
565 strstr(linkto, "/system/sounds/") == linkto ||
566 strstr(linkto, "/system/media/") == linkto) {
567 result.append(" ");
568 result.append(buffer);
569 result.append(" -> ");
570 result.append(linkto);
571 result.append("\n");
572 }
573 }
574 } else {
575 result.append(" unexpected type for ");
576 result.append(buffer);
577 result.append("\n");
578 }
579 }
580 }
581 }
582 closedir(d);
583 } else {
584 result.append("couldn't open ");
585 result.append(buffer);
586 result.append("\n");
587 }
588
589#if defined(__arm__)
590 bool dumpMem = false;
591 for (size_t i = 0; i < args.size(); i++) {
592 if (args[i] == String16("-m")) {
593 dumpMem = true;
594 }
595 }
596 if (dumpMem) {
597 memStatus(fd, args);
598 }
599#endif
600 }
601 write(fd, result.string(), result.size());
602 return NO_ERROR;
603}
604
605void MediaPlayerService::removeClient(wp<Client> client)
606{
607 Mutex::Autolock lock(mLock);
608 mClients.remove(client);
609}
610
611MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
612 int32_t connId, const sp<IMediaPlayerClient>& client)
613{
614 LOGV("Client(%d) constructor", connId);
615 mPid = pid;
616 mConnId = connId;
617 mService = service;
618 mClient = client;
619 mLoop = false;
620 mStatus = NO_INIT;
621#if CALLBACK_ANTAGONIZER
622 LOGD("create Antagonizer");
623 mAntagonizer = new Antagonizer(notify, this);
624#endif
625}
626
627MediaPlayerService::Client::~Client()
628{
629 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
630 mAudioOutput.clear();
631 wp<Client> client(this);
632 disconnect();
633 mService->removeClient(client);
634}
635
636void MediaPlayerService::Client::disconnect()
637{
638 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
639 // grab local reference and clear main reference to prevent future
640 // access to object
641 sp<MediaPlayerBase> p;
642 {
643 Mutex::Autolock l(mLock);
644 p = mPlayer;
645 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700646 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 mPlayer.clear();
649
650 // clear the notification to prevent callbacks to dead client
651 // and reset the player. We assume the player will serialize
652 // access to itself if necessary.
653 if (p != 0) {
654 p->setNotifyCallback(0, 0);
655#if CALLBACK_ANTAGONIZER
656 LOGD("kill Antagonizer");
657 mAntagonizer->kill();
658#endif
659 p->reset();
660 }
661
662 IPCThreadState::self()->flushCommands();
663}
664
Andreas Huber0d596d42009-08-07 09:30:32 -0700665static player_type getDefaultPlayerType() {
Andreas Huber2aa39c42009-09-11 09:54:52 -0700666#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber0d596d42009-08-07 09:30:32 -0700667 char value[PROPERTY_VALUE_MAX];
668 if (property_get("media.stagefright.enable-player", value, NULL)
669 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
670 return STAGEFRIGHT_PLAYER;
671 }
Andreas Huber2aa39c42009-09-11 09:54:52 -0700672#endif
Andreas Huber0d596d42009-08-07 09:30:32 -0700673
674 return PV_PLAYER;
675}
676
Andreas Hubereb5eef32010-05-04 11:46:42 -0700677// By default we use the VORBIS_PLAYER for vorbis playback (duh!),
678// but if the magic property is set we will use our new experimental
679// stagefright code instead.
680static player_type OverrideStagefrightForVorbis(player_type player) {
681 if (player != VORBIS_PLAYER) {
682 return player;
683 }
684
685#if BUILD_WITH_FULL_STAGEFRIGHT
686 char value[PROPERTY_VALUE_MAX];
687 if (property_get("media.stagefright.enable-vorbis", value, NULL)
688 && (!strcmp(value, "1") || !strcmp(value, "true"))) {
689 return STAGEFRIGHT_PLAYER;
690 }
691#endif
692
693 return VORBIS_PLAYER;
694}
695
696
James Dong392ff3b2009-09-06 14:29:45 -0700697player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698{
699 char buf[20];
700 lseek(fd, offset, SEEK_SET);
701 read(fd, buf, sizeof(buf));
702 lseek(fd, offset, SEEK_SET);
703
704 long ident = *((long*)buf);
705
706 // Ogg vorbis?
707 if (ident == 0x5367674f) // 'OggS'
Andreas Hubereb5eef32010-05-04 11:46:42 -0700708 return OverrideStagefrightForVorbis(VORBIS_PLAYER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800710#ifndef NO_OPENCORE
711 if (ident == 0x75b22630) {
712 // The magic number for .asf files, i.e. wmv and wma content.
713 // These are not currently supported through stagefright.
714 return PV_PLAYER;
715 }
716#endif
717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 // Some kind of MIDI?
719 EAS_DATA_HANDLE easdata;
720 if (EAS_Init(&easdata) == EAS_SUCCESS) {
721 EAS_FILE locator;
722 locator.path = NULL;
723 locator.fd = fd;
724 locator.offset = offset;
725 locator.length = length;
726 EAS_HANDLE eashandle;
727 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
728 EAS_CloseFile(easdata, eashandle);
729 EAS_Shutdown(easdata);
730 return SONIVOX_PLAYER;
731 }
732 EAS_Shutdown(easdata);
733 }
734
Andreas Huber0d596d42009-08-07 09:30:32 -0700735 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736}
737
James Dong392ff3b2009-09-06 14:29:45 -0700738player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700740 if (TestPlayerStub::canBeUsed(url)) {
741 return TEST_PLAYER;
742 }
743
Andreas Hubereb5eef32010-05-04 11:46:42 -0700744 bool useStagefrightForHTTP = false;
745 char value[PROPERTY_VALUE_MAX];
746 if (property_get("media.stagefright.enable-http", value, NULL)
747 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
748 useStagefrightForHTTP = true;
749 }
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 // use MidiFile for MIDI extensions
752 int lenURL = strlen(url);
753 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
754 int len = strlen(FILE_EXTS[i].extension);
755 int start = lenURL - len;
756 if (start > 0) {
Atsushi Enoebcc51d2010-03-19 23:18:02 +0900757 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Hubereb5eef32010-05-04 11:46:42 -0700758 if (FILE_EXTS[i].playertype == VORBIS_PLAYER
759 && !strncasecmp(url, "http://", 7)
760 && useStagefrightForHTTP) {
761 return STAGEFRIGHT_PLAYER;
762 }
763 return OverrideStagefrightForVorbis(FILE_EXTS[i].playertype);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
765 }
766 }
767
Andreas Huber6a3a0182009-12-17 13:31:13 -0800768 if (!strncasecmp(url, "http://", 7)) {
Andreas Hubereb5eef32010-05-04 11:46:42 -0700769 if (!useStagefrightForHTTP) {
Andreas Huber67aee052010-01-04 17:27:37 -0800770 return PV_PLAYER;
771 }
Andreas Huber6a3a0182009-12-17 13:31:13 -0800772 }
773
James Dong42d66572010-04-13 21:33:26 -0700774 // Use PV_PLAYER for rtsp for now
775 if (!strncasecmp(url, "rtsp://", 7)) {
776 return PV_PLAYER;
777 }
778
Andreas Huber0d596d42009-08-07 09:30:32 -0700779 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780}
781
782static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
783 notify_callback_f notifyFunc)
784{
785 sp<MediaPlayerBase> p;
786 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700787#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 case PV_PLAYER:
789 LOGV(" create PVPlayer");
790 p = new PVPlayer();
791 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700792#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 case SONIVOX_PLAYER:
794 LOGV(" create MidiFile");
795 p = new MidiFile();
796 break;
797 case VORBIS_PLAYER:
798 LOGV(" create VorbisPlayer");
799 p = new VorbisPlayer();
800 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700801#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Hubere46b7be2009-07-14 16:56:47 -0700802 case STAGEFRIGHT_PLAYER:
803 LOGV(" create StagefrightPlayer");
804 p = new StagefrightPlayer;
805 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700806#endif
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700807 case TEST_PLAYER:
808 LOGV("Create Test Player stub");
809 p = new TestPlayerStub();
810 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
812 if (p != NULL) {
813 if (p->initCheck() == NO_ERROR) {
814 p->setNotifyCallback(cookie, notifyFunc);
815 } else {
816 p.clear();
817 }
818 }
819 if (p == NULL) {
820 LOGE("Failed to create player object");
821 }
822 return p;
823}
824
825sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
826{
827 // determine if we have the right player type
828 sp<MediaPlayerBase> p = mPlayer;
829 if ((p != NULL) && (p->playerType() != playerType)) {
830 LOGV("delete player");
831 p.clear();
832 }
833 if (p == NULL) {
834 p = android::createPlayer(playerType, this, notify);
835 }
836 return p;
837}
838
Andreas Huber25643002010-01-28 11:19:57 -0800839status_t MediaPlayerService::Client::setDataSource(
840 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841{
842 LOGV("setDataSource(%s)", url);
843 if (url == NULL)
844 return UNKNOWN_ERROR;
845
846 if (strncmp(url, "content://", 10) == 0) {
847 // get a filedescriptor for the content Uri and
848 // pass it to the setDataSource(fd) method
849
850 String16 url16(url);
851 int fd = android::openContentProviderFile(url16);
852 if (fd < 0)
853 {
854 LOGE("Couldn't open fd for %s", url);
855 return UNKNOWN_ERROR;
856 }
857 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
858 close(fd);
859 return mStatus;
860 } else {
861 player_type playerType = getPlayerType(url);
862 LOGV("player type = %d", playerType);
863
864 // create the right type of player
865 sp<MediaPlayerBase> p = createPlayer(playerType);
866 if (p == NULL) return NO_INIT;
867
868 if (!p->hardwareOutput()) {
869 mAudioOutput = new AudioOutput();
870 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
871 }
872
873 // now set data source
874 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800875 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700876 if (mStatus == NO_ERROR) {
877 mPlayer = p;
878 } else {
879 LOGE(" error: %d", mStatus);
880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 return mStatus;
882 }
883}
884
885status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
886{
887 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
888 struct stat sb;
889 int ret = fstat(fd, &sb);
890 if (ret != 0) {
891 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
892 return UNKNOWN_ERROR;
893 }
894
895 LOGV("st_dev = %llu", sb.st_dev);
896 LOGV("st_mode = %u", sb.st_mode);
897 LOGV("st_uid = %lu", sb.st_uid);
898 LOGV("st_gid = %lu", sb.st_gid);
899 LOGV("st_size = %llu", sb.st_size);
900
901 if (offset >= sb.st_size) {
902 LOGE("offset error");
903 ::close(fd);
904 return UNKNOWN_ERROR;
905 }
906 if (offset + length > sb.st_size) {
907 length = sb.st_size - offset;
908 LOGV("calculated length = %lld", length);
909 }
910
911 player_type playerType = getPlayerType(fd, offset, length);
912 LOGV("player type = %d", playerType);
913
914 // create the right type of player
915 sp<MediaPlayerBase> p = createPlayer(playerType);
916 if (p == NULL) return NO_INIT;
917
918 if (!p->hardwareOutput()) {
919 mAudioOutput = new AudioOutput();
920 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
921 }
922
923 // now set data source
924 mStatus = p->setDataSource(fd, offset, length);
925 if (mStatus == NO_ERROR) mPlayer = p;
926 return mStatus;
927}
928
929status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
930{
931 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
932 sp<MediaPlayerBase> p = getPlayer();
933 if (p == 0) return UNKNOWN_ERROR;
934 return p->setVideoSurface(surface);
935}
936
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700937status_t MediaPlayerService::Client::invoke(const Parcel& request,
938 Parcel *reply)
939{
940 sp<MediaPlayerBase> p = getPlayer();
941 if (p == NULL) return UNKNOWN_ERROR;
942 return p->invoke(request, reply);
943}
944
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700945// This call doesn't need to access the native player.
946status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
947{
948 status_t status;
nikobc726922009-07-20 15:07:26 -0700949 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700950
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700951 if (unmarshallFilter(filter, &allow, &status) &&
952 unmarshallFilter(filter, &drop, &status)) {
953 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700954
955 mMetadataAllow = allow;
956 mMetadataDrop = drop;
957 }
958 return status;
959}
960
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700961status_t MediaPlayerService::Client::getMetadata(
962 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700963{
nikobc726922009-07-20 15:07:26 -0700964 sp<MediaPlayerBase> player = getPlayer();
965 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700966
niko89948372009-07-16 16:39:53 -0700967 status_t status;
968 // Placeholder for the return code, updated by the caller.
969 reply->writeInt32(-1);
970
nikobc726922009-07-20 15:07:26 -0700971 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700972
973 // We don't block notifications while we fetch the data. We clear
974 // mMetadataUpdated first so we don't lose notifications happening
975 // during the rest of this call.
976 {
977 Mutex::Autolock lock(mLock);
978 if (update_only) {
niko89948372009-07-16 16:39:53 -0700979 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700980 }
981 mMetadataUpdated.clear();
982 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700983
nikobc726922009-07-20 15:07:26 -0700984 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700985
nikobc726922009-07-20 15:07:26 -0700986 metadata.appendHeader();
987 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700988
989 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700990 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700991 LOGE("getMetadata failed %d", status);
992 return status;
993 }
994
995 // FIXME: Implement filtering on the result. Not critical since
996 // filtering takes place on the update notifications already. This
997 // would be when all the metadata are fetch and a filter is set.
998
niko89948372009-07-16 16:39:53 -0700999 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -07001000 metadata.updateLength();
niko89948372009-07-16 16:39:53 -07001001 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -07001002}
1003
Andreas Huberfbb38852010-02-12 12:35:58 -08001004status_t MediaPlayerService::Client::suspend() {
1005 sp<MediaPlayerBase> p = getPlayer();
1006 if (p == 0) return UNKNOWN_ERROR;
1007
1008 return p->suspend();
1009}
1010
1011status_t MediaPlayerService::Client::resume() {
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014
1015 return p->resume();
1016}
1017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018status_t MediaPlayerService::Client::prepareAsync()
1019{
1020 LOGV("[%d] prepareAsync", mConnId);
1021 sp<MediaPlayerBase> p = getPlayer();
1022 if (p == 0) return UNKNOWN_ERROR;
1023 status_t ret = p->prepareAsync();
1024#if CALLBACK_ANTAGONIZER
1025 LOGD("start Antagonizer");
1026 if (ret == NO_ERROR) mAntagonizer->start();
1027#endif
1028 return ret;
1029}
1030
1031status_t MediaPlayerService::Client::start()
1032{
1033 LOGV("[%d] start", mConnId);
1034 sp<MediaPlayerBase> p = getPlayer();
1035 if (p == 0) return UNKNOWN_ERROR;
1036 p->setLooping(mLoop);
1037 return p->start();
1038}
1039
1040status_t MediaPlayerService::Client::stop()
1041{
1042 LOGV("[%d] stop", mConnId);
1043 sp<MediaPlayerBase> p = getPlayer();
1044 if (p == 0) return UNKNOWN_ERROR;
1045 return p->stop();
1046}
1047
1048status_t MediaPlayerService::Client::pause()
1049{
1050 LOGV("[%d] pause", mConnId);
1051 sp<MediaPlayerBase> p = getPlayer();
1052 if (p == 0) return UNKNOWN_ERROR;
1053 return p->pause();
1054}
1055
1056status_t MediaPlayerService::Client::isPlaying(bool* state)
1057{
1058 *state = false;
1059 sp<MediaPlayerBase> p = getPlayer();
1060 if (p == 0) return UNKNOWN_ERROR;
1061 *state = p->isPlaying();
1062 LOGV("[%d] isPlaying: %d", mConnId, *state);
1063 return NO_ERROR;
1064}
1065
1066status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1067{
1068 LOGV("getCurrentPosition");
1069 sp<MediaPlayerBase> p = getPlayer();
1070 if (p == 0) return UNKNOWN_ERROR;
1071 status_t ret = p->getCurrentPosition(msec);
1072 if (ret == NO_ERROR) {
1073 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1074 } else {
1075 LOGE("getCurrentPosition returned %d", ret);
1076 }
1077 return ret;
1078}
1079
1080status_t MediaPlayerService::Client::getDuration(int *msec)
1081{
1082 LOGV("getDuration");
1083 sp<MediaPlayerBase> p = getPlayer();
1084 if (p == 0) return UNKNOWN_ERROR;
1085 status_t ret = p->getDuration(msec);
1086 if (ret == NO_ERROR) {
1087 LOGV("[%d] getDuration = %d", mConnId, *msec);
1088 } else {
1089 LOGE("getDuration returned %d", ret);
1090 }
1091 return ret;
1092}
1093
1094status_t MediaPlayerService::Client::seekTo(int msec)
1095{
1096 LOGV("[%d] seekTo(%d)", mConnId, msec);
1097 sp<MediaPlayerBase> p = getPlayer();
1098 if (p == 0) return UNKNOWN_ERROR;
1099 return p->seekTo(msec);
1100}
1101
1102status_t MediaPlayerService::Client::reset()
1103{
1104 LOGV("[%d] reset", mConnId);
1105 sp<MediaPlayerBase> p = getPlayer();
1106 if (p == 0) return UNKNOWN_ERROR;
1107 return p->reset();
1108}
1109
1110status_t MediaPlayerService::Client::setAudioStreamType(int type)
1111{
1112 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1113 // TODO: for hardware output, call player instead
1114 Mutex::Autolock l(mLock);
1115 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1116 return NO_ERROR;
1117}
1118
1119status_t MediaPlayerService::Client::setLooping(int loop)
1120{
1121 LOGV("[%d] setLooping(%d)", mConnId, loop);
1122 mLoop = loop;
1123 sp<MediaPlayerBase> p = getPlayer();
1124 if (p != 0) return p->setLooping(loop);
1125 return NO_ERROR;
1126}
1127
1128status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1129{
1130 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1131 // TODO: for hardware output, call player instead
1132 Mutex::Autolock l(mLock);
1133 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1134 return NO_ERROR;
1135}
1136
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1139{
1140 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001141
1142 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001143 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001144 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001145
1146 if(client->shouldDropMetadata(metadata_type)) {
1147 return;
1148 }
1149
1150 // Update the list of metadata that have changed. getMetadata
1151 // also access mMetadataUpdated and clears it.
1152 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1155 client->mClient->notify(msg, ext1, ext2);
1156}
1157
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001158
nikobc726922009-07-20 15:07:26 -07001159bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001160{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001161 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001162
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001163 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001164 return true;
1165 }
1166
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001167 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001168 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001169 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001170 return true;
1171 }
1172}
1173
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001174
nikobc726922009-07-20 15:07:26 -07001175void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001176 Mutex::Autolock lock(mLock);
1177 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1178 mMetadataUpdated.add(metadata_type);
1179 }
1180}
1181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182#if CALLBACK_ANTAGONIZER
1183const int Antagonizer::interval = 10000; // 10 msecs
1184
1185Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1186 mExit(false), mActive(false), mClient(client), mCb(cb)
1187{
1188 createThread(callbackThread, this);
1189}
1190
1191void Antagonizer::kill()
1192{
1193 Mutex::Autolock _l(mLock);
1194 mActive = false;
1195 mExit = true;
1196 mCondition.wait(mLock);
1197}
1198
1199int Antagonizer::callbackThread(void* user)
1200{
1201 LOGD("Antagonizer started");
1202 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1203 while (!p->mExit) {
1204 if (p->mActive) {
1205 LOGV("send event");
1206 p->mCb(p->mClient, 0, 0, 0);
1207 }
1208 usleep(interval);
1209 }
1210 Mutex::Autolock _l(p->mLock);
1211 p->mCondition.signal();
1212 LOGD("Antagonizer stopped");
1213 return 0;
1214}
1215#endif
1216
1217static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1218
1219sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1220{
1221 LOGV("decode(%s)", url);
1222 sp<MemoryBase> mem;
1223 sp<MediaPlayerBase> player;
1224
1225 // Protect our precious, precious DRMd ringtones by only allowing
1226 // decoding of http, but not filesystem paths or content Uris.
1227 // If the application wants to decode those, it should open a
1228 // filedescriptor for them and use that.
1229 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1230 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1231 return mem;
1232 }
1233
1234 player_type playerType = getPlayerType(url);
1235 LOGV("player type = %d", playerType);
1236
1237 // create the right type of player
1238 sp<AudioCache> cache = new AudioCache(url);
1239 player = android::createPlayer(playerType, cache.get(), cache->notify);
1240 if (player == NULL) goto Exit;
1241 if (player->hardwareOutput()) goto Exit;
1242
1243 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1244
1245 // set data source
1246 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1247
1248 LOGV("prepare");
1249 player->prepareAsync();
1250
1251 LOGV("wait for prepare");
1252 if (cache->wait() != NO_ERROR) goto Exit;
1253
1254 LOGV("start");
1255 player->start();
1256
1257 LOGV("wait for playback complete");
1258 if (cache->wait() != NO_ERROR) goto Exit;
1259
1260 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1261 *pSampleRate = cache->sampleRate();
1262 *pNumChannels = cache->channelCount();
1263 *pFormat = cache->format();
1264 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1265
1266Exit:
1267 if (player != 0) player->reset();
1268 return mem;
1269}
1270
1271sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1272{
1273 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1274 sp<MemoryBase> mem;
1275 sp<MediaPlayerBase> player;
1276
1277 player_type playerType = getPlayerType(fd, offset, length);
1278 LOGV("player type = %d", playerType);
1279
1280 // create the right type of player
1281 sp<AudioCache> cache = new AudioCache("decode_fd");
1282 player = android::createPlayer(playerType, cache.get(), cache->notify);
1283 if (player == NULL) goto Exit;
1284 if (player->hardwareOutput()) goto Exit;
1285
1286 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1287
1288 // set data source
1289 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1290
1291 LOGV("prepare");
1292 player->prepareAsync();
1293
1294 LOGV("wait for prepare");
1295 if (cache->wait() != NO_ERROR) goto Exit;
1296
1297 LOGV("start");
1298 player->start();
1299
1300 LOGV("wait for playback complete");
1301 if (cache->wait() != NO_ERROR) goto Exit;
1302
1303 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1304 *pSampleRate = cache->sampleRate();
1305 *pNumChannels = cache->channelCount();
1306 *pFormat = cache->format();
1307 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1308
1309Exit:
1310 if (player != 0) player->reset();
1311 ::close(fd);
1312 return mem;
1313}
1314
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001315/*
1316 * Avert your eyes, ugly hack ahead.
1317 * The following is to support music visualizations.
1318 */
1319
1320static const int NUMVIZBUF = 32;
1321static const int VIZBUFFRAMES = 1024;
Marco Nelissene274db12010-01-12 09:23:54 -08001322static const int BUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1323static const int TOTALBUFTIMEMSEC = NUMVIZBUF * BUFTIMEMSEC;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001324
1325static bool gotMem = false;
Marco Nelissene274db12010-01-12 09:23:54 -08001326static sp<MemoryHeapBase> heap;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001327static sp<MemoryBase> mem[NUMVIZBUF];
Marco Nelissene274db12010-01-12 09:23:54 -08001328static uint64_t endTime;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001329static uint64_t lastReadTime;
1330static uint64_t lastWriteTime;
1331static int writeIdx = 0;
1332
1333static void allocVizBufs() {
1334 if (!gotMem) {
Marco Nelissene274db12010-01-12 09:23:54 -08001335 heap = new MemoryHeapBase(NUMVIZBUF * VIZBUFFRAMES * 2, 0, "snooper");
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001336 for (int i=0;i<NUMVIZBUF;i++) {
Marco Nelissene274db12010-01-12 09:23:54 -08001337 mem[i] = new MemoryBase(heap, VIZBUFFRAMES * 2 * i, VIZBUFFRAMES * 2);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001338 }
Marco Nelissene274db12010-01-12 09:23:54 -08001339 endTime = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001340 gotMem = true;
1341 }
1342}
1343
1344
1345/*
1346 * Get a buffer of audio data that is about to be played.
1347 * We don't synchronize this because in practice the writer
1348 * is ahead of the reader, and even if we did happen to catch
1349 * a buffer while it's being written, it's just a visualization,
1350 * so no harm done.
1351 */
1352static sp<MemoryBase> getVizBuffer() {
1353
1354 allocVizBufs();
1355
Marco Nelissene274db12010-01-12 09:23:54 -08001356 lastReadTime = uptimeMillis();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001357
1358 // if there is no recent buffer (yet), just return empty handed
1359 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
Marco Nelissene274db12010-01-12 09:23:54 -08001360 //LOGI("@@@@ no audio data to look at yet: %d + %d < %d", (int)lastWriteTime, TOTALBUFTIMEMSEC, (int)lastReadTime);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001361 return NULL;
1362 }
1363
Marco Nelissene274db12010-01-12 09:23:54 -08001364 int timedelta = endTime - lastReadTime;
1365 if (timedelta < 0) timedelta = 0;
1366 int framedelta = timedelta * 44100 / 1000;
1367 int headIdx = (writeIdx - framedelta) / VIZBUFFRAMES - 1;
1368 while (headIdx < 0) {
1369 headIdx += NUMVIZBUF;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001370 }
Marco Nelissene274db12010-01-12 09:23:54 -08001371 return mem[headIdx];
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001372}
1373
Marco Nelissene274db12010-01-12 09:23:54 -08001374// Append the data to the vizualization buffer
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001375static void makeVizBuffers(const char *data, int len, uint64_t time) {
1376
1377 allocVizBufs();
1378
1379 uint64_t startTime = time;
1380 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
Marco Nelissene274db12010-01-12 09:23:54 -08001381 int offset = writeIdx;
1382 int maxoff = heap->getSize() / 2; // in shorts
1383 short *base = (short*)heap->getBase();
1384 short *src = (short*)data;
1385 while (len > 0) {
1386
1387 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1388 // This should still be good enough for a visualization
1389 base[offset++] = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1390 src += 2;
1391 len -= frameSize;
1392 if (offset >= maxoff) {
1393 offset = 0;
1394 }
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001395 }
Marco Nelissene274db12010-01-12 09:23:54 -08001396 writeIdx = offset;
1397 endTime = time + (len / frameSize) / 44;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001398 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1399}
1400
1401sp<IMemory> MediaPlayerService::snoop()
1402{
1403 sp<MemoryBase> mem = getVizBuffer();
1404 return mem;
1405}
1406
1407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408#undef LOG_TAG
1409#define LOG_TAG "AudioSink"
1410MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001411 : mCallback(NULL),
1412 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 mTrack = 0;
1414 mStreamType = AudioSystem::MUSIC;
1415 mLeftVolume = 1.0;
1416 mRightVolume = 1.0;
1417 mLatency = 0;
1418 mMsecsPerFrame = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001419 mNumFramesWritten = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 setMinBufferCount();
1421}
1422
1423MediaPlayerService::AudioOutput::~AudioOutput()
1424{
1425 close();
1426}
1427
1428void MediaPlayerService::AudioOutput::setMinBufferCount()
1429{
1430 char value[PROPERTY_VALUE_MAX];
1431 if (property_get("ro.kernel.qemu", value, 0)) {
1432 mIsOnEmulator = true;
1433 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1434 }
1435}
1436
1437bool MediaPlayerService::AudioOutput::isOnEmulator()
1438{
1439 setMinBufferCount();
1440 return mIsOnEmulator;
1441}
1442
1443int MediaPlayerService::AudioOutput::getMinBufferCount()
1444{
1445 setMinBufferCount();
1446 return mMinBufferCount;
1447}
1448
1449ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1450{
1451 if (mTrack == 0) return NO_INIT;
1452 return mTrack->frameCount() * frameSize();
1453}
1454
1455ssize_t MediaPlayerService::AudioOutput::frameCount() const
1456{
1457 if (mTrack == 0) return NO_INIT;
1458 return mTrack->frameCount();
1459}
1460
1461ssize_t MediaPlayerService::AudioOutput::channelCount() const
1462{
1463 if (mTrack == 0) return NO_INIT;
1464 return mTrack->channelCount();
1465}
1466
1467ssize_t MediaPlayerService::AudioOutput::frameSize() const
1468{
1469 if (mTrack == 0) return NO_INIT;
1470 return mTrack->frameSize();
1471}
1472
1473uint32_t MediaPlayerService::AudioOutput::latency () const
1474{
1475 return mLatency;
1476}
1477
1478float MediaPlayerService::AudioOutput::msecsPerFrame() const
1479{
1480 return mMsecsPerFrame;
1481}
1482
Eric Laurent0986e792010-01-19 17:37:09 -08001483status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1484{
1485 if (mTrack == 0) return NO_INIT;
1486 return mTrack->getPosition(position);
1487}
1488
Andreas Hubere46b7be2009-07-14 16:56:47 -07001489status_t MediaPlayerService::AudioOutput::open(
1490 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1491 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001493 mCallback = cb;
1494 mCallbackCookie = cookie;
1495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 // Check argument "bufferCount" against the mininum buffer count
1497 if (bufferCount < mMinBufferCount) {
1498 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1499 bufferCount = mMinBufferCount;
1500
1501 }
1502 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1503 if (mTrack) close();
1504 int afSampleRate;
1505 int afFrameCount;
1506 int frameCount;
1507
1508 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1509 return NO_INIT;
1510 }
1511 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1512 return NO_INIT;
1513 }
1514
1515 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001516
1517 AudioTrack *t;
1518 if (mCallback != NULL) {
1519 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001520 mStreamType,
1521 sampleRate,
1522 format,
1523 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1524 frameCount,
1525 0 /* flags */,
1526 CallbackWrapper,
1527 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001528 } else {
1529 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001530 mStreamType,
1531 sampleRate,
1532 format,
1533 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1534 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001535 }
1536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1538 LOGE("Unable to create audio track");
1539 delete t;
1540 return NO_INIT;
1541 }
1542
1543 LOGV("setVolume");
1544 t->setVolume(mLeftVolume, mRightVolume);
1545 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001546 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 mTrack = t;
1548 return NO_ERROR;
1549}
1550
1551void MediaPlayerService::AudioOutput::start()
1552{
1553 LOGV("start");
1554 if (mTrack) {
1555 mTrack->setVolume(mLeftVolume, mRightVolume);
1556 mTrack->start();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001557 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559}
1560
Marco Nelissene274db12010-01-12 09:23:54 -08001561void MediaPlayerService::AudioOutput::snoopWrite(const void* buffer, size_t size) {
1562 // Only make visualization buffers if anyone recently requested visualization data
1563 uint64_t now = uptimeMillis();
1564 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1565 // Based on the current play counter, the number of frames written and
1566 // the current real time we can calculate the approximate real start
1567 // time of the buffer we're about to write.
1568 uint32_t pos;
1569 mTrack->getPosition(&pos);
1570
1571 // we're writing ahead by this many frames:
1572 int ahead = mNumFramesWritten - pos;
1573 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1574 // which is this many milliseconds, assuming 44100 Hz:
1575 ahead /= 44;
1576
1577 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1578 lastWriteTime = now;
1579 }
1580}
1581
1582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1584{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001585 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001588 if (mTrack) {
Marco Nelissene274db12010-01-12 09:23:54 -08001589 snoopWrite(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001590 ssize_t ret = mTrack->write(buffer, size);
1591 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1592 return ret;
1593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 return NO_INIT;
1595}
1596
1597void MediaPlayerService::AudioOutput::stop()
1598{
1599 LOGV("stop");
1600 if (mTrack) mTrack->stop();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001601 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602}
1603
1604void MediaPlayerService::AudioOutput::flush()
1605{
1606 LOGV("flush");
1607 if (mTrack) mTrack->flush();
1608}
1609
1610void MediaPlayerService::AudioOutput::pause()
1611{
1612 LOGV("pause");
1613 if (mTrack) mTrack->pause();
Marco Nelissen758613d2009-11-02 13:52:11 -08001614 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615}
1616
1617void MediaPlayerService::AudioOutput::close()
1618{
1619 LOGV("close");
1620 delete mTrack;
1621 mTrack = 0;
1622}
1623
1624void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1625{
1626 LOGV("setVolume(%f, %f)", left, right);
1627 mLeftVolume = left;
1628 mRightVolume = right;
1629 if (mTrack) {
1630 mTrack->setVolume(left, right);
1631 }
1632}
1633
Andreas Hubere46b7be2009-07-14 16:56:47 -07001634// static
1635void MediaPlayerService::AudioOutput::CallbackWrapper(
1636 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001637 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001638 if (event != AudioTrack::EVENT_MORE_DATA) {
1639 return;
1640 }
1641
1642 AudioOutput *me = (AudioOutput *)cookie;
1643 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1644
Andreas Huber6ed937e2010-02-09 16:59:18 -08001645 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001646 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001647
Andreas Huber406a18b2010-02-18 16:45:13 -08001648 buffer->size = actualSize;
1649
Andreas Huber6ed937e2010-02-09 16:59:18 -08001650 if (actualSize > 0) {
1651 me->snoopWrite(buffer->raw, actualSize);
1652 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001653}
1654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655#undef LOG_TAG
1656#define LOG_TAG "AudioCache"
1657MediaPlayerService::AudioCache::AudioCache(const char* name) :
1658 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1659 mError(NO_ERROR), mCommandComplete(false)
1660{
1661 // create ashmem heap
1662 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1663}
1664
1665uint32_t MediaPlayerService::AudioCache::latency () const
1666{
1667 return 0;
1668}
1669
1670float MediaPlayerService::AudioCache::msecsPerFrame() const
1671{
1672 return mMsecsPerFrame;
1673}
1674
Eric Laurent0986e792010-01-19 17:37:09 -08001675status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1676{
1677 if (position == 0) return BAD_VALUE;
1678 *position = mSize;
1679 return NO_ERROR;
1680}
1681
Andreas Huber6ed937e2010-02-09 16:59:18 -08001682////////////////////////////////////////////////////////////////////////////////
1683
1684struct CallbackThread : public Thread {
1685 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1686 MediaPlayerBase::AudioSink::AudioCallback cb,
1687 void *cookie);
1688
1689protected:
1690 virtual ~CallbackThread();
1691
1692 virtual bool threadLoop();
1693
1694private:
1695 wp<MediaPlayerBase::AudioSink> mSink;
1696 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1697 void *mCookie;
1698 void *mBuffer;
1699 size_t mBufferSize;
1700
1701 CallbackThread(const CallbackThread &);
1702 CallbackThread &operator=(const CallbackThread &);
1703};
1704
1705CallbackThread::CallbackThread(
1706 const wp<MediaPlayerBase::AudioSink> &sink,
1707 MediaPlayerBase::AudioSink::AudioCallback cb,
1708 void *cookie)
1709 : mSink(sink),
1710 mCallback(cb),
1711 mCookie(cookie),
1712 mBuffer(NULL),
1713 mBufferSize(0) {
1714}
1715
1716CallbackThread::~CallbackThread() {
1717 if (mBuffer) {
1718 free(mBuffer);
1719 mBuffer = NULL;
1720 }
1721}
1722
1723bool CallbackThread::threadLoop() {
1724 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1725 if (sink == NULL) {
1726 return false;
1727 }
1728
1729 if (mBuffer == NULL) {
1730 mBufferSize = sink->bufferSize();
1731 mBuffer = malloc(mBufferSize);
1732 }
1733
1734 size_t actualSize =
1735 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1736
1737 if (actualSize > 0) {
1738 sink->write(mBuffer, actualSize);
1739 }
1740
1741 return true;
1742}
1743
1744////////////////////////////////////////////////////////////////////////////////
1745
Andreas Hubere46b7be2009-07-14 16:56:47 -07001746status_t MediaPlayerService::AudioCache::open(
1747 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1748 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749{
Dave Sparks14f89402009-12-09 20:20:26 -08001750 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001751 if (mHeap->getHeapID() < 0) {
1752 return NO_INIT;
1753 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 mSampleRate = sampleRate;
1756 mChannelCount = (uint16_t)channelCount;
1757 mFormat = (uint16_t)format;
1758 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001759
1760 if (cb != NULL) {
1761 mCallbackThread = new CallbackThread(this, cb, cookie);
1762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 return NO_ERROR;
1764}
1765
Andreas Huber6ed937e2010-02-09 16:59:18 -08001766void MediaPlayerService::AudioCache::start() {
1767 if (mCallbackThread != NULL) {
1768 mCallbackThread->run("AudioCache callback");
1769 }
1770}
1771
1772void MediaPlayerService::AudioCache::stop() {
1773 if (mCallbackThread != NULL) {
1774 mCallbackThread->requestExitAndWait();
1775 }
1776}
1777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1779{
1780 LOGV("write(%p, %u)", buffer, size);
1781 if ((buffer == 0) || (size == 0)) return size;
1782
1783 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1784 if (p == NULL) return NO_INIT;
1785 p += mSize;
1786 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1787 if (mSize + size > mHeap->getSize()) {
1788 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1789 size = mHeap->getSize() - mSize;
1790 }
1791 memcpy(p, buffer, size);
1792 mSize += size;
1793 return size;
1794}
1795
1796// call with lock held
1797status_t MediaPlayerService::AudioCache::wait()
1798{
1799 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001800 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 mSignal.wait(mLock);
1802 }
1803 mCommandComplete = false;
1804
1805 if (mError == NO_ERROR) {
1806 LOGV("wait - success");
1807 } else {
1808 LOGV("wait - error");
1809 }
1810 return mError;
1811}
1812
1813void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1814{
1815 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1816 AudioCache* p = static_cast<AudioCache*>(cookie);
1817
1818 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001819 switch (msg)
1820 {
1821 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 LOGE("Error %d, %d occurred", ext1, ext2);
1823 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001824 break;
1825 case MEDIA_PREPARED:
1826 LOGV("prepared");
1827 break;
1828 case MEDIA_PLAYBACK_COMPLETE:
1829 LOGV("playback complete");
1830 break;
1831 default:
1832 LOGV("ignored");
1833 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835
1836 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001837 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 p->mCommandComplete = true;
1839 p->mSignal.signal();
1840}
1841
nikobc726922009-07-20 15:07:26 -07001842} // namespace android