blob: 3e1f4a57ba66791045f1ffebbe2b0806b311319e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <dirent.h>
27#include <unistd.h>
28
29#include <string.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031#include <cutils/atomic.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070032#include <cutils/properties.h> // for property_get
Mathias Agopiana650aaa2009-06-03 17:32:49 -070033
34#include <utils/misc.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
36#include <android_runtime/ActivityManager.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070037
Mathias Agopian07952722009-05-19 19:08:10 -070038#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
40#include <binder/MemoryHeapBase.h>
41#include <binder/MemoryBase.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissenc39d2e32009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070045#include <utils/Vector.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046#include <cutils/properties.h>
47
48#include <media/MediaPlayerInterface.h>
49#include <media/mediarecorder.h>
50#include <media/MediaMetadataRetrieverInterface.h>
nikobc726922009-07-20 15:07:26 -070051#include <media/Metadata.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052#include <media/AudioTrack.h>
53
54#include "MediaRecorderClient.h"
55#include "MediaPlayerService.h"
56#include "MetadataRetrieverClient.h"
57
58#include "MidiFile.h"
59#include "VorbisPlayer.h"
60#include <media/PVPlayer.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070061#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070062#include "StagefrightPlayer.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070063
Andreas Hubere46b7be2009-07-14 16:56:47 -070064#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066/* desktop Linux needs a little help with gettid() */
67#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
68#define __KERNEL__
69# include <linux/unistd.h>
70#ifdef _syscall0
71_syscall0(pid_t,gettid)
72#else
73pid_t gettid() { return syscall(__NR_gettid);}
74#endif
75#undef __KERNEL__
76#endif
77
Nicolas Cataniab2c69392009-07-08 08:57:42 -070078namespace {
nikobc726922009-07-20 15:07:26 -070079using android::media::Metadata;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070080using android::status_t;
81using android::OK;
82using android::BAD_VALUE;
83using android::NOT_ENOUGH_DATA;
84using android::Parcel;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070085
86// Max number of entries in the filter.
87const int kMaxFilterSize = 64; // I pulled that out of thin air.
88
nikobc726922009-07-20 15:07:26 -070089// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070090
Nicolas Cataniab2c69392009-07-08 08:57:42 -070091
92// Unmarshall a filter from a Parcel.
93// Filter format in a parcel:
94//
95// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
96// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
97// | number of entries (n) |
98// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99// | metadata type 1 |
100// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101// | metadata type 2 |
102// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103// ....
104// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105// | metadata type n |
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107//
108// @param p Parcel that should start with a filter.
109// @param[out] filter On exit contains the list of metadata type to be
110// filtered.
111// @param[out] status On exit contains the status code to be returned.
112// @return true if the parcel starts with a valid filter.
113bool unmarshallFilter(const Parcel& p,
nikobc726922009-07-20 15:07:26 -0700114 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700115 status_t *status)
116{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700117 int32_t val;
118 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700119 {
120 LOGE("Failed to read filter's length");
121 *status = NOT_ENOUGH_DATA;
122 return false;
123 }
124
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700125 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700126 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700127 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700128 *status = BAD_VALUE;
129 return false;
130 }
131
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700132 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700133
134 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700135 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700136
nikobc726922009-07-20 15:07:26 -0700137 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700138
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700139
140 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700141 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700142 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700143 *status = NOT_ENOUGH_DATA;
144 return false;
145 }
146
nikobc726922009-07-20 15:07:26 -0700147 const Metadata::Type *data =
148 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700149
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700150 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700151 {
152 LOGE("Filter had no data");
153 *status = BAD_VALUE;
154 return false;
155 }
156
157 // TODO: The stl impl of vector would be more efficient here
158 // because it degenerates into a memcpy on pod types. Try to
159 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700160 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700161 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700162 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700163 ++data;
164 }
165 *status = OK;
166 return true;
167}
168
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700169// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700170// @param val To be searched.
171// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700172bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700173{
174 // Deal with empty and ANY right away
175 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700176 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700177
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700178 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700179}
180
181} // anonymous namespace
182
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184namespace android {
185
186// TODO: Temp hack until we can register players
187typedef struct {
188 const char *extension;
189 const player_type playertype;
190} extmap;
191extmap FILE_EXTS [] = {
192 {".mid", SONIVOX_PLAYER},
193 {".midi", SONIVOX_PLAYER},
194 {".smf", SONIVOX_PLAYER},
195 {".xmf", SONIVOX_PLAYER},
196 {".imy", SONIVOX_PLAYER},
197 {".rtttl", SONIVOX_PLAYER},
198 {".rtx", SONIVOX_PLAYER},
199 {".ota", SONIVOX_PLAYER},
200 {".ogg", VORBIS_PLAYER},
201 {".oga", VORBIS_PLAYER},
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800202#ifndef NO_OPENCORE
203 {".wma", PV_PLAYER},
204 {".wmv", PV_PLAYER},
205 {".asf", PV_PLAYER},
206#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207};
208
209// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
211/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
212
213void MediaPlayerService::instantiate() {
214 defaultServiceManager()->addService(
215 String16("media.player"), new MediaPlayerService());
216}
217
218MediaPlayerService::MediaPlayerService()
219{
220 LOGV("MediaPlayerService created");
221 mNextConnId = 1;
222}
223
224MediaPlayerService::~MediaPlayerService()
225{
226 LOGV("MediaPlayerService destroyed");
227}
228
229sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
230{
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700231#ifndef NO_OPENCORE
Gloria Wang608a2632009-10-29 15:46:37 -0700232 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
233 wp<MediaRecorderClient> w = recorder;
234 Mutex::Autolock lock(mLock);
235 mMediaRecorderClients.add(w);
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700236#else
237 sp<MediaRecorderClient> recorder = NULL;
238#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 LOGV("Create new media recorder client from pid %d", pid);
240 return recorder;
241}
242
Gloria Wang608a2632009-10-29 15:46:37 -0700243void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
244{
245 Mutex::Autolock lock(mLock);
246 mMediaRecorderClients.remove(client);
247 LOGV("Delete media recorder client");
248}
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
251{
252 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
253 LOGV("Create new media retriever from pid %d", pid);
254 return retriever;
255}
256
Andreas Huber25643002010-01-28 11:19:57 -0800257sp<IMediaPlayer> MediaPlayerService::create(
258 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
259 const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260{
261 int32_t connId = android_atomic_inc(&mNextConnId);
262 sp<Client> c = new Client(this, pid, connId, client);
263 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
Andreas Huber25643002010-01-28 11:19:57 -0800264 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 {
266 c.clear();
267 return c;
268 }
269 wp<Client> w = c;
270 Mutex::Autolock lock(mLock);
271 mClients.add(w);
272 return c;
273}
274
275sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
276 int fd, int64_t offset, int64_t length)
277{
278 int32_t connId = android_atomic_inc(&mNextConnId);
279 sp<Client> c = new Client(this, pid, connId, client);
280 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
281 connId, pid, fd, offset, length);
282 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
283 c.clear();
284 } else {
285 wp<Client> w = c;
286 Mutex::Autolock lock(mLock);
287 mClients.add(w);
288 }
289 ::close(fd);
290 return c;
291}
292
Andreas Huber784202e2009-10-15 13:46:54 -0700293sp<IOMX> MediaPlayerService::getOMX() {
294 Mutex::Autolock autoLock(mLock);
295
296 if (mOMX.get() == NULL) {
297 mOMX = new OMX;
298 }
299
300 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700301}
302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308
309 result.append(" AudioCache\n");
310 if (mHeap != 0) {
311 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
312 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
313 result.append(buffer);
314 }
315 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
316 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
317 result.append(buffer);
318 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
319 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
320 result.append(buffer);
321 ::write(fd, result.string(), result.size());
322 return NO_ERROR;
323}
324
325status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
326{
327 const size_t SIZE = 256;
328 char buffer[SIZE];
329 String8 result;
330
331 result.append(" AudioOutput\n");
332 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
333 mStreamType, mLeftVolume, mRightVolume);
334 result.append(buffer);
335 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
336 mMsecsPerFrame, mLatency);
337 result.append(buffer);
338 ::write(fd, result.string(), result.size());
339 if (mTrack != 0) {
340 mTrack->dump(fd, args);
341 }
342 return NO_ERROR;
343}
344
345status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
350 result.append(" Client\n");
351 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
352 mPid, mConnId, mStatus, mLoop?"true": "false");
353 result.append(buffer);
354 write(fd, result.string(), result.size());
355 if (mAudioOutput != 0) {
356 mAudioOutput->dump(fd, args);
357 }
358 write(fd, "\n", 1);
359 return NO_ERROR;
360}
361
362static int myTid() {
363#ifdef HAVE_GETTID
364 return gettid();
365#else
366 return getpid();
367#endif
368}
369
370#if defined(__arm__)
371extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
372 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
373extern "C" void free_malloc_leak_info(uint8_t* info);
374
Andreas Huber27123462009-10-27 15:50:04 -0700375// Use the String-class below instead of String8 to allocate all memory
376// beforehand and not reenter the heap while we are examining it...
377struct MyString8 {
378 static const size_t MAX_SIZE = 256 * 1024;
379
380 MyString8()
381 : mPtr((char *)malloc(MAX_SIZE)) {
382 *mPtr = '\0';
383 }
384
385 ~MyString8() {
386 free(mPtr);
387 }
388
389 void append(const char *s) {
390 strcat(mPtr, s);
391 }
392
393 const char *string() const {
394 return mPtr;
395 }
396
397 size_t size() const {
398 return strlen(mPtr);
399 }
400
401private:
402 char *mPtr;
403
404 MyString8(const MyString8 &);
405 MyString8 &operator=(const MyString8 &);
406};
407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408void memStatus(int fd, const Vector<String16>& args)
409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
Andreas Huber27123462009-10-27 15:50:04 -0700412 MyString8 result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413
414 typedef struct {
415 size_t size;
416 size_t dups;
417 intptr_t * backtrace;
418 } AllocEntry;
419
420 uint8_t *info = NULL;
421 size_t overallSize = 0;
422 size_t infoSize = 0;
423 size_t totalMemory = 0;
424 size_t backtraceSize = 0;
425
426 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
427 if (info) {
428 uint8_t *ptr = info;
429 size_t count = overallSize / infoSize;
430
431 snprintf(buffer, SIZE, " Allocation count %i\n", count);
432 result.append(buffer);
James Dong3d23a612010-02-25 10:06:32 -0800433 snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
434 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
436 AllocEntry * entries = new AllocEntry[count];
437
438 for (size_t i = 0; i < count; i++) {
439 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
440 AllocEntry *e = &entries[i];
441
442 e->size = *reinterpret_cast<size_t *>(ptr);
443 ptr += sizeof(size_t);
444
445 e->dups = *reinterpret_cast<size_t *>(ptr);
446 ptr += sizeof(size_t);
447
448 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
449 ptr += sizeof(intptr_t) * backtraceSize;
450 }
451
452 // Now we need to sort the entries. They come sorted by size but
453 // not by stack trace which causes problems using diff.
454 bool moved;
455 do {
456 moved = false;
457 for (size_t i = 0; i < (count - 1); i++) {
458 AllocEntry *e1 = &entries[i];
459 AllocEntry *e2 = &entries[i+1];
460
461 bool swap = e1->size < e2->size;
462 if (e1->size == e2->size) {
463 for(size_t j = 0; j < backtraceSize; j++) {
464 if (e1->backtrace[j] == e2->backtrace[j]) {
465 continue;
466 }
467 swap = e1->backtrace[j] < e2->backtrace[j];
468 break;
469 }
470 }
471 if (swap) {
472 AllocEntry t = entries[i];
473 entries[i] = entries[i+1];
474 entries[i+1] = t;
475 moved = true;
476 }
477 }
478 } while (moved);
479
480 for (size_t i = 0; i < count; i++) {
481 AllocEntry *e = &entries[i];
482
James Dong3d23a612010-02-25 10:06:32 -0800483 snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 result.append(buffer);
485 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
486 if (ct) {
487 result.append(", ");
488 }
489 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
490 result.append(buffer);
491 }
492 result.append("\n");
493 }
494
495 delete[] entries;
496 free_malloc_leak_info(info);
497 }
498
499 write(fd, result.string(), result.size());
500}
501#endif
502
503status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
504{
505 const size_t SIZE = 256;
506 char buffer[SIZE];
507 String8 result;
508 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
509 snprintf(buffer, SIZE, "Permission Denial: "
510 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
511 IPCThreadState::self()->getCallingPid(),
512 IPCThreadState::self()->getCallingUid());
513 result.append(buffer);
514 } else {
515 Mutex::Autolock lock(mLock);
516 for (int i = 0, n = mClients.size(); i < n; ++i) {
517 sp<Client> c = mClients[i].promote();
518 if (c != 0) c->dump(fd, args);
519 }
Gloria Wang608a2632009-10-29 15:46:37 -0700520 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
521 result.append(" MediaRecorderClient\n");
522 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
523 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid);
524 result.append(buffer);
525 }
526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 result.append(" Files opened and/or mapped:\n");
528 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
529 FILE *f = fopen(buffer, "r");
530 if (f) {
531 while (!feof(f)) {
532 fgets(buffer, SIZE, f);
533 if (strstr(buffer, " /sdcard/") ||
534 strstr(buffer, " /system/sounds/") ||
535 strstr(buffer, " /system/media/")) {
536 result.append(" ");
537 result.append(buffer);
538 }
539 }
540 fclose(f);
541 } else {
542 result.append("couldn't open ");
543 result.append(buffer);
544 result.append("\n");
545 }
546
547 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
548 DIR *d = opendir(buffer);
549 if (d) {
550 struct dirent *ent;
551 while((ent = readdir(d)) != NULL) {
552 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
553 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
554 struct stat s;
555 if (lstat(buffer, &s) == 0) {
556 if ((s.st_mode & S_IFMT) == S_IFLNK) {
557 char linkto[256];
558 int len = readlink(buffer, linkto, sizeof(linkto));
559 if(len > 0) {
560 if(len > 255) {
561 linkto[252] = '.';
562 linkto[253] = '.';
563 linkto[254] = '.';
564 linkto[255] = 0;
565 } else {
566 linkto[len] = 0;
567 }
568 if (strstr(linkto, "/sdcard/") == linkto ||
569 strstr(linkto, "/system/sounds/") == linkto ||
570 strstr(linkto, "/system/media/") == linkto) {
571 result.append(" ");
572 result.append(buffer);
573 result.append(" -> ");
574 result.append(linkto);
575 result.append("\n");
576 }
577 }
578 } else {
579 result.append(" unexpected type for ");
580 result.append(buffer);
581 result.append("\n");
582 }
583 }
584 }
585 }
586 closedir(d);
587 } else {
588 result.append("couldn't open ");
589 result.append(buffer);
590 result.append("\n");
591 }
592
593#if defined(__arm__)
594 bool dumpMem = false;
595 for (size_t i = 0; i < args.size(); i++) {
596 if (args[i] == String16("-m")) {
597 dumpMem = true;
598 }
599 }
600 if (dumpMem) {
601 memStatus(fd, args);
602 }
603#endif
604 }
605 write(fd, result.string(), result.size());
606 return NO_ERROR;
607}
608
609void MediaPlayerService::removeClient(wp<Client> client)
610{
611 Mutex::Autolock lock(mLock);
612 mClients.remove(client);
613}
614
615MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
616 int32_t connId, const sp<IMediaPlayerClient>& client)
617{
618 LOGV("Client(%d) constructor", connId);
619 mPid = pid;
620 mConnId = connId;
621 mService = service;
622 mClient = client;
623 mLoop = false;
624 mStatus = NO_INIT;
625#if CALLBACK_ANTAGONIZER
626 LOGD("create Antagonizer");
627 mAntagonizer = new Antagonizer(notify, this);
628#endif
629}
630
631MediaPlayerService::Client::~Client()
632{
633 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
634 mAudioOutput.clear();
635 wp<Client> client(this);
636 disconnect();
637 mService->removeClient(client);
638}
639
640void MediaPlayerService::Client::disconnect()
641{
642 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
643 // grab local reference and clear main reference to prevent future
644 // access to object
645 sp<MediaPlayerBase> p;
646 {
647 Mutex::Autolock l(mLock);
648 p = mPlayer;
649 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700650 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 mPlayer.clear();
653
654 // clear the notification to prevent callbacks to dead client
655 // and reset the player. We assume the player will serialize
656 // access to itself if necessary.
657 if (p != 0) {
658 p->setNotifyCallback(0, 0);
659#if CALLBACK_ANTAGONIZER
660 LOGD("kill Antagonizer");
661 mAntagonizer->kill();
662#endif
663 p->reset();
664 }
665
666 IPCThreadState::self()->flushCommands();
667}
668
Andreas Huber0d596d42009-08-07 09:30:32 -0700669static player_type getDefaultPlayerType() {
Andreas Huber2aa39c42009-09-11 09:54:52 -0700670#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber0d596d42009-08-07 09:30:32 -0700671 char value[PROPERTY_VALUE_MAX];
672 if (property_get("media.stagefright.enable-player", value, NULL)
673 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
674 return STAGEFRIGHT_PLAYER;
675 }
Andreas Huber2aa39c42009-09-11 09:54:52 -0700676#endif
Andreas Huber0d596d42009-08-07 09:30:32 -0700677
678 return PV_PLAYER;
679}
680
Andreas Hubereb5eef32010-05-04 11:46:42 -0700681// By default we use the VORBIS_PLAYER for vorbis playback (duh!),
682// but if the magic property is set we will use our new experimental
683// stagefright code instead.
684static player_type OverrideStagefrightForVorbis(player_type player) {
685 if (player != VORBIS_PLAYER) {
686 return player;
687 }
688
689#if BUILD_WITH_FULL_STAGEFRIGHT
690 char value[PROPERTY_VALUE_MAX];
691 if (property_get("media.stagefright.enable-vorbis", value, NULL)
692 && (!strcmp(value, "1") || !strcmp(value, "true"))) {
693 return STAGEFRIGHT_PLAYER;
694 }
695#endif
696
697 return VORBIS_PLAYER;
698}
699
700
James Dong392ff3b2009-09-06 14:29:45 -0700701player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702{
703 char buf[20];
704 lseek(fd, offset, SEEK_SET);
705 read(fd, buf, sizeof(buf));
706 lseek(fd, offset, SEEK_SET);
707
708 long ident = *((long*)buf);
709
710 // Ogg vorbis?
711 if (ident == 0x5367674f) // 'OggS'
Andreas Hubereb5eef32010-05-04 11:46:42 -0700712 return OverrideStagefrightForVorbis(VORBIS_PLAYER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
Andreas Huber2cb5c9c2010-01-20 16:11:15 -0800714#ifndef NO_OPENCORE
715 if (ident == 0x75b22630) {
716 // The magic number for .asf files, i.e. wmv and wma content.
717 // These are not currently supported through stagefright.
718 return PV_PLAYER;
719 }
720#endif
721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 // Some kind of MIDI?
723 EAS_DATA_HANDLE easdata;
724 if (EAS_Init(&easdata) == EAS_SUCCESS) {
725 EAS_FILE locator;
726 locator.path = NULL;
727 locator.fd = fd;
728 locator.offset = offset;
729 locator.length = length;
730 EAS_HANDLE eashandle;
731 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
732 EAS_CloseFile(easdata, eashandle);
733 EAS_Shutdown(easdata);
734 return SONIVOX_PLAYER;
735 }
736 EAS_Shutdown(easdata);
737 }
738
Andreas Huber0d596d42009-08-07 09:30:32 -0700739 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740}
741
James Dong392ff3b2009-09-06 14:29:45 -0700742player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700744 if (TestPlayerStub::canBeUsed(url)) {
745 return TEST_PLAYER;
746 }
747
Andreas Hubereb5eef32010-05-04 11:46:42 -0700748 bool useStagefrightForHTTP = false;
749 char value[PROPERTY_VALUE_MAX];
750 if (property_get("media.stagefright.enable-http", value, NULL)
751 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
752 useStagefrightForHTTP = true;
753 }
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 // use MidiFile for MIDI extensions
756 int lenURL = strlen(url);
757 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
758 int len = strlen(FILE_EXTS[i].extension);
759 int start = lenURL - len;
760 if (start > 0) {
761 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Hubereb5eef32010-05-04 11:46:42 -0700762 if (FILE_EXTS[i].playertype == VORBIS_PLAYER
763 && !strncasecmp(url, "http://", 7)
764 && useStagefrightForHTTP) {
765 return STAGEFRIGHT_PLAYER;
766 }
767 return OverrideStagefrightForVorbis(FILE_EXTS[i].playertype);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 }
770 }
771
Andreas Huber6a3a0182009-12-17 13:31:13 -0800772 if (!strncasecmp(url, "http://", 7)) {
Andreas Hubereb5eef32010-05-04 11:46:42 -0700773 if (!useStagefrightForHTTP) {
Andreas Huber67aee052010-01-04 17:27:37 -0800774 return PV_PLAYER;
775 }
Andreas Huber6a3a0182009-12-17 13:31:13 -0800776 }
777
James Dong42d66572010-04-13 21:33:26 -0700778 // Use PV_PLAYER for rtsp for now
779 if (!strncasecmp(url, "rtsp://", 7)) {
780 return PV_PLAYER;
781 }
782
Andreas Huber0d596d42009-08-07 09:30:32 -0700783 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784}
785
786static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
787 notify_callback_f notifyFunc)
788{
789 sp<MediaPlayerBase> p;
790 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700791#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 case PV_PLAYER:
793 LOGV(" create PVPlayer");
794 p = new PVPlayer();
795 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700796#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 case SONIVOX_PLAYER:
798 LOGV(" create MidiFile");
799 p = new MidiFile();
800 break;
801 case VORBIS_PLAYER:
802 LOGV(" create VorbisPlayer");
803 p = new VorbisPlayer();
804 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700805#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Hubere46b7be2009-07-14 16:56:47 -0700806 case STAGEFRIGHT_PLAYER:
807 LOGV(" create StagefrightPlayer");
808 p = new StagefrightPlayer;
809 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700810#endif
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700811 case TEST_PLAYER:
812 LOGV("Create Test Player stub");
813 p = new TestPlayerStub();
814 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816 if (p != NULL) {
817 if (p->initCheck() == NO_ERROR) {
818 p->setNotifyCallback(cookie, notifyFunc);
819 } else {
820 p.clear();
821 }
822 }
823 if (p == NULL) {
824 LOGE("Failed to create player object");
825 }
826 return p;
827}
828
829sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
830{
831 // determine if we have the right player type
832 sp<MediaPlayerBase> p = mPlayer;
833 if ((p != NULL) && (p->playerType() != playerType)) {
834 LOGV("delete player");
835 p.clear();
836 }
837 if (p == NULL) {
838 p = android::createPlayer(playerType, this, notify);
839 }
840 return p;
841}
842
Andreas Huber25643002010-01-28 11:19:57 -0800843status_t MediaPlayerService::Client::setDataSource(
844 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845{
846 LOGV("setDataSource(%s)", url);
847 if (url == NULL)
848 return UNKNOWN_ERROR;
849
850 if (strncmp(url, "content://", 10) == 0) {
851 // get a filedescriptor for the content Uri and
852 // pass it to the setDataSource(fd) method
853
854 String16 url16(url);
855 int fd = android::openContentProviderFile(url16);
856 if (fd < 0)
857 {
858 LOGE("Couldn't open fd for %s", url);
859 return UNKNOWN_ERROR;
860 }
861 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
862 close(fd);
863 return mStatus;
864 } else {
865 player_type playerType = getPlayerType(url);
866 LOGV("player type = %d", playerType);
867
868 // create the right type of player
869 sp<MediaPlayerBase> p = createPlayer(playerType);
870 if (p == NULL) return NO_INIT;
871
872 if (!p->hardwareOutput()) {
873 mAudioOutput = new AudioOutput();
874 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
875 }
876
877 // now set data source
878 LOGV(" setDataSource");
Andreas Huber25643002010-01-28 11:19:57 -0800879 mStatus = p->setDataSource(url, headers);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700880 if (mStatus == NO_ERROR) {
881 mPlayer = p;
882 } else {
883 LOGE(" error: %d", mStatus);
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 return mStatus;
886 }
887}
888
889status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
890{
891 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
892 struct stat sb;
893 int ret = fstat(fd, &sb);
894 if (ret != 0) {
895 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
896 return UNKNOWN_ERROR;
897 }
898
899 LOGV("st_dev = %llu", sb.st_dev);
900 LOGV("st_mode = %u", sb.st_mode);
901 LOGV("st_uid = %lu", sb.st_uid);
902 LOGV("st_gid = %lu", sb.st_gid);
903 LOGV("st_size = %llu", sb.st_size);
904
905 if (offset >= sb.st_size) {
906 LOGE("offset error");
907 ::close(fd);
908 return UNKNOWN_ERROR;
909 }
910 if (offset + length > sb.st_size) {
911 length = sb.st_size - offset;
912 LOGV("calculated length = %lld", length);
913 }
914
915 player_type playerType = getPlayerType(fd, offset, length);
916 LOGV("player type = %d", playerType);
917
918 // create the right type of player
919 sp<MediaPlayerBase> p = createPlayer(playerType);
920 if (p == NULL) return NO_INIT;
921
922 if (!p->hardwareOutput()) {
923 mAudioOutput = new AudioOutput();
924 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
925 }
926
927 // now set data source
928 mStatus = p->setDataSource(fd, offset, length);
929 if (mStatus == NO_ERROR) mPlayer = p;
930 return mStatus;
931}
932
933status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
934{
935 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
936 sp<MediaPlayerBase> p = getPlayer();
937 if (p == 0) return UNKNOWN_ERROR;
938 return p->setVideoSurface(surface);
939}
940
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700941status_t MediaPlayerService::Client::invoke(const Parcel& request,
942 Parcel *reply)
943{
944 sp<MediaPlayerBase> p = getPlayer();
945 if (p == NULL) return UNKNOWN_ERROR;
946 return p->invoke(request, reply);
947}
948
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700949// This call doesn't need to access the native player.
950status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
951{
952 status_t status;
nikobc726922009-07-20 15:07:26 -0700953 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700954
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700955 if (unmarshallFilter(filter, &allow, &status) &&
956 unmarshallFilter(filter, &drop, &status)) {
957 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700958
959 mMetadataAllow = allow;
960 mMetadataDrop = drop;
961 }
962 return status;
963}
964
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700965status_t MediaPlayerService::Client::getMetadata(
966 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700967{
nikobc726922009-07-20 15:07:26 -0700968 sp<MediaPlayerBase> player = getPlayer();
969 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700970
niko89948372009-07-16 16:39:53 -0700971 status_t status;
972 // Placeholder for the return code, updated by the caller.
973 reply->writeInt32(-1);
974
nikobc726922009-07-20 15:07:26 -0700975 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700976
977 // We don't block notifications while we fetch the data. We clear
978 // mMetadataUpdated first so we don't lose notifications happening
979 // during the rest of this call.
980 {
981 Mutex::Autolock lock(mLock);
982 if (update_only) {
niko89948372009-07-16 16:39:53 -0700983 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700984 }
985 mMetadataUpdated.clear();
986 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700987
nikobc726922009-07-20 15:07:26 -0700988 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700989
nikobc726922009-07-20 15:07:26 -0700990 metadata.appendHeader();
991 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700992
993 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700994 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700995 LOGE("getMetadata failed %d", status);
996 return status;
997 }
998
999 // FIXME: Implement filtering on the result. Not critical since
1000 // filtering takes place on the update notifications already. This
1001 // would be when all the metadata are fetch and a filter is set.
1002
niko89948372009-07-16 16:39:53 -07001003 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -07001004 metadata.updateLength();
niko89948372009-07-16 16:39:53 -07001005 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -07001006}
1007
Andreas Huberfbb38852010-02-12 12:35:58 -08001008status_t MediaPlayerService::Client::suspend() {
1009 sp<MediaPlayerBase> p = getPlayer();
1010 if (p == 0) return UNKNOWN_ERROR;
1011
1012 return p->suspend();
1013}
1014
1015status_t MediaPlayerService::Client::resume() {
1016 sp<MediaPlayerBase> p = getPlayer();
1017 if (p == 0) return UNKNOWN_ERROR;
1018
1019 return p->resume();
1020}
1021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022status_t MediaPlayerService::Client::prepareAsync()
1023{
1024 LOGV("[%d] prepareAsync", mConnId);
1025 sp<MediaPlayerBase> p = getPlayer();
1026 if (p == 0) return UNKNOWN_ERROR;
1027 status_t ret = p->prepareAsync();
1028#if CALLBACK_ANTAGONIZER
1029 LOGD("start Antagonizer");
1030 if (ret == NO_ERROR) mAntagonizer->start();
1031#endif
1032 return ret;
1033}
1034
1035status_t MediaPlayerService::Client::start()
1036{
1037 LOGV("[%d] start", mConnId);
1038 sp<MediaPlayerBase> p = getPlayer();
1039 if (p == 0) return UNKNOWN_ERROR;
1040 p->setLooping(mLoop);
1041 return p->start();
1042}
1043
1044status_t MediaPlayerService::Client::stop()
1045{
1046 LOGV("[%d] stop", mConnId);
1047 sp<MediaPlayerBase> p = getPlayer();
1048 if (p == 0) return UNKNOWN_ERROR;
1049 return p->stop();
1050}
1051
1052status_t MediaPlayerService::Client::pause()
1053{
1054 LOGV("[%d] pause", mConnId);
1055 sp<MediaPlayerBase> p = getPlayer();
1056 if (p == 0) return UNKNOWN_ERROR;
1057 return p->pause();
1058}
1059
1060status_t MediaPlayerService::Client::isPlaying(bool* state)
1061{
1062 *state = false;
1063 sp<MediaPlayerBase> p = getPlayer();
1064 if (p == 0) return UNKNOWN_ERROR;
1065 *state = p->isPlaying();
1066 LOGV("[%d] isPlaying: %d", mConnId, *state);
1067 return NO_ERROR;
1068}
1069
1070status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1071{
1072 LOGV("getCurrentPosition");
1073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 status_t ret = p->getCurrentPosition(msec);
1076 if (ret == NO_ERROR) {
1077 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1078 } else {
1079 LOGE("getCurrentPosition returned %d", ret);
1080 }
1081 return ret;
1082}
1083
1084status_t MediaPlayerService::Client::getDuration(int *msec)
1085{
1086 LOGV("getDuration");
1087 sp<MediaPlayerBase> p = getPlayer();
1088 if (p == 0) return UNKNOWN_ERROR;
1089 status_t ret = p->getDuration(msec);
1090 if (ret == NO_ERROR) {
1091 LOGV("[%d] getDuration = %d", mConnId, *msec);
1092 } else {
1093 LOGE("getDuration returned %d", ret);
1094 }
1095 return ret;
1096}
1097
1098status_t MediaPlayerService::Client::seekTo(int msec)
1099{
1100 LOGV("[%d] seekTo(%d)", mConnId, msec);
1101 sp<MediaPlayerBase> p = getPlayer();
1102 if (p == 0) return UNKNOWN_ERROR;
1103 return p->seekTo(msec);
1104}
1105
1106status_t MediaPlayerService::Client::reset()
1107{
1108 LOGV("[%d] reset", mConnId);
1109 sp<MediaPlayerBase> p = getPlayer();
1110 if (p == 0) return UNKNOWN_ERROR;
1111 return p->reset();
1112}
1113
1114status_t MediaPlayerService::Client::setAudioStreamType(int type)
1115{
1116 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1117 // TODO: for hardware output, call player instead
1118 Mutex::Autolock l(mLock);
1119 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1120 return NO_ERROR;
1121}
1122
1123status_t MediaPlayerService::Client::setLooping(int loop)
1124{
1125 LOGV("[%d] setLooping(%d)", mConnId, loop);
1126 mLoop = loop;
1127 sp<MediaPlayerBase> p = getPlayer();
1128 if (p != 0) return p->setLooping(loop);
1129 return NO_ERROR;
1130}
1131
1132status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1133{
1134 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1135 // TODO: for hardware output, call player instead
1136 Mutex::Autolock l(mLock);
1137 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1138 return NO_ERROR;
1139}
1140
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1143{
1144 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001145
1146 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001147 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001148 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001149
1150 if(client->shouldDropMetadata(metadata_type)) {
1151 return;
1152 }
1153
1154 // Update the list of metadata that have changed. getMetadata
1155 // also access mMetadataUpdated and clears it.
1156 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1159 client->mClient->notify(msg, ext1, ext2);
1160}
1161
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001162
nikobc726922009-07-20 15:07:26 -07001163bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001164{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001165 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001166
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001167 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001168 return true;
1169 }
1170
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001171 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001172 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001173 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001174 return true;
1175 }
1176}
1177
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001178
nikobc726922009-07-20 15:07:26 -07001179void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001180 Mutex::Autolock lock(mLock);
1181 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1182 mMetadataUpdated.add(metadata_type);
1183 }
1184}
1185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186#if CALLBACK_ANTAGONIZER
1187const int Antagonizer::interval = 10000; // 10 msecs
1188
1189Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1190 mExit(false), mActive(false), mClient(client), mCb(cb)
1191{
1192 createThread(callbackThread, this);
1193}
1194
1195void Antagonizer::kill()
1196{
1197 Mutex::Autolock _l(mLock);
1198 mActive = false;
1199 mExit = true;
1200 mCondition.wait(mLock);
1201}
1202
1203int Antagonizer::callbackThread(void* user)
1204{
1205 LOGD("Antagonizer started");
1206 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1207 while (!p->mExit) {
1208 if (p->mActive) {
1209 LOGV("send event");
1210 p->mCb(p->mClient, 0, 0, 0);
1211 }
1212 usleep(interval);
1213 }
1214 Mutex::Autolock _l(p->mLock);
1215 p->mCondition.signal();
1216 LOGD("Antagonizer stopped");
1217 return 0;
1218}
1219#endif
1220
1221static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1222
1223sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1224{
1225 LOGV("decode(%s)", url);
1226 sp<MemoryBase> mem;
1227 sp<MediaPlayerBase> player;
1228
1229 // Protect our precious, precious DRMd ringtones by only allowing
1230 // decoding of http, but not filesystem paths or content Uris.
1231 // If the application wants to decode those, it should open a
1232 // filedescriptor for them and use that.
1233 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1234 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1235 return mem;
1236 }
1237
1238 player_type playerType = getPlayerType(url);
1239 LOGV("player type = %d", playerType);
1240
1241 // create the right type of player
1242 sp<AudioCache> cache = new AudioCache(url);
1243 player = android::createPlayer(playerType, cache.get(), cache->notify);
1244 if (player == NULL) goto Exit;
1245 if (player->hardwareOutput()) goto Exit;
1246
1247 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1248
1249 // set data source
1250 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1251
1252 LOGV("prepare");
1253 player->prepareAsync();
1254
1255 LOGV("wait for prepare");
1256 if (cache->wait() != NO_ERROR) goto Exit;
1257
1258 LOGV("start");
1259 player->start();
1260
1261 LOGV("wait for playback complete");
1262 if (cache->wait() != NO_ERROR) goto Exit;
1263
1264 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1265 *pSampleRate = cache->sampleRate();
1266 *pNumChannels = cache->channelCount();
1267 *pFormat = cache->format();
1268 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1269
1270Exit:
1271 if (player != 0) player->reset();
1272 return mem;
1273}
1274
1275sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1276{
1277 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1278 sp<MemoryBase> mem;
1279 sp<MediaPlayerBase> player;
1280
1281 player_type playerType = getPlayerType(fd, offset, length);
1282 LOGV("player type = %d", playerType);
1283
1284 // create the right type of player
1285 sp<AudioCache> cache = new AudioCache("decode_fd");
1286 player = android::createPlayer(playerType, cache.get(), cache->notify);
1287 if (player == NULL) goto Exit;
1288 if (player->hardwareOutput()) goto Exit;
1289
1290 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1291
1292 // set data source
1293 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1294
1295 LOGV("prepare");
1296 player->prepareAsync();
1297
1298 LOGV("wait for prepare");
1299 if (cache->wait() != NO_ERROR) goto Exit;
1300
1301 LOGV("start");
1302 player->start();
1303
1304 LOGV("wait for playback complete");
1305 if (cache->wait() != NO_ERROR) goto Exit;
1306
1307 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1308 *pSampleRate = cache->sampleRate();
1309 *pNumChannels = cache->channelCount();
1310 *pFormat = cache->format();
1311 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1312
1313Exit:
1314 if (player != 0) player->reset();
1315 ::close(fd);
1316 return mem;
1317}
1318
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001319/*
1320 * Avert your eyes, ugly hack ahead.
1321 * The following is to support music visualizations.
1322 */
1323
1324static const int NUMVIZBUF = 32;
1325static const int VIZBUFFRAMES = 1024;
Marco Nelissene274db12010-01-12 09:23:54 -08001326static const int BUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1327static const int TOTALBUFTIMEMSEC = NUMVIZBUF * BUFTIMEMSEC;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001328
1329static bool gotMem = false;
Marco Nelissene274db12010-01-12 09:23:54 -08001330static sp<MemoryHeapBase> heap;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001331static sp<MemoryBase> mem[NUMVIZBUF];
Marco Nelissene274db12010-01-12 09:23:54 -08001332static uint64_t endTime;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001333static uint64_t lastReadTime;
1334static uint64_t lastWriteTime;
1335static int writeIdx = 0;
1336
1337static void allocVizBufs() {
1338 if (!gotMem) {
Marco Nelissene274db12010-01-12 09:23:54 -08001339 heap = new MemoryHeapBase(NUMVIZBUF * VIZBUFFRAMES * 2, 0, "snooper");
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001340 for (int i=0;i<NUMVIZBUF;i++) {
Marco Nelissene274db12010-01-12 09:23:54 -08001341 mem[i] = new MemoryBase(heap, VIZBUFFRAMES * 2 * i, VIZBUFFRAMES * 2);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001342 }
Marco Nelissene274db12010-01-12 09:23:54 -08001343 endTime = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001344 gotMem = true;
1345 }
1346}
1347
1348
1349/*
1350 * Get a buffer of audio data that is about to be played.
1351 * We don't synchronize this because in practice the writer
1352 * is ahead of the reader, and even if we did happen to catch
1353 * a buffer while it's being written, it's just a visualization,
1354 * so no harm done.
1355 */
1356static sp<MemoryBase> getVizBuffer() {
1357
1358 allocVizBufs();
1359
Marco Nelissene274db12010-01-12 09:23:54 -08001360 lastReadTime = uptimeMillis();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001361
1362 // if there is no recent buffer (yet), just return empty handed
1363 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
Marco Nelissene274db12010-01-12 09:23:54 -08001364 //LOGI("@@@@ no audio data to look at yet: %d + %d < %d", (int)lastWriteTime, TOTALBUFTIMEMSEC, (int)lastReadTime);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001365 return NULL;
1366 }
1367
Marco Nelissene274db12010-01-12 09:23:54 -08001368 int timedelta = endTime - lastReadTime;
1369 if (timedelta < 0) timedelta = 0;
1370 int framedelta = timedelta * 44100 / 1000;
1371 int headIdx = (writeIdx - framedelta) / VIZBUFFRAMES - 1;
1372 while (headIdx < 0) {
1373 headIdx += NUMVIZBUF;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001374 }
Marco Nelissene274db12010-01-12 09:23:54 -08001375 return mem[headIdx];
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001376}
1377
Marco Nelissene274db12010-01-12 09:23:54 -08001378// Append the data to the vizualization buffer
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001379static void makeVizBuffers(const char *data, int len, uint64_t time) {
1380
1381 allocVizBufs();
1382
1383 uint64_t startTime = time;
1384 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
Marco Nelissene274db12010-01-12 09:23:54 -08001385 int offset = writeIdx;
1386 int maxoff = heap->getSize() / 2; // in shorts
1387 short *base = (short*)heap->getBase();
1388 short *src = (short*)data;
1389 while (len > 0) {
1390
1391 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1392 // This should still be good enough for a visualization
1393 base[offset++] = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1394 src += 2;
1395 len -= frameSize;
1396 if (offset >= maxoff) {
1397 offset = 0;
1398 }
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001399 }
Marco Nelissene274db12010-01-12 09:23:54 -08001400 writeIdx = offset;
1401 endTime = time + (len / frameSize) / 44;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001402 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1403}
1404
1405sp<IMemory> MediaPlayerService::snoop()
1406{
1407 sp<MemoryBase> mem = getVizBuffer();
1408 return mem;
1409}
1410
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412#undef LOG_TAG
1413#define LOG_TAG "AudioSink"
1414MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001415 : mCallback(NULL),
1416 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 mTrack = 0;
1418 mStreamType = AudioSystem::MUSIC;
1419 mLeftVolume = 1.0;
1420 mRightVolume = 1.0;
1421 mLatency = 0;
1422 mMsecsPerFrame = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001423 mNumFramesWritten = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 setMinBufferCount();
1425}
1426
1427MediaPlayerService::AudioOutput::~AudioOutput()
1428{
1429 close();
1430}
1431
1432void MediaPlayerService::AudioOutput::setMinBufferCount()
1433{
1434 char value[PROPERTY_VALUE_MAX];
1435 if (property_get("ro.kernel.qemu", value, 0)) {
1436 mIsOnEmulator = true;
1437 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1438 }
1439}
1440
1441bool MediaPlayerService::AudioOutput::isOnEmulator()
1442{
1443 setMinBufferCount();
1444 return mIsOnEmulator;
1445}
1446
1447int MediaPlayerService::AudioOutput::getMinBufferCount()
1448{
1449 setMinBufferCount();
1450 return mMinBufferCount;
1451}
1452
1453ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1454{
1455 if (mTrack == 0) return NO_INIT;
1456 return mTrack->frameCount() * frameSize();
1457}
1458
1459ssize_t MediaPlayerService::AudioOutput::frameCount() const
1460{
1461 if (mTrack == 0) return NO_INIT;
1462 return mTrack->frameCount();
1463}
1464
1465ssize_t MediaPlayerService::AudioOutput::channelCount() const
1466{
1467 if (mTrack == 0) return NO_INIT;
1468 return mTrack->channelCount();
1469}
1470
1471ssize_t MediaPlayerService::AudioOutput::frameSize() const
1472{
1473 if (mTrack == 0) return NO_INIT;
1474 return mTrack->frameSize();
1475}
1476
1477uint32_t MediaPlayerService::AudioOutput::latency () const
1478{
1479 return mLatency;
1480}
1481
1482float MediaPlayerService::AudioOutput::msecsPerFrame() const
1483{
1484 return mMsecsPerFrame;
1485}
1486
Eric Laurent0986e792010-01-19 17:37:09 -08001487status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1488{
1489 if (mTrack == 0) return NO_INIT;
1490 return mTrack->getPosition(position);
1491}
1492
Andreas Hubere46b7be2009-07-14 16:56:47 -07001493status_t MediaPlayerService::AudioOutput::open(
1494 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1495 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001497 mCallback = cb;
1498 mCallbackCookie = cookie;
1499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 // Check argument "bufferCount" against the mininum buffer count
1501 if (bufferCount < mMinBufferCount) {
1502 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1503 bufferCount = mMinBufferCount;
1504
1505 }
1506 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1507 if (mTrack) close();
1508 int afSampleRate;
1509 int afFrameCount;
1510 int frameCount;
1511
1512 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1513 return NO_INIT;
1514 }
1515 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1516 return NO_INIT;
1517 }
1518
1519 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001520
1521 AudioTrack *t;
1522 if (mCallback != NULL) {
1523 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001524 mStreamType,
1525 sampleRate,
1526 format,
1527 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1528 frameCount,
1529 0 /* flags */,
1530 CallbackWrapper,
1531 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001532 } else {
1533 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001534 mStreamType,
1535 sampleRate,
1536 format,
1537 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1538 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001539 }
1540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1542 LOGE("Unable to create audio track");
1543 delete t;
1544 return NO_INIT;
1545 }
1546
1547 LOGV("setVolume");
1548 t->setVolume(mLeftVolume, mRightVolume);
1549 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparksb904c2a2009-12-03 10:13:32 -08001550 mLatency = t->latency();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 mTrack = t;
1552 return NO_ERROR;
1553}
1554
1555void MediaPlayerService::AudioOutput::start()
1556{
1557 LOGV("start");
1558 if (mTrack) {
1559 mTrack->setVolume(mLeftVolume, mRightVolume);
1560 mTrack->start();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001561 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563}
1564
Marco Nelissene274db12010-01-12 09:23:54 -08001565void MediaPlayerService::AudioOutput::snoopWrite(const void* buffer, size_t size) {
1566 // Only make visualization buffers if anyone recently requested visualization data
1567 uint64_t now = uptimeMillis();
1568 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1569 // Based on the current play counter, the number of frames written and
1570 // the current real time we can calculate the approximate real start
1571 // time of the buffer we're about to write.
1572 uint32_t pos;
1573 mTrack->getPosition(&pos);
1574
1575 // we're writing ahead by this many frames:
1576 int ahead = mNumFramesWritten - pos;
1577 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1578 // which is this many milliseconds, assuming 44100 Hz:
1579 ahead /= 44;
1580
1581 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1582 lastWriteTime = now;
1583 }
1584}
1585
1586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1588{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001589 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001592 if (mTrack) {
Marco Nelissene274db12010-01-12 09:23:54 -08001593 snoopWrite(buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001594 ssize_t ret = mTrack->write(buffer, size);
1595 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1596 return ret;
1597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 return NO_INIT;
1599}
1600
1601void MediaPlayerService::AudioOutput::stop()
1602{
1603 LOGV("stop");
1604 if (mTrack) mTrack->stop();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001605 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606}
1607
1608void MediaPlayerService::AudioOutput::flush()
1609{
1610 LOGV("flush");
1611 if (mTrack) mTrack->flush();
1612}
1613
1614void MediaPlayerService::AudioOutput::pause()
1615{
1616 LOGV("pause");
1617 if (mTrack) mTrack->pause();
Marco Nelissen758613d2009-11-02 13:52:11 -08001618 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619}
1620
1621void MediaPlayerService::AudioOutput::close()
1622{
1623 LOGV("close");
1624 delete mTrack;
1625 mTrack = 0;
1626}
1627
1628void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1629{
1630 LOGV("setVolume(%f, %f)", left, right);
1631 mLeftVolume = left;
1632 mRightVolume = right;
1633 if (mTrack) {
1634 mTrack->setVolume(left, right);
1635 }
1636}
1637
Andreas Hubere46b7be2009-07-14 16:56:47 -07001638// static
1639void MediaPlayerService::AudioOutput::CallbackWrapper(
1640 int event, void *cookie, void *info) {
Marco Nelissene274db12010-01-12 09:23:54 -08001641 //LOGV("callbackwrapper");
Andreas Hubere46b7be2009-07-14 16:56:47 -07001642 if (event != AudioTrack::EVENT_MORE_DATA) {
1643 return;
1644 }
1645
1646 AudioOutput *me = (AudioOutput *)cookie;
1647 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1648
Andreas Huber6ed937e2010-02-09 16:59:18 -08001649 size_t actualSize = (*me->mCallback)(
Andreas Hubere46b7be2009-07-14 16:56:47 -07001650 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber6ed937e2010-02-09 16:59:18 -08001651
Andreas Huber406a18b2010-02-18 16:45:13 -08001652 buffer->size = actualSize;
1653
Andreas Huber6ed937e2010-02-09 16:59:18 -08001654 if (actualSize > 0) {
1655 me->snoopWrite(buffer->raw, actualSize);
1656 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001657}
1658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659#undef LOG_TAG
1660#define LOG_TAG "AudioCache"
1661MediaPlayerService::AudioCache::AudioCache(const char* name) :
1662 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1663 mError(NO_ERROR), mCommandComplete(false)
1664{
1665 // create ashmem heap
1666 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1667}
1668
1669uint32_t MediaPlayerService::AudioCache::latency () const
1670{
1671 return 0;
1672}
1673
1674float MediaPlayerService::AudioCache::msecsPerFrame() const
1675{
1676 return mMsecsPerFrame;
1677}
1678
Eric Laurent0986e792010-01-19 17:37:09 -08001679status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1680{
1681 if (position == 0) return BAD_VALUE;
1682 *position = mSize;
1683 return NO_ERROR;
1684}
1685
Andreas Huber6ed937e2010-02-09 16:59:18 -08001686////////////////////////////////////////////////////////////////////////////////
1687
1688struct CallbackThread : public Thread {
1689 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1690 MediaPlayerBase::AudioSink::AudioCallback cb,
1691 void *cookie);
1692
1693protected:
1694 virtual ~CallbackThread();
1695
1696 virtual bool threadLoop();
1697
1698private:
1699 wp<MediaPlayerBase::AudioSink> mSink;
1700 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1701 void *mCookie;
1702 void *mBuffer;
1703 size_t mBufferSize;
1704
1705 CallbackThread(const CallbackThread &);
1706 CallbackThread &operator=(const CallbackThread &);
1707};
1708
1709CallbackThread::CallbackThread(
1710 const wp<MediaPlayerBase::AudioSink> &sink,
1711 MediaPlayerBase::AudioSink::AudioCallback cb,
1712 void *cookie)
1713 : mSink(sink),
1714 mCallback(cb),
1715 mCookie(cookie),
1716 mBuffer(NULL),
1717 mBufferSize(0) {
1718}
1719
1720CallbackThread::~CallbackThread() {
1721 if (mBuffer) {
1722 free(mBuffer);
1723 mBuffer = NULL;
1724 }
1725}
1726
1727bool CallbackThread::threadLoop() {
1728 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1729 if (sink == NULL) {
1730 return false;
1731 }
1732
1733 if (mBuffer == NULL) {
1734 mBufferSize = sink->bufferSize();
1735 mBuffer = malloc(mBufferSize);
1736 }
1737
1738 size_t actualSize =
1739 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1740
1741 if (actualSize > 0) {
1742 sink->write(mBuffer, actualSize);
1743 }
1744
1745 return true;
1746}
1747
1748////////////////////////////////////////////////////////////////////////////////
1749
Andreas Hubere46b7be2009-07-14 16:56:47 -07001750status_t MediaPlayerService::AudioCache::open(
1751 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1752 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753{
Dave Sparks14f89402009-12-09 20:20:26 -08001754 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks14f89402009-12-09 20:20:26 -08001755 if (mHeap->getHeapID() < 0) {
1756 return NO_INIT;
1757 }
Andreas Hubere46b7be2009-07-14 16:56:47 -07001758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 mSampleRate = sampleRate;
1760 mChannelCount = (uint16_t)channelCount;
1761 mFormat = (uint16_t)format;
1762 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber6ed937e2010-02-09 16:59:18 -08001763
1764 if (cb != NULL) {
1765 mCallbackThread = new CallbackThread(this, cb, cookie);
1766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 return NO_ERROR;
1768}
1769
Andreas Huber6ed937e2010-02-09 16:59:18 -08001770void MediaPlayerService::AudioCache::start() {
1771 if (mCallbackThread != NULL) {
1772 mCallbackThread->run("AudioCache callback");
1773 }
1774}
1775
1776void MediaPlayerService::AudioCache::stop() {
1777 if (mCallbackThread != NULL) {
1778 mCallbackThread->requestExitAndWait();
1779 }
1780}
1781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1783{
1784 LOGV("write(%p, %u)", buffer, size);
1785 if ((buffer == 0) || (size == 0)) return size;
1786
1787 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1788 if (p == NULL) return NO_INIT;
1789 p += mSize;
1790 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1791 if (mSize + size > mHeap->getSize()) {
1792 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1793 size = mHeap->getSize() - mSize;
1794 }
1795 memcpy(p, buffer, size);
1796 mSize += size;
1797 return size;
1798}
1799
1800// call with lock held
1801status_t MediaPlayerService::AudioCache::wait()
1802{
1803 Mutex::Autolock lock(mLock);
Dave Sparks16433e22010-03-01 19:29:58 -08001804 while (!mCommandComplete) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 mSignal.wait(mLock);
1806 }
1807 mCommandComplete = false;
1808
1809 if (mError == NO_ERROR) {
1810 LOGV("wait - success");
1811 } else {
1812 LOGV("wait - error");
1813 }
1814 return mError;
1815}
1816
1817void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1818{
1819 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1820 AudioCache* p = static_cast<AudioCache*>(cookie);
1821
1822 // ignore buffering messages
Dave Sparks14f89402009-12-09 20:20:26 -08001823 switch (msg)
1824 {
1825 case MEDIA_ERROR:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 LOGE("Error %d, %d occurred", ext1, ext2);
1827 p->mError = ext1;
Dave Sparks14f89402009-12-09 20:20:26 -08001828 break;
1829 case MEDIA_PREPARED:
1830 LOGV("prepared");
1831 break;
1832 case MEDIA_PLAYBACK_COMPLETE:
1833 LOGV("playback complete");
1834 break;
1835 default:
1836 LOGV("ignored");
1837 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839
1840 // wake up thread
Dave Sparks6c26fe42010-03-02 12:56:37 -08001841 Mutex::Autolock lock(p->mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 p->mCommandComplete = true;
1843 p->mSignal.signal();
1844}
1845
nikobc726922009-07-20 15:07:26 -07001846} // namespace android