blob: d7ca6356300d178b0fa0a7f3fa10523cab2aa0cf [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 if (!strncasecmp(url, "rtsp://", 7)) {
Andreas Huber7a747b82010-06-07 15:19:40 -0700775 char value[PROPERTY_VALUE_MAX];
776 if (!property_get("media.stagefright.enable-rtsp", value, NULL)
777 || (strcmp(value, "1") && strcasecmp(value, "true"))) {
778 // For now, we're going to use PV for rtsp-based playback
779 // by default until we can clear up a few more issues.
780 return PV_PLAYER;
781 }
James Dong42d66572010-04-13 21:33:26 -0700782 }
783
Andreas Huber0d596d42009-08-07 09:30:32 -0700784 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785}
786
787static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
788 notify_callback_f notifyFunc)
789{
790 sp<MediaPlayerBase> p;
791 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700792#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 case PV_PLAYER:
794 LOGV(" create PVPlayer");
795 p = new PVPlayer();
796 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700797#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 case SONIVOX_PLAYER:
799 LOGV(" create MidiFile");
800 p = new MidiFile();
801 break;
802 case VORBIS_PLAYER:
803 LOGV(" create VorbisPlayer");
804 p = new VorbisPlayer();
805 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700806#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Hubere46b7be2009-07-14 16:56:47 -0700807 case STAGEFRIGHT_PLAYER:
808 LOGV(" create StagefrightPlayer");
809 p = new StagefrightPlayer;
810 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700811#endif
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700812 case TEST_PLAYER:
813 LOGV("Create Test Player stub");
814 p = new TestPlayerStub();
815 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817 if (p != NULL) {
818 if (p->initCheck() == NO_ERROR) {
819 p->setNotifyCallback(cookie, notifyFunc);
820 } else {
821 p.clear();
822 }
823 }
824 if (p == NULL) {
825 LOGE("Failed to create player object");
826 }
827 return p;
828}
829
830sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
831{
832 // determine if we have the right player type
833 sp<MediaPlayerBase> p = mPlayer;
834 if ((p != NULL) && (p->playerType() != playerType)) {
835 LOGV("delete player");
836 p.clear();
837 }
838 if (p == NULL) {
839 p = android::createPlayer(playerType, this, notify);
840 }
841 return p;
842}
843
Andreas Huber25643002010-01-28 11:19:57 -0800844status_t MediaPlayerService::Client::setDataSource(
845 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846{
847 LOGV("setDataSource(%s)", url);
848 if (url == NULL)
849 return UNKNOWN_ERROR;
850
851 if (strncmp(url, "content://", 10) == 0) {
852 // get a filedescriptor for the content Uri and
853 // pass it to the setDataSource(fd) method
854
855 String16 url16(url);
856 int fd = android::openContentProviderFile(url16);
857 if (fd < 0)
858 {
859 LOGE("Couldn't open fd for %s", url);
860 return UNKNOWN_ERROR;
861 }
862 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
863 close(fd);
864 return mStatus;
865 } else {
866 player_type playerType = getPlayerType(url);
867 LOGV("player type = %d", playerType);
868
869 // create the right type of player
870 sp<MediaPlayerBase> p = createPlayer(playerType);
871 if (p == NULL) return NO_INIT;
872
873 if (!p->hardwareOutput()) {
874 mAudioOutput = new AudioOutput();
875 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
876 }
877
878 // now set data source
879 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800880 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700881 if (mStatus == NO_ERROR) {
882 mPlayer = p;
883 } else {
884 LOGE(" error: %d", mStatus);
885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 return mStatus;
887 }
888}
889
890status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
891{
892 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
893 struct stat sb;
894 int ret = fstat(fd, &sb);
895 if (ret != 0) {
896 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
897 return UNKNOWN_ERROR;
898 }
899
900 LOGV("st_dev = %llu", sb.st_dev);
901 LOGV("st_mode = %u", sb.st_mode);
902 LOGV("st_uid = %lu", sb.st_uid);
903 LOGV("st_gid = %lu", sb.st_gid);
904 LOGV("st_size = %llu", sb.st_size);
905
906 if (offset >= sb.st_size) {
907 LOGE("offset error");
908 ::close(fd);
909 return UNKNOWN_ERROR;
910 }
911 if (offset + length > sb.st_size) {
912 length = sb.st_size - offset;
913 LOGV("calculated length = %lld", length);
914 }
915
916 player_type playerType = getPlayerType(fd, offset, length);
917 LOGV("player type = %d", playerType);
918
919 // create the right type of player
920 sp<MediaPlayerBase> p = createPlayer(playerType);
921 if (p == NULL) return NO_INIT;
922
923 if (!p->hardwareOutput()) {
924 mAudioOutput = new AudioOutput();
925 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
926 }
927
928 // now set data source
929 mStatus = p->setDataSource(fd, offset, length);
930 if (mStatus == NO_ERROR) mPlayer = p;
931 return mStatus;
932}
933
934status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
935{
936 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
937 sp<MediaPlayerBase> p = getPlayer();
938 if (p == 0) return UNKNOWN_ERROR;
939 return p->setVideoSurface(surface);
940}
941
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700942status_t MediaPlayerService::Client::invoke(const Parcel& request,
943 Parcel *reply)
944{
945 sp<MediaPlayerBase> p = getPlayer();
946 if (p == NULL) return UNKNOWN_ERROR;
947 return p->invoke(request, reply);
948}
949
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700950// This call doesn't need to access the native player.
951status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
952{
953 status_t status;
nikobc726922009-07-20 15:07:26 -0700954 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700955
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700956 if (unmarshallFilter(filter, &allow, &status) &&
957 unmarshallFilter(filter, &drop, &status)) {
958 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700959
960 mMetadataAllow = allow;
961 mMetadataDrop = drop;
962 }
963 return status;
964}
965
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700966status_t MediaPlayerService::Client::getMetadata(
967 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700968{
nikobc726922009-07-20 15:07:26 -0700969 sp<MediaPlayerBase> player = getPlayer();
970 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700971
niko89948372009-07-16 16:39:53 -0700972 status_t status;
973 // Placeholder for the return code, updated by the caller.
974 reply->writeInt32(-1);
975
nikobc726922009-07-20 15:07:26 -0700976 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700977
978 // We don't block notifications while we fetch the data. We clear
979 // mMetadataUpdated first so we don't lose notifications happening
980 // during the rest of this call.
981 {
982 Mutex::Autolock lock(mLock);
983 if (update_only) {
niko89948372009-07-16 16:39:53 -0700984 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700985 }
986 mMetadataUpdated.clear();
987 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700988
nikobc726922009-07-20 15:07:26 -0700989 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700990
nikobc726922009-07-20 15:07:26 -0700991 metadata.appendHeader();
992 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700993
994 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700995 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700996 LOGE("getMetadata failed %d", status);
997 return status;
998 }
999
1000 // FIXME: Implement filtering on the result. Not critical since
1001 // filtering takes place on the update notifications already. This
1002 // would be when all the metadata are fetch and a filter is set.
1003
niko89948372009-07-16 16:39:53 -07001004 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -07001005 metadata.updateLength();
niko89948372009-07-16 16:39:53 -07001006 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -07001007}
1008
Andreas Huberfbb38852010-02-12 12:35:58 -08001009status_t MediaPlayerService::Client::suspend() {
1010 sp<MediaPlayerBase> p = getPlayer();
1011 if (p == 0) return UNKNOWN_ERROR;
1012
1013 return p->suspend();
1014}
1015
1016status_t MediaPlayerService::Client::resume() {
1017 sp<MediaPlayerBase> p = getPlayer();
1018 if (p == 0) return UNKNOWN_ERROR;
1019
1020 return p->resume();
1021}
1022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023status_t MediaPlayerService::Client::prepareAsync()
1024{
1025 LOGV("[%d] prepareAsync", mConnId);
1026 sp<MediaPlayerBase> p = getPlayer();
1027 if (p == 0) return UNKNOWN_ERROR;
1028 status_t ret = p->prepareAsync();
1029#if CALLBACK_ANTAGONIZER
1030 LOGD("start Antagonizer");
1031 if (ret == NO_ERROR) mAntagonizer->start();
1032#endif
1033 return ret;
1034}
1035
1036status_t MediaPlayerService::Client::start()
1037{
1038 LOGV("[%d] start", mConnId);
1039 sp<MediaPlayerBase> p = getPlayer();
1040 if (p == 0) return UNKNOWN_ERROR;
1041 p->setLooping(mLoop);
1042 return p->start();
1043}
1044
1045status_t MediaPlayerService::Client::stop()
1046{
1047 LOGV("[%d] stop", mConnId);
1048 sp<MediaPlayerBase> p = getPlayer();
1049 if (p == 0) return UNKNOWN_ERROR;
1050 return p->stop();
1051}
1052
1053status_t MediaPlayerService::Client::pause()
1054{
1055 LOGV("[%d] pause", mConnId);
1056 sp<MediaPlayerBase> p = getPlayer();
1057 if (p == 0) return UNKNOWN_ERROR;
1058 return p->pause();
1059}
1060
1061status_t MediaPlayerService::Client::isPlaying(bool* state)
1062{
1063 *state = false;
1064 sp<MediaPlayerBase> p = getPlayer();
1065 if (p == 0) return UNKNOWN_ERROR;
1066 *state = p->isPlaying();
1067 LOGV("[%d] isPlaying: %d", mConnId, *state);
1068 return NO_ERROR;
1069}
1070
1071status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1072{
1073 LOGV("getCurrentPosition");
1074 sp<MediaPlayerBase> p = getPlayer();
1075 if (p == 0) return UNKNOWN_ERROR;
1076 status_t ret = p->getCurrentPosition(msec);
1077 if (ret == NO_ERROR) {
1078 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1079 } else {
1080 LOGE("getCurrentPosition returned %d", ret);
1081 }
1082 return ret;
1083}
1084
1085status_t MediaPlayerService::Client::getDuration(int *msec)
1086{
1087 LOGV("getDuration");
1088 sp<MediaPlayerBase> p = getPlayer();
1089 if (p == 0) return UNKNOWN_ERROR;
1090 status_t ret = p->getDuration(msec);
1091 if (ret == NO_ERROR) {
1092 LOGV("[%d] getDuration = %d", mConnId, *msec);
1093 } else {
1094 LOGE("getDuration returned %d", ret);
1095 }
1096 return ret;
1097}
1098
1099status_t MediaPlayerService::Client::seekTo(int msec)
1100{
1101 LOGV("[%d] seekTo(%d)", mConnId, msec);
1102 sp<MediaPlayerBase> p = getPlayer();
1103 if (p == 0) return UNKNOWN_ERROR;
1104 return p->seekTo(msec);
1105}
1106
1107status_t MediaPlayerService::Client::reset()
1108{
1109 LOGV("[%d] reset", mConnId);
1110 sp<MediaPlayerBase> p = getPlayer();
1111 if (p == 0) return UNKNOWN_ERROR;
1112 return p->reset();
1113}
1114
1115status_t MediaPlayerService::Client::setAudioStreamType(int type)
1116{
1117 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1118 // TODO: for hardware output, call player instead
1119 Mutex::Autolock l(mLock);
1120 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1121 return NO_ERROR;
1122}
1123
1124status_t MediaPlayerService::Client::setLooping(int loop)
1125{
1126 LOGV("[%d] setLooping(%d)", mConnId, loop);
1127 mLoop = loop;
1128 sp<MediaPlayerBase> p = getPlayer();
1129 if (p != 0) return p->setLooping(loop);
1130 return NO_ERROR;
1131}
1132
1133status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1134{
1135 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1136 // TODO: for hardware output, call player instead
1137 Mutex::Autolock l(mLock);
1138 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1139 return NO_ERROR;
1140}
1141
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1144{
1145 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001146
1147 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001148 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001149 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001150
1151 if(client->shouldDropMetadata(metadata_type)) {
1152 return;
1153 }
1154
1155 // Update the list of metadata that have changed. getMetadata
1156 // also access mMetadataUpdated and clears it.
1157 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1160 client->mClient->notify(msg, ext1, ext2);
1161}
1162
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001163
nikobc726922009-07-20 15:07:26 -07001164bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001165{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001166 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001167
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001168 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001169 return true;
1170 }
1171
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001172 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001173 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001174 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001175 return true;
1176 }
1177}
1178
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001179
nikobc726922009-07-20 15:07:26 -07001180void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001181 Mutex::Autolock lock(mLock);
1182 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1183 mMetadataUpdated.add(metadata_type);
1184 }
1185}
1186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187#if CALLBACK_ANTAGONIZER
1188const int Antagonizer::interval = 10000; // 10 msecs
1189
1190Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1191 mExit(false), mActive(false), mClient(client), mCb(cb)
1192{
1193 createThread(callbackThread, this);
1194}
1195
1196void Antagonizer::kill()
1197{
1198 Mutex::Autolock _l(mLock);
1199 mActive = false;
1200 mExit = true;
1201 mCondition.wait(mLock);
1202}
1203
1204int Antagonizer::callbackThread(void* user)
1205{
1206 LOGD("Antagonizer started");
1207 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1208 while (!p->mExit) {
1209 if (p->mActive) {
1210 LOGV("send event");
1211 p->mCb(p->mClient, 0, 0, 0);
1212 }
1213 usleep(interval);
1214 }
1215 Mutex::Autolock _l(p->mLock);
1216 p->mCondition.signal();
1217 LOGD("Antagonizer stopped");
1218 return 0;
1219}
1220#endif
1221
1222static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1223
1224sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1225{
1226 LOGV("decode(%s)", url);
1227 sp<MemoryBase> mem;
1228 sp<MediaPlayerBase> player;
1229
1230 // Protect our precious, precious DRMd ringtones by only allowing
1231 // decoding of http, but not filesystem paths or content Uris.
1232 // If the application wants to decode those, it should open a
1233 // filedescriptor for them and use that.
1234 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1235 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1236 return mem;
1237 }
1238
1239 player_type playerType = getPlayerType(url);
1240 LOGV("player type = %d", playerType);
1241
1242 // create the right type of player
1243 sp<AudioCache> cache = new AudioCache(url);
1244 player = android::createPlayer(playerType, cache.get(), cache->notify);
1245 if (player == NULL) goto Exit;
1246 if (player->hardwareOutput()) goto Exit;
1247
1248 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1249
1250 // set data source
1251 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1252
1253 LOGV("prepare");
1254 player->prepareAsync();
1255
1256 LOGV("wait for prepare");
1257 if (cache->wait() != NO_ERROR) goto Exit;
1258
1259 LOGV("start");
1260 player->start();
1261
1262 LOGV("wait for playback complete");
1263 if (cache->wait() != NO_ERROR) goto Exit;
1264
1265 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1266 *pSampleRate = cache->sampleRate();
1267 *pNumChannels = cache->channelCount();
1268 *pFormat = cache->format();
1269 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1270
1271Exit:
1272 if (player != 0) player->reset();
1273 return mem;
1274}
1275
1276sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1277{
1278 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1279 sp<MemoryBase> mem;
1280 sp<MediaPlayerBase> player;
1281
1282 player_type playerType = getPlayerType(fd, offset, length);
1283 LOGV("player type = %d", playerType);
1284
1285 // create the right type of player
1286 sp<AudioCache> cache = new AudioCache("decode_fd");
1287 player = android::createPlayer(playerType, cache.get(), cache->notify);
1288 if (player == NULL) goto Exit;
1289 if (player->hardwareOutput()) goto Exit;
1290
1291 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1292
1293 // set data source
1294 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1295
1296 LOGV("prepare");
1297 player->prepareAsync();
1298
1299 LOGV("wait for prepare");
1300 if (cache->wait() != NO_ERROR) goto Exit;
1301
1302 LOGV("start");
1303 player->start();
1304
1305 LOGV("wait for playback complete");
1306 if (cache->wait() != NO_ERROR) goto Exit;
1307
1308 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1309 *pSampleRate = cache->sampleRate();
1310 *pNumChannels = cache->channelCount();
1311 *pFormat = cache->format();
1312 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1313
1314Exit:
1315 if (player != 0) player->reset();
1316 ::close(fd);
1317 return mem;
1318}
1319
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001320/*
1321 * Avert your eyes, ugly hack ahead.
1322 * The following is to support music visualizations.
1323 */
1324
1325static const int NUMVIZBUF = 32;
1326static const int VIZBUFFRAMES = 1024;
Marco Nelissene274db12010-01-12 09:23:54 -08001327static const int BUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1328static const int TOTALBUFTIMEMSEC = NUMVIZBUF * BUFTIMEMSEC;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001329
1330static bool gotMem = false;
Marco Nelissene274db12010-01-12 09:23:54 -08001331static sp<MemoryHeapBase> heap;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001332static sp<MemoryBase> mem[NUMVIZBUF];
Marco Nelissene274db12010-01-12 09:23:54 -08001333static uint64_t endTime;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001334static uint64_t lastReadTime;
1335static uint64_t lastWriteTime;
1336static int writeIdx = 0;
1337
1338static void allocVizBufs() {
1339 if (!gotMem) {
Marco Nelissene274db12010-01-12 09:23:54 -08001340 heap = new MemoryHeapBase(NUMVIZBUF * VIZBUFFRAMES * 2, 0, "snooper");
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001341 for (int i=0;i<NUMVIZBUF;i++) {
Marco Nelissene274db12010-01-12 09:23:54 -08001342 mem[i] = new MemoryBase(heap, VIZBUFFRAMES * 2 * i, VIZBUFFRAMES * 2);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001343 }
Marco Nelissene274db12010-01-12 09:23:54 -08001344 endTime = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001345 gotMem = true;
1346 }
1347}
1348
1349
1350/*
1351 * Get a buffer of audio data that is about to be played.
1352 * We don't synchronize this because in practice the writer
1353 * is ahead of the reader, and even if we did happen to catch
1354 * a buffer while it's being written, it's just a visualization,
1355 * so no harm done.
1356 */
1357static sp<MemoryBase> getVizBuffer() {
1358
1359 allocVizBufs();
1360
Marco Nelissene274db12010-01-12 09:23:54 -08001361 lastReadTime = uptimeMillis();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001362
1363 // if there is no recent buffer (yet), just return empty handed
1364 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
Marco Nelissene274db12010-01-12 09:23:54 -08001365 //LOGI("@@@@ no audio data to look at yet: %d + %d < %d", (int)lastWriteTime, TOTALBUFTIMEMSEC, (int)lastReadTime);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001366 return NULL;
1367 }
1368
Marco Nelissene274db12010-01-12 09:23:54 -08001369 int timedelta = endTime - lastReadTime;
1370 if (timedelta < 0) timedelta = 0;
1371 int framedelta = timedelta * 44100 / 1000;
1372 int headIdx = (writeIdx - framedelta) / VIZBUFFRAMES - 1;
1373 while (headIdx < 0) {
1374 headIdx += NUMVIZBUF;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001375 }
Marco Nelissene274db12010-01-12 09:23:54 -08001376 return mem[headIdx];
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001377}
1378
Marco Nelissene274db12010-01-12 09:23:54 -08001379// Append the data to the vizualization buffer
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001380static void makeVizBuffers(const char *data, int len, uint64_t time) {
1381
1382 allocVizBufs();
1383
1384 uint64_t startTime = time;
1385 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
Marco Nelissene274db12010-01-12 09:23:54 -08001386 int offset = writeIdx;
1387 int maxoff = heap->getSize() / 2; // in shorts
1388 short *base = (short*)heap->getBase();
1389 short *src = (short*)data;
1390 while (len > 0) {
1391
1392 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1393 // This should still be good enough for a visualization
1394 base[offset++] = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1395 src += 2;
1396 len -= frameSize;
1397 if (offset >= maxoff) {
1398 offset = 0;
1399 }
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001400 }
Marco Nelissene274db12010-01-12 09:23:54 -08001401 writeIdx = offset;
1402 endTime = time + (len / frameSize) / 44;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001403 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1404}
1405
1406sp<IMemory> MediaPlayerService::snoop()
1407{
1408 sp<MemoryBase> mem = getVizBuffer();
1409 return mem;
1410}
1411
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413#undef LOG_TAG
1414#define LOG_TAG "AudioSink"
1415MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001416 : mCallback(NULL),
1417 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 mTrack = 0;
1419 mStreamType = AudioSystem::MUSIC;
1420 mLeftVolume = 1.0;
1421 mRightVolume = 1.0;
1422 mLatency = 0;
1423 mMsecsPerFrame = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001424 mNumFramesWritten = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 setMinBufferCount();
1426}
1427
1428MediaPlayerService::AudioOutput::~AudioOutput()
1429{
1430 close();
1431}
1432
1433void MediaPlayerService::AudioOutput::setMinBufferCount()
1434{
1435 char value[PROPERTY_VALUE_MAX];
1436 if (property_get("ro.kernel.qemu", value, 0)) {
1437 mIsOnEmulator = true;
1438 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1439 }
1440}
1441
1442bool MediaPlayerService::AudioOutput::isOnEmulator()
1443{
1444 setMinBufferCount();
1445 return mIsOnEmulator;
1446}
1447
1448int MediaPlayerService::AudioOutput::getMinBufferCount()
1449{
1450 setMinBufferCount();
1451 return mMinBufferCount;
1452}
1453
1454ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1455{
1456 if (mTrack == 0) return NO_INIT;
1457 return mTrack->frameCount() * frameSize();
1458}
1459
1460ssize_t MediaPlayerService::AudioOutput::frameCount() const
1461{
1462 if (mTrack == 0) return NO_INIT;
1463 return mTrack->frameCount();
1464}
1465
1466ssize_t MediaPlayerService::AudioOutput::channelCount() const
1467{
1468 if (mTrack == 0) return NO_INIT;
1469 return mTrack->channelCount();
1470}
1471
1472ssize_t MediaPlayerService::AudioOutput::frameSize() const
1473{
1474 if (mTrack == 0) return NO_INIT;
1475 return mTrack->frameSize();
1476}
1477
1478uint32_t MediaPlayerService::AudioOutput::latency () const
1479{
1480 return mLatency;
1481}
1482
1483float MediaPlayerService::AudioOutput::msecsPerFrame() const
1484{
1485 return mMsecsPerFrame;
1486}
1487
Eric Laurent0986e792010-01-19 17:37:09 -08001488status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1489{
1490 if (mTrack == 0) return NO_INIT;
1491 return mTrack->getPosition(position);
1492}
1493
Andreas Hubere46b7be2009-07-14 16:56:47 -07001494status_t MediaPlayerService::AudioOutput::open(
1495 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1496 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001498 mCallback = cb;
1499 mCallbackCookie = cookie;
1500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 // Check argument "bufferCount" against the mininum buffer count
1502 if (bufferCount < mMinBufferCount) {
1503 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1504 bufferCount = mMinBufferCount;
1505
1506 }
1507 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1508 if (mTrack) close();
1509 int afSampleRate;
1510 int afFrameCount;
1511 int frameCount;
1512
1513 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1514 return NO_INIT;
1515 }
1516 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1517 return NO_INIT;
1518 }
1519
1520 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001521
1522 AudioTrack *t;
1523 if (mCallback != NULL) {
1524 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001525 mStreamType,
1526 sampleRate,
1527 format,
1528 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1529 frameCount,
1530 0 /* flags */,
1531 CallbackWrapper,
1532 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001533 } else {
1534 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001535 mStreamType,
1536 sampleRate,
1537 format,
1538 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1539 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001540 }
1541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1543 LOGE("Unable to create audio track");
1544 delete t;
1545 return NO_INIT;
1546 }
1547
1548 LOGV("setVolume");
1549 t->setVolume(mLeftVolume, mRightVolume);
1550 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001551 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 mTrack = t;
1553 return NO_ERROR;
1554}
1555
1556void MediaPlayerService::AudioOutput::start()
1557{
1558 LOGV("start");
1559 if (mTrack) {
1560 mTrack->setVolume(mLeftVolume, mRightVolume);
1561 mTrack->start();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001562 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
1564}
1565
Marco Nelissene274db12010-01-12 09:23:54 -08001566void MediaPlayerService::AudioOutput::snoopWrite(const void* buffer, size_t size) {
1567 // Only make visualization buffers if anyone recently requested visualization data
1568 uint64_t now = uptimeMillis();
1569 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1570 // Based on the current play counter, the number of frames written and
1571 // the current real time we can calculate the approximate real start
1572 // time of the buffer we're about to write.
1573 uint32_t pos;
1574 mTrack->getPosition(&pos);
1575
1576 // we're writing ahead by this many frames:
1577 int ahead = mNumFramesWritten - pos;
1578 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1579 // which is this many milliseconds, assuming 44100 Hz:
1580 ahead /= 44;
1581
1582 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1583 lastWriteTime = now;
1584 }
1585}
1586
1587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1589{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001590 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001593 if (mTrack) {
Marco Nelissene274db12010-01-12 09:23:54 -08001594 snoopWrite(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001595 ssize_t ret = mTrack->write(buffer, size);
1596 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1597 return ret;
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 return NO_INIT;
1600}
1601
1602void MediaPlayerService::AudioOutput::stop()
1603{
1604 LOGV("stop");
1605 if (mTrack) mTrack->stop();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001606 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607}
1608
1609void MediaPlayerService::AudioOutput::flush()
1610{
1611 LOGV("flush");
1612 if (mTrack) mTrack->flush();
1613}
1614
1615void MediaPlayerService::AudioOutput::pause()
1616{
1617 LOGV("pause");
1618 if (mTrack) mTrack->pause();
Marco Nelissen758613d2009-11-02 13:52:11 -08001619 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620}
1621
1622void MediaPlayerService::AudioOutput::close()
1623{
1624 LOGV("close");
1625 delete mTrack;
1626 mTrack = 0;
1627}
1628
1629void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1630{
1631 LOGV("setVolume(%f, %f)", left, right);
1632 mLeftVolume = left;
1633 mRightVolume = right;
1634 if (mTrack) {
1635 mTrack->setVolume(left, right);
1636 }
1637}
1638
Andreas Hubere46b7be2009-07-14 16:56:47 -07001639// static
1640void MediaPlayerService::AudioOutput::CallbackWrapper(
1641 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001642 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001643 if (event != AudioTrack::EVENT_MORE_DATA) {
1644 return;
1645 }
1646
1647 AudioOutput *me = (AudioOutput *)cookie;
1648 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1649
Andreas Huber6ed937e2010-02-09 16:59:18 -08001650 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001651 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001652
Andreas Huber406a18b2010-02-18 16:45:13 -08001653 buffer->size = actualSize;
1654
Andreas Huber6ed937e2010-02-09 16:59:18 -08001655 if (actualSize > 0) {
1656 me->snoopWrite(buffer->raw, actualSize);
1657 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001658}
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660#undef LOG_TAG
1661#define LOG_TAG "AudioCache"
1662MediaPlayerService::AudioCache::AudioCache(const char* name) :
1663 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1664 mError(NO_ERROR), mCommandComplete(false)
1665{
1666 // create ashmem heap
1667 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1668}
1669
1670uint32_t MediaPlayerService::AudioCache::latency () const
1671{
1672 return 0;
1673}
1674
1675float MediaPlayerService::AudioCache::msecsPerFrame() const
1676{
1677 return mMsecsPerFrame;
1678}
1679
Eric Laurent0986e792010-01-19 17:37:09 -08001680status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1681{
1682 if (position == 0) return BAD_VALUE;
1683 *position = mSize;
1684 return NO_ERROR;
1685}
1686
Andreas Huber6ed937e2010-02-09 16:59:18 -08001687////////////////////////////////////////////////////////////////////////////////
1688
1689struct CallbackThread : public Thread {
1690 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1691 MediaPlayerBase::AudioSink::AudioCallback cb,
1692 void *cookie);
1693
1694protected:
1695 virtual ~CallbackThread();
1696
1697 virtual bool threadLoop();
1698
1699private:
1700 wp<MediaPlayerBase::AudioSink> mSink;
1701 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1702 void *mCookie;
1703 void *mBuffer;
1704 size_t mBufferSize;
1705
1706 CallbackThread(const CallbackThread &);
1707 CallbackThread &operator=(const CallbackThread &);
1708};
1709
1710CallbackThread::CallbackThread(
1711 const wp<MediaPlayerBase::AudioSink> &sink,
1712 MediaPlayerBase::AudioSink::AudioCallback cb,
1713 void *cookie)
1714 : mSink(sink),
1715 mCallback(cb),
1716 mCookie(cookie),
1717 mBuffer(NULL),
1718 mBufferSize(0) {
1719}
1720
1721CallbackThread::~CallbackThread() {
1722 if (mBuffer) {
1723 free(mBuffer);
1724 mBuffer = NULL;
1725 }
1726}
1727
1728bool CallbackThread::threadLoop() {
1729 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1730 if (sink == NULL) {
1731 return false;
1732 }
1733
1734 if (mBuffer == NULL) {
1735 mBufferSize = sink->bufferSize();
1736 mBuffer = malloc(mBufferSize);
1737 }
1738
1739 size_t actualSize =
1740 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1741
1742 if (actualSize > 0) {
1743 sink->write(mBuffer, actualSize);
1744 }
1745
1746 return true;
1747}
1748
1749////////////////////////////////////////////////////////////////////////////////
1750
Andreas Hubere46b7be2009-07-14 16:56:47 -07001751status_t MediaPlayerService::AudioCache::open(
1752 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1753 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754{
Dave Sparks14f89402009-12-09 20:20:26 -08001755 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001756 if (mHeap->getHeapID() < 0) {
1757 return NO_INIT;
1758 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 mSampleRate = sampleRate;
1761 mChannelCount = (uint16_t)channelCount;
1762 mFormat = (uint16_t)format;
1763 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001764
1765 if (cb != NULL) {
1766 mCallbackThread = new CallbackThread(this, cb, cookie);
1767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 return NO_ERROR;
1769}
1770
Andreas Huber6ed937e2010-02-09 16:59:18 -08001771void MediaPlayerService::AudioCache::start() {
1772 if (mCallbackThread != NULL) {
1773 mCallbackThread->run("AudioCache callback");
1774 }
1775}
1776
1777void MediaPlayerService::AudioCache::stop() {
1778 if (mCallbackThread != NULL) {
1779 mCallbackThread->requestExitAndWait();
1780 }
1781}
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1784{
1785 LOGV("write(%p, %u)", buffer, size);
1786 if ((buffer == 0) || (size == 0)) return size;
1787
1788 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1789 if (p == NULL) return NO_INIT;
1790 p += mSize;
1791 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1792 if (mSize + size > mHeap->getSize()) {
1793 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1794 size = mHeap->getSize() - mSize;
1795 }
1796 memcpy(p, buffer, size);
1797 mSize += size;
1798 return size;
1799}
1800
1801// call with lock held
1802status_t MediaPlayerService::AudioCache::wait()
1803{
1804 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001805 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 mSignal.wait(mLock);
1807 }
1808 mCommandComplete = false;
1809
1810 if (mError == NO_ERROR) {
1811 LOGV("wait - success");
1812 } else {
1813 LOGV("wait - error");
1814 }
1815 return mError;
1816}
1817
1818void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1819{
1820 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1821 AudioCache* p = static_cast<AudioCache*>(cookie);
1822
1823 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001824 switch (msg)
1825 {
1826 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 LOGE("Error %d, %d occurred", ext1, ext2);
1828 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001829 break;
1830 case MEDIA_PREPARED:
1831 LOGV("prepared");
1832 break;
1833 case MEDIA_PLAYBACK_COMPLETE:
1834 LOGV("playback complete");
1835 break;
1836 default:
1837 LOGV("ignored");
1838 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840
1841 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001842 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 p->mCommandComplete = true;
1844 p->mSignal.signal();
1845}
1846
nikobc726922009-07-20 15:07:26 -07001847} // namespace android