M7350v1_en_gpl

This commit is contained in:
T
2024-09-09 08:52:07 +00:00
commit f9cc65cfda
65988 changed files with 26357421 additions and 0 deletions
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ActivityManager_H
#define ActivityManager_H
#include <utils/String16.h>
namespace android {
// Perform a ContentProvider.openFile() call for the given URI.
//
// Returns the native file descriptor for the opened stream, < 0 on error.
extern int openContentProviderFile(const String16& uri);
}
#endif
@@ -0,0 +1,127 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
#ifndef _RUNTIME_ANDROID_RUNTIME_H
#define _RUNTIME_ANDROID_RUNTIME_H
#include <utils/Errors.h>
#include <binder/IBinder.h>
#include <utils/String8.h>
#include <utils/String16.h>
#include <utils/Vector.h>
#include <utils/threads.h>
#include <pthread.h>
#include <nativehelper/jni.h>
namespace android {
class AndroidRuntime
{
public:
AndroidRuntime();
virtual ~AndroidRuntime();
/**
* Register a set of methods in the specified class.
*/
static int registerNativeMethods(JNIEnv* env,
const char* className, const JNINativeMethod* gMethods, int numMethods);
/**
* Call a static Java function that takes no arguments and returns void.
*/
status_t callStatic(const char* className, const char* methodName);
/**
* Call a class's static main method with the given arguments,
*/
status_t callMain(const char* className, int argc, const char* const argv[]);
/**
* Find a class, with the input either of the form
* "package/class" or "package.class".
*/
static jclass findClass(JNIEnv* env, const char* className);
int addVmArguments(int argc, const char* const argv[]);
void start(const char *classname, const bool startSystemServer);
void start(); // start in android.util.RuntimeInit
static AndroidRuntime* getRuntime();
/**
* This gets called after the JavaVM has initialized. Override it
* with the system's native entry point.
*/
virtual void onStarted() = 0;
/**
* This gets called after the JavaVM has initialized after a Zygote
* fork. Override it to initialize threads, etc. Upon return, the
* correct static main will be invoked.
*/
virtual void onZygoteInit() {};
/**
* Called when the Java application exits. The default
* implementation calls exit(code).
*/
virtual void onExit(int code);
/** create a new thread that is visible from Java */
static android_thread_id_t createJavaThread(const char* name, void (*start)(void *),
void* arg);
/** return a pointer to the VM running in this process */
static JavaVM* getJavaVM() { return mJavaVM; }
/** return a pointer to the JNIEnv pointer for this thread */
static JNIEnv* getJNIEnv();
private:
static int startReg(JNIEnv* env);
void parseExtraOpts(char* extraOptsBuf);
int startVm(JavaVM** pJavaVM, JNIEnv** pEnv);
Vector<JavaVMOption> mOptions;
/* JNI JavaVM pointer */
static JavaVM* mJavaVM;
/*
* Thread creation helpers.
*/
static int javaCreateThreadEtc(
android_thread_func_t entryFunction,
void* userData,
const char* threadName,
int32_t threadPriority,
size_t threadStackSize,
android_thread_id_t* threadId);
static int javaThreadShell(void* args);
};
// Returns the Unix file descriptor for a ParcelFileDescriptor object
extern int getParcelFileDescriptorFD(JNIEnv* env, jobject object);
}
#endif
@@ -0,0 +1,153 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _ANDROID_APP_NATIVEACTIVITY_H
#define _ANDROID_APP_NATIVEACTIVITY_H
#include <ui/InputTransport.h>
#include <utils/Looper.h>
#include <android/native_activity.h>
#include "jni.h"
namespace android {
extern void android_NativeActivity_finish(
ANativeActivity* activity);
extern void android_NativeActivity_setWindowFormat(
ANativeActivity* activity, int32_t format);
extern void android_NativeActivity_setWindowFlags(
ANativeActivity* activity, int32_t values, int32_t mask);
extern void android_NativeActivity_showSoftInput(
ANativeActivity* activity, int32_t flags);
extern void android_NativeActivity_hideSoftInput(
ANativeActivity* activity, int32_t flags);
} // namespace android
/*
* NDK input queue API.
*
* Here is the event flow:
* 1. Event arrives in input consumer, and is returned by getEvent().
* 2. Application calls preDispatchEvent():
* a. Event is assigned a sequence ID and enqueued in mPreDispatchingKeys.
* b. Main thread picks up event, hands to input method.
* c. Input method eventually returns sequence # and whether it was handled.
* d. finishPreDispatch() is called to enqueue the information.
* e. next getEvent() call will:
* - finish any pre-dispatch events that the input method handled
* - return the next pre-dispatched event that the input method didn't handle.
* f. (A preDispatchEvent() call on this event will now return false).
* 3. Application calls finishEvent() with whether it was handled.
* - If handled is true, the event is finished.
* - If handled is false, the event is put on mUnhandledKeys, and:
* a. Main thread receives event from consumeUnhandledEvent().
* b. Java sends event through default key handler.
* c. event is finished.
*/
struct AInputQueue : public android::InputEventFactoryInterface {
public:
/* Creates a consumer associated with an input channel. */
explicit AInputQueue(const android::sp<android::InputChannel>& channel, int workWrite);
/* Destroys the consumer and releases its input channel. */
~AInputQueue();
void attachLooper(ALooper* looper, int ident, ALooper_callbackFunc callback, void* data);
void detachLooper();
int32_t hasEvents();
int32_t getEvent(AInputEvent** outEvent);
bool preDispatchEvent(AInputEvent* event);
void finishEvent(AInputEvent* event, bool handled);
// ----------------------------------------------------------
inline android::InputConsumer& getConsumer() { return mConsumer; }
void dispatchEvent(android::KeyEvent* event);
void finishPreDispatch(int seq, bool handled);
android::KeyEvent* consumeUnhandledEvent();
android::KeyEvent* consumePreDispatchingEvent(int* outSeq);
virtual android::KeyEvent* createKeyEvent();
virtual android::MotionEvent* createMotionEvent();
int mWorkWrite;
private:
void doUnhandledKey(android::KeyEvent* keyEvent);
bool preDispatchKey(android::KeyEvent* keyEvent);
void wakeupDispatch();
android::InputConsumer mConsumer;
android::sp<android::Looper> mLooper;
int mDispatchKeyRead;
int mDispatchKeyWrite;
struct in_flight_event {
android::InputEvent* event;
int seq;
bool doFinish;
};
struct finish_pre_dispatch {
int seq;
bool handled;
};
android::Mutex mLock;
int mSeq;
// Cache of previously allocated key events.
android::Vector<android::KeyEvent*> mAvailKeyEvents;
// Cache of previously allocated motion events.
android::Vector<android::MotionEvent*> mAvailMotionEvents;
// All input events that are actively being processed.
android::Vector<in_flight_event> mInFlightEvents;
// Key events that the app didn't handle, and are pending for
// delivery to the activity's default key handling.
android::Vector<android::KeyEvent*> mUnhandledKeys;
// Keys that arrived in the Java framework and need to be
// dispatched to the app.
android::Vector<android::KeyEvent*> mDispatchingKeys;
// Key events that are pending to be pre-dispatched to the IME.
android::Vector<in_flight_event> mPreDispatchingKeys;
// Event sequence numbers that we have finished pre-dispatching.
android::Vector<finish_pre_dispatch> mFinishPreDispatches;
};
#endif // _ANDROID_APP_NATIVEACTIVITY_H
@@ -0,0 +1,36 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _ANDROID_CONTENT_RES_CONFIGURATION_H
#define _ANDROID_CONTENT_RES_CONFIGURATION_H
#include <utils/ResourceTypes.h>
#include <android/configuration.h>
#include "jni.h"
struct AConfiguration : android::ResTable_config {
};
namespace android {
extern void android_Configuration_getFromJava(
JNIEnv* env, jobject clazz, struct AConfiguration* out);
} // namespace android
#endif // _ANDROID_CONTENT_RES_CONFIGURATION_H
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef android_util_AssetManager_H
#define android_util_AssetManager_H
#include <utils/AssetManager.h>
#include "jni.h"
namespace android {
extern AssetManager* assetManagerForJavaObject(JNIEnv* env, jobject assetMgr);
}
#endif
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _ANDROID_VIEW_SURFACE_H
#define _ANDROID_VIEW_SURFACE_H
#include <android/native_window.h>
#include "jni.h"
namespace android {
extern sp<ANativeWindow> android_Surface_getNativeWindow(
JNIEnv* env, jobject clazz);
} // namespace android
#endif // _ANDROID_VIEW_SURFACE_H
+103
View File
@@ -0,0 +1,103 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_BINDER_H
#define ANDROID_BINDER_H
#include <binder/IBinder.h>
// ---------------------------------------------------------------------------
namespace android {
class BBinder : public IBinder
{
public:
BBinder();
virtual const String16& getInterfaceDescriptor() const;
virtual bool isBinderAlive() const;
virtual status_t pingBinder();
virtual status_t dump(int fd, const Vector<String16>& args);
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
virtual status_t linkToDeath(const sp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0);
virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0,
wp<DeathRecipient>* outRecipient = NULL);
virtual void attachObject( const void* objectID,
void* object,
void* cleanupCookie,
object_cleanup_func func);
virtual void* findObject(const void* objectID) const;
virtual void detachObject(const void* objectID);
virtual BBinder* localBinder();
protected:
virtual ~BBinder();
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
private:
BBinder(const BBinder& o);
BBinder& operator=(const BBinder& o);
class Extras;
Extras* mExtras;
void* mReserved0;
};
// ---------------------------------------------------------------------------
class BpRefBase : public virtual RefBase
{
protected:
BpRefBase(const sp<IBinder>& o);
virtual ~BpRefBase();
virtual void onFirstRef();
virtual void onLastStrongRef(const void* id);
virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
inline IBinder* remote() { return mRemote; }
inline IBinder* remote() const { return mRemote; }
private:
BpRefBase(const BpRefBase& o);
BpRefBase& operator=(const BpRefBase& o);
IBinder* const mRemote;
RefBase::weakref_type* mRefs;
volatile int32_t mState;
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_BINDER_H
+60
View File
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_BINDER_SERVICE_H
#define ANDROID_BINDER_SERVICE_H
#include <stdint.h>
#include <utils/Errors.h>
#include <utils/String16.h>
#include <binder/IServiceManager.h>
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
// ---------------------------------------------------------------------------
namespace android {
template<typename SERVICE>
class BinderService
{
public:
static status_t publish() {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(String16(SERVICE::getServiceName()), new SERVICE());
}
static void publishAndJoinThreadPool() {
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm(defaultServiceManager());
sm->addService(String16(SERVICE::getServiceName()), new SERVICE());
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
static void instantiate() { publish(); }
static status_t shutdown() {
return NO_ERROR;
}
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_BINDER_SERVICE_H
+124
View File
@@ -0,0 +1,124 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_BPBINDER_H
#define ANDROID_BPBINDER_H
#include <binder/IBinder.h>
#include <utils/KeyedVector.h>
#include <utils/threads.h>
// ---------------------------------------------------------------------------
namespace android {
class BpBinder : public IBinder
{
public:
BpBinder(int32_t handle);
inline int32_t handle() const { return mHandle; }
virtual const String16& getInterfaceDescriptor() const;
virtual bool isBinderAlive() const;
virtual status_t pingBinder();
virtual status_t dump(int fd, const Vector<String16>& args);
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
virtual status_t linkToDeath(const sp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0);
virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0,
wp<DeathRecipient>* outRecipient = NULL);
virtual void attachObject( const void* objectID,
void* object,
void* cleanupCookie,
object_cleanup_func func);
virtual void* findObject(const void* objectID) const;
virtual void detachObject(const void* objectID);
virtual BpBinder* remoteBinder();
status_t setConstantData(const void* data, size_t size);
void sendObituary();
class ObjectManager
{
public:
ObjectManager();
~ObjectManager();
void attach( const void* objectID,
void* object,
void* cleanupCookie,
IBinder::object_cleanup_func func);
void* find(const void* objectID) const;
void detach(const void* objectID);
void kill();
private:
ObjectManager(const ObjectManager&);
ObjectManager& operator=(const ObjectManager&);
struct entry_t
{
void* object;
void* cleanupCookie;
IBinder::object_cleanup_func func;
};
KeyedVector<const void*, entry_t> mObjects;
};
protected:
virtual ~BpBinder();
virtual void onFirstRef();
virtual void onLastStrongRef(const void* id);
virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
private:
const int32_t mHandle;
struct Obituary {
wp<DeathRecipient> recipient;
void* cookie;
uint32_t flags;
};
void reportOneDeath(const Obituary& obit);
bool isDescriptorCached() const;
mutable Mutex mLock;
volatile int32_t mAlive;
volatile int32_t mObitsSent;
Vector<Obituary>* mObituaries;
ObjectManager mObjects;
Parcel* mConstantData;
mutable String16 mDescriptorCache;
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_BPBINDER_H
+159
View File
@@ -0,0 +1,159 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IBINDER_H
#define ANDROID_IBINDER_H
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/String16.h>
#include <utils/Vector.h>
#define B_PACK_CHARS(c1, c2, c3, c4) \
((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4))
// ---------------------------------------------------------------------------
namespace android {
class BBinder;
class BpBinder;
class IInterface;
class Parcel;
/**
* Base class and low-level protocol for a remotable object.
* You can derive from this class to create an object for which other
* processes can hold references to it. Communication between processes
* (method calls, property get and set) is down through a low-level
* protocol implemented on top of the transact() API.
*/
class IBinder : public virtual RefBase
{
public:
enum {
FIRST_CALL_TRANSACTION = 0x00000001,
LAST_CALL_TRANSACTION = 0x00ffffff,
PING_TRANSACTION = B_PACK_CHARS('_','P','N','G'),
DUMP_TRANSACTION = B_PACK_CHARS('_','D','M','P'),
INTERFACE_TRANSACTION = B_PACK_CHARS('_', 'N', 'T', 'F'),
// Corresponds to TF_ONE_WAY -- an asynchronous call.
FLAG_ONEWAY = 0x00000001
};
IBinder();
/**
* Check if this IBinder implements the interface named by
* @a descriptor. If it does, the base pointer to it is returned,
* which you can safely static_cast<> to the concrete C++ interface.
*/
virtual sp<IInterface> queryLocalInterface(const String16& descriptor);
/**
* Return the canonical name of the interface provided by this IBinder
* object.
*/
virtual const String16& getInterfaceDescriptor() const = 0;
virtual bool isBinderAlive() const = 0;
virtual status_t pingBinder() = 0;
virtual status_t dump(int fd, const Vector<String16>& args) = 0;
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0) = 0;
/**
* This method allows you to add data that is transported through
* IPC along with your IBinder pointer. When implementing a Binder
* object, override it to write your desired data in to @a outData.
* You can then call getConstantData() on your IBinder to retrieve
* that data, from any process. You MUST return the number of bytes
* written in to the parcel (including padding).
*/
class DeathRecipient : public virtual RefBase
{
public:
virtual void binderDied(const wp<IBinder>& who) = 0;
};
/**
* Register the @a recipient for a notification if this binder
* goes away. If this binder object unexpectedly goes away
* (typically because its hosting process has been killed),
* then DeathRecipient::binderDied() will be called with a referene
* to this.
*
* The @a cookie is optional -- if non-NULL, it should be a
* memory address that you own (that is, you know it is unique).
*
* @note You will only receive death notifications for remote binders,
* as local binders by definition can't die without you dying as well.
* Trying to use this function on a local binder will result in an
* INVALID_OPERATION code being returned and nothing happening.
*
* @note This link always holds a weak reference to its recipient.
*
* @note You will only receive a weak reference to the dead
* binder. You should not try to promote this to a strong reference.
* (Nor should you need to, as there is nothing useful you can
* directly do with it now that it has passed on.)
*/
virtual status_t linkToDeath(const sp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0) = 0;
/**
* Remove a previously registered death notification.
* The @a recipient will no longer be called if this object
* dies. The @a cookie is optional. If non-NULL, you can
* supply a NULL @a recipient, and the recipient previously
* added with that cookie will be unlinked.
*/
virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0,
wp<DeathRecipient>* outRecipient = NULL) = 0;
virtual bool checkSubclass(const void* subclassID) const;
typedef void (*object_cleanup_func)(const void* id, void* obj, void* cleanupCookie);
virtual void attachObject( const void* objectID,
void* object,
void* cleanupCookie,
object_cleanup_func func) = 0;
virtual void* findObject(const void* objectID) const = 0;
virtual void detachObject(const void* objectID) = 0;
virtual BBinder* localBinder();
virtual BpBinder* remoteBinder();
protected:
virtual ~IBinder();
private:
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_IBINDER_H
+150
View File
@@ -0,0 +1,150 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
#ifndef ANDROID_IINTERFACE_H
#define ANDROID_IINTERFACE_H
#include <binder/Binder.h>
namespace android {
// ----------------------------------------------------------------------
class IInterface : public virtual RefBase
{
public:
IInterface();
sp<IBinder> asBinder();
sp<const IBinder> asBinder() const;
protected:
virtual ~IInterface();
virtual IBinder* onAsBinder() = 0;
};
// ----------------------------------------------------------------------
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
// ----------------------------------------------------------------------
template<typename INTERFACE>
class BnInterface : public INTERFACE, public BBinder
{
public:
virtual sp<IInterface> queryLocalInterface(const String16& _descriptor);
virtual const String16& getInterfaceDescriptor() const;
protected:
virtual IBinder* onAsBinder();
};
// ----------------------------------------------------------------------
template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
BpInterface(const sp<IBinder>& remote);
protected:
virtual IBinder* onAsBinder();
};
// ----------------------------------------------------------------------
#define DECLARE_META_INTERFACE(INTERFACE) \
static const android::String16 descriptor; \
static android::sp<I##INTERFACE> asInterface( \
const android::sp<android::IBinder>& obj); \
virtual const android::String16& getInterfaceDescriptor() const; \
I##INTERFACE(); \
virtual ~I##INTERFACE(); \
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
const android::String16 I##INTERFACE::descriptor(NAME); \
const android::String16& \
I##INTERFACE::getInterfaceDescriptor() const { \
return I##INTERFACE::descriptor; \
} \
android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const android::sp<android::IBinder>& obj) \
{ \
android::sp<I##INTERFACE> intr; \
if (obj != NULL) { \
intr = static_cast<I##INTERFACE*>( \
obj->queryLocalInterface( \
I##INTERFACE::descriptor).get()); \
if (intr == NULL) { \
intr = new Bp##INTERFACE(obj); \
} \
} \
return intr; \
} \
I##INTERFACE::I##INTERFACE() { } \
I##INTERFACE::~I##INTERFACE() { } \
#define CHECK_INTERFACE(interface, data, reply) \
if (!data.checkInterface(this)) { return PERMISSION_DENIED; } \
// ----------------------------------------------------------------------
// No user-serviceable parts after this...
template<typename INTERFACE>
inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
const String16& _descriptor)
{
if (_descriptor == INTERFACE::descriptor) return this;
return NULL;
}
template<typename INTERFACE>
inline const String16& BnInterface<INTERFACE>::getInterfaceDescriptor() const
{
return INTERFACE::getInterfaceDescriptor();
}
template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
return this;
}
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpRefBase(remote)
{
}
template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder()
{
return remote();
}
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IINTERFACE_H
+101
View File
@@ -0,0 +1,101 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IMEMORY_H
#define ANDROID_IMEMORY_H
#include <stdint.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------------
class IMemoryHeap : public IInterface
{
public:
DECLARE_META_INTERFACE(MemoryHeap);
// flags returned by getFlags()
enum {
READ_ONLY = 0x00000001
};
virtual int getHeapID() const = 0;
virtual void* getBase() const = 0;
virtual size_t getSize() const = 0;
virtual uint32_t getFlags() const = 0;
// these are there just for backward source compatibility
int32_t heapID() const { return getHeapID(); }
void* base() const { return getBase(); }
size_t virtualSize() const { return getSize(); }
};
class BnMemoryHeap : public BnInterface<IMemoryHeap>
{
public:
virtual status_t onTransact(
uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
BnMemoryHeap();
protected:
virtual ~BnMemoryHeap();
};
// ----------------------------------------------------------------------------
class IMemory : public IInterface
{
public:
DECLARE_META_INTERFACE(Memory);
virtual sp<IMemoryHeap> getMemory(ssize_t* offset=0, size_t* size=0) const = 0;
// helpers
void* fastPointer(const sp<IBinder>& heap, ssize_t offset) const;
void* pointer() const;
size_t size() const;
ssize_t offset() const;
};
class BnMemory : public BnInterface<IMemory>
{
public:
virtual status_t onTransact(
uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
BnMemory();
protected:
virtual ~BnMemory();
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IMEMORY_H
+126
View File
@@ -0,0 +1,126 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IPC_THREAD_STATE_H
#define ANDROID_IPC_THREAD_STATE_H
#include <utils/Errors.h>
#include <binder/Parcel.h>
#include <binder/ProcessState.h>
#include <utils/Vector.h>
#ifdef HAVE_WIN32_PROC
typedef int uid_t;
#endif
// ---------------------------------------------------------------------------
namespace android {
class IPCThreadState
{
public:
static IPCThreadState* self();
sp<ProcessState> process();
status_t clearLastError();
int getCallingPid();
int getCallingUid();
void setStrictModePolicy(int32_t policy);
int32_t getStrictModePolicy() const;
void setLastTransactionBinderFlags(int32_t flags);
int32_t getLastTransactionBinderFlags() const;
int64_t clearCallingIdentity();
void restoreCallingIdentity(int64_t token);
void flushCommands();
void joinThreadPool(bool isMain = true);
// Stop the local process.
void stopProcess(bool immediate = true);
status_t transact(int32_t handle,
uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags);
void incStrongHandle(int32_t handle);
void decStrongHandle(int32_t handle);
void incWeakHandle(int32_t handle);
void decWeakHandle(int32_t handle);
status_t attemptIncStrongHandle(int32_t handle);
static void expungeHandle(int32_t handle, IBinder* binder);
status_t requestDeathNotification( int32_t handle,
BpBinder* proxy);
status_t clearDeathNotification( int32_t handle,
BpBinder* proxy);
static void shutdown();
// Call this to disable switching threads to background scheduling when
// receiving incoming IPC calls. This is specifically here for the
// Android system process, since it expects to have background apps calling
// in to it but doesn't want to acquire locks in its services while in
// the background.
static void disableBackgroundScheduling(bool disable);
private:
IPCThreadState();
~IPCThreadState();
status_t sendReply(const Parcel& reply, uint32_t flags);
status_t waitForResponse(Parcel *reply,
status_t *acquireResult=NULL);
status_t talkWithDriver(bool doReceive=true);
status_t writeTransactionData(int32_t cmd,
uint32_t binderFlags,
int32_t handle,
uint32_t code,
const Parcel& data,
status_t* statusBuffer);
status_t executeCommand(int32_t command);
void clearCaller();
static void threadDestructor(void *st);
static void freeBuffer(Parcel* parcel,
const uint8_t* data, size_t dataSize,
const size_t* objects, size_t objectsSize,
void* cookie);
const sp<ProcessState> mProcess;
const pid_t mMyThreadId;
Vector<BBinder*> mPendingStrongDerefs;
Vector<RefBase::weakref_type*> mPendingWeakDerefs;
Parcel mIn;
Parcel mOut;
status_t mLastError;
pid_t mCallingPid;
uid_t mCallingUid;
int32_t mStrictModePolicy;
int32_t mLastTransactionBinderFlags;
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_IPC_THREAD_STATE_H
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
#ifndef ANDROID_IPERMISSION_CONTROLLER_H
#define ANDROID_IPERMISSION_CONTROLLER_H
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------
class IPermissionController : public IInterface
{
public:
DECLARE_META_INTERFACE(PermissionController);
virtual bool checkPermission(const String16& permission,
int32_t pid, int32_t uid) = 0;
enum {
CHECK_PERMISSION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION
};
};
// ----------------------------------------------------------------------
class BnPermissionController : public BnInterface<IPermissionController>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IPERMISSION_CONTROLLER_H
+100
View File
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
#ifndef ANDROID_ISERVICE_MANAGER_H
#define ANDROID_ISERVICE_MANAGER_H
#include <binder/IInterface.h>
#include <binder/IPermissionController.h>
#include <utils/Vector.h>
#include <utils/String16.h>
namespace android {
// ----------------------------------------------------------------------
class IServiceManager : public IInterface
{
public:
DECLARE_META_INTERFACE(ServiceManager);
/**
* Retrieve an existing service, blocking for a few seconds
* if it doesn't yet exist.
*/
virtual sp<IBinder> getService( const String16& name) const = 0;
/**
* Retrieve an existing service, non-blocking.
*/
virtual sp<IBinder> checkService( const String16& name) const = 0;
/**
* Register a service.
*/
virtual status_t addService( const String16& name,
const sp<IBinder>& service) = 0;
/**
* Return list of all existing services.
*/
virtual Vector<String16> listServices() = 0;
enum {
GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
CHECK_SERVICE_TRANSACTION,
ADD_SERVICE_TRANSACTION,
LIST_SERVICES_TRANSACTION,
};
};
sp<IServiceManager> defaultServiceManager();
template<typename INTERFACE>
status_t getService(const String16& name, sp<INTERFACE>* outService)
{
const sp<IServiceManager> sm = defaultServiceManager();
if (sm != NULL) {
*outService = interface_cast<INTERFACE>(sm->getService(name));
if ((*outService) != NULL) return NO_ERROR;
}
return NAME_NOT_FOUND;
}
bool checkCallingPermission(const String16& permission);
bool checkCallingPermission(const String16& permission,
int32_t* outPid, int32_t* outUid);
bool checkPermission(const String16& permission, pid_t pid, uid_t uid);
// ----------------------------------------------------------------------
class BnServiceManager : public BnInterface<IServiceManager>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_ISERVICE_MANAGER_H
+51
View File
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_BASE_H
#define ANDROID_MEMORY_BASE_H
#include <stdlib.h>
#include <stdint.h>
#include <binder/IMemory.h>
namespace android {
// ---------------------------------------------------------------------------
class MemoryBase : public BnMemory
{
public:
MemoryBase(const sp<IMemoryHeap>& heap, ssize_t offset, size_t size);
virtual ~MemoryBase();
virtual sp<IMemoryHeap> getMemory(ssize_t* offset, size_t* size) const;
protected:
size_t getSize() const { return mSize; }
ssize_t getOffset() const { return mOffset; }
const sp<IMemoryHeap>& getHeap() const { return mHeap; }
private:
size_t mSize;
ssize_t mOffset;
sp<IMemoryHeap> mHeap;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_BASE_H
+60
View File
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_DEALER_H
#define ANDROID_MEMORY_DEALER_H
#include <stdint.h>
#include <sys/types.h>
#include <binder/IMemory.h>
#include <binder/MemoryHeapBase.h>
namespace android {
// ----------------------------------------------------------------------------
class SimpleBestFitAllocator;
// ----------------------------------------------------------------------------
class MemoryDealer : public RefBase
{
public:
MemoryDealer(size_t size, const char* name = 0);
virtual sp<IMemory> allocate(size_t size);
virtual void deallocate(size_t offset);
virtual void dump(const char* what) const;
sp<IMemoryHeap> getMemoryHeap() const { return heap(); }
protected:
virtual ~MemoryDealer();
private:
const sp<IMemoryHeap>& heap() const;
SimpleBestFitAllocator* allocator() const;
sp<IMemoryHeap> mHeap;
SimpleBestFitAllocator* mAllocator;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_DEALER_H
+99
View File
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_HEAP_BASE_H
#define ANDROID_MEMORY_HEAP_BASE_H
#include <stdlib.h>
#include <stdint.h>
#include <binder/IMemory.h>
namespace android {
// ---------------------------------------------------------------------------
class MemoryHeapBase : public virtual BnMemoryHeap
{
public:
enum {
READ_ONLY = IMemoryHeap::READ_ONLY,
// memory won't be mapped locally, but will be mapped in the remote
// process.
DONT_MAP_LOCALLY = 0x00000100,
NO_CACHING = 0x00000200,
MAP_LOCKED_MAP_POPULATE = 0x00000400,
};
/*
* maps the memory referenced by fd. but DOESN'T take ownership
* of the filedescriptor (it makes a copy with dup()
*/
MemoryHeapBase(int fd, size_t size, uint32_t flags = 0, uint32_t offset = 0);
/*
* maps memory from the given device
*/
MemoryHeapBase(const char* device, size_t size = 0, uint32_t flags = 0);
/*
* maps memory from ashmem, with the given name for debugging
*/
MemoryHeapBase(size_t size, uint32_t flags = 0, char const* name = NULL);
virtual ~MemoryHeapBase();
/* implement IMemoryHeap interface */
virtual int getHeapID() const;
virtual void* getBase() const;
virtual size_t getSize() const;
virtual uint32_t getFlags() const;
const char* getDevice() const;
/* this closes this heap -- use carefully */
void dispose();
/* this is only needed as a workaround, use only if you know
* what you are doing */
status_t setDevice(const char* device) {
if (mDevice == 0)
mDevice = device;
return mDevice ? NO_ERROR : ALREADY_EXISTS;
}
protected:
MemoryHeapBase();
// init() takes ownership of fd
status_t init(int fd, void *base, int size,
int flags = 0, const char* device = NULL);
private:
status_t mapfd(int fd, size_t size, uint32_t offset = 0);
int mFD;
size_t mSize;
void* mBase;
uint32_t mFlags;
const char* mDevice;
bool mNeedUnmap;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_HEAP_BASE_H
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_HEAP_ION_H
#define ANDROID_MEMORY_HEAP_ION_H
#include <stdlib.h>
#include <stdint.h>
#include <binder/MemoryHeapBase.h>
#include <binder/IMemory.h>
#include <utils/SortedVector.h>
#include <utils/threads.h>
#include <linux/ion.h>
namespace android {
class MemoryHeapBase;
// ---------------------------------------------------------------------------
class MemoryHeapIon : public MemoryHeapBase
{
public:
MemoryHeapIon(const char*, size_t, uint32_t, long unsigned int);
MemoryHeapIon();
~MemoryHeapIon();
status_t mapIonFd(int fd, size_t size, unsigned long memory_type, int flags);
status_t ionInit(int ionFd, void *base, int size, int flags,
const char* device, struct ion_handle *handle,
int ionMapFd);
private:
int mIonDeviceFd; /*fd we get from open("/dev/ion")*/
struct ion_handle *mIonHandle; /*handle we get from ION_IOC_ALLOC*/ };
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_HEAP_ION_H
+79
View File
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_HEAP_PMEM_H
#define ANDROID_MEMORY_HEAP_PMEM_H
#include <stdlib.h>
#include <stdint.h>
#include <binder/MemoryHeapBase.h>
#include <binder/IMemory.h>
#include <utils/SortedVector.h>
#include <utils/threads.h>
namespace android {
class MemoryHeapBase;
// ---------------------------------------------------------------------------
class MemoryHeapPmem : public MemoryHeapBase
{
public:
class MemoryPmem : public BnMemory {
public:
MemoryPmem(const sp<MemoryHeapPmem>& heap);
~MemoryPmem();
protected:
const sp<MemoryHeapPmem>& getHeap() const { return mClientHeap; }
private:
friend class MemoryHeapPmem;
virtual void revoke() = 0;
sp<MemoryHeapPmem> mClientHeap;
};
MemoryHeapPmem(const sp<MemoryHeapBase>& pmemHeap, uint32_t flags = 0);
~MemoryHeapPmem();
/* HeapInterface additions */
virtual sp<IMemory> mapMemory(size_t offset, size_t size);
/* make the whole heap visible (you know who you are) */
virtual status_t slap();
/* hide (revoke) the whole heap (the client will see the garbage page) */
virtual status_t unslap();
/* revoke all allocations made by this heap */
virtual void revoke();
private:
/* use this to create your own IMemory for mapMemory */
virtual sp<MemoryPmem> createMemory(size_t offset, size_t size);
void remove(const wp<MemoryPmem>& memory);
private:
sp<MemoryHeapBase> mParentHeap;
mutable Mutex mLock;
SortedVector< wp<MemoryPmem> > mAllocations;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_HEAP_PMEM_H
+248
View File
@@ -0,0 +1,248 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_PARCEL_H
#define ANDROID_PARCEL_H
#include <cutils/native_handle.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/String16.h>
#include <utils/Vector.h>
// ---------------------------------------------------------------------------
namespace android {
class Flattenable;
class IBinder;
class IPCThreadState;
class ProcessState;
class String8;
class TextOutput;
struct flat_binder_object; // defined in support_p/binder_module.h
class Parcel
{
public:
Parcel();
~Parcel();
const uint8_t* data() const;
size_t dataSize() const;
size_t dataAvail() const;
size_t dataPosition() const;
size_t dataCapacity() const;
status_t setDataSize(size_t size);
void setDataPosition(size_t pos) const;
status_t setDataCapacity(size_t size);
status_t setData(const uint8_t* buffer, size_t len);
status_t appendFrom(Parcel *parcel, size_t start, size_t len);
bool hasFileDescriptors() const;
// Writes the RPC header.
status_t writeInterfaceToken(const String16& interface);
// Parses the RPC header, returning true if the interface name
// in the header matches the expected interface from the caller.
//
// Additionally, enforceInterface does part of the work of
// propagating the StrictMode policy mask, populating the current
// IPCThreadState, which as an optimization may optionally be
// passed in.
bool enforceInterface(const String16& interface,
IPCThreadState* threadState = NULL) const;
bool checkInterface(IBinder*) const;
void freeData();
const size_t* objects() const;
size_t objectsCount() const;
status_t errorCheck() const;
void setError(status_t err);
status_t write(const void* data, size_t len);
void* writeInplace(size_t len);
status_t writeUnpadded(const void* data, size_t len);
status_t writeInt32(int32_t val);
status_t writeInt64(int64_t val);
status_t writeFloat(float val);
status_t writeDouble(double val);
status_t writeIntPtr(intptr_t val);
status_t writeCString(const char* str);
status_t writeString8(const String8& str);
status_t writeString16(const String16& str);
status_t writeString16(const char16_t* str, size_t len);
status_t writeStrongBinder(const sp<IBinder>& val);
status_t writeWeakBinder(const wp<IBinder>& val);
status_t write(const Flattenable& val);
// Place a native_handle into the parcel (the native_handle's file-
// descriptors are dup'ed, so it is safe to delete the native_handle
// when this function returns).
// Doesn't take ownership of the native_handle.
status_t writeNativeHandle(const native_handle* handle);
// Place a file descriptor into the parcel. The given fd must remain
// valid for the lifetime of the parcel.
status_t writeFileDescriptor(int fd);
// Place a file descriptor into the parcel. A dup of the fd is made, which
// will be closed once the parcel is destroyed.
status_t writeDupFileDescriptor(int fd);
status_t writeObject(const flat_binder_object& val, bool nullMetaData);
// Like Parcel.java's writeNoException(). Just writes a zero int32.
// Currently the native implementation doesn't do any of the StrictMode
// stack gathering and serialization that the Java implementation does.
status_t writeNoException();
void remove(size_t start, size_t amt);
status_t read(void* outData, size_t len) const;
const void* readInplace(size_t len) const;
int32_t readInt32() const;
status_t readInt32(int32_t *pArg) const;
int64_t readInt64() const;
status_t readInt64(int64_t *pArg) const;
float readFloat() const;
status_t readFloat(float *pArg) const;
double readDouble() const;
status_t readDouble(double *pArg) const;
intptr_t readIntPtr() const;
status_t readIntPtr(intptr_t *pArg) const;
const char* readCString() const;
String8 readString8() const;
String16 readString16() const;
const char16_t* readString16Inplace(size_t* outLen) const;
sp<IBinder> readStrongBinder() const;
wp<IBinder> readWeakBinder() const;
status_t read(Flattenable& val) const;
// Like Parcel.java's readExceptionCode(). Reads the first int32
// off of a Parcel's header, returning 0 or the negative error
// code on exceptions, but also deals with skipping over rich
// response headers. Callers should use this to read & parse the
// response headers rather than doing it by hand.
int32_t readExceptionCode() const;
// Retrieve native_handle from the parcel. This returns a copy of the
// parcel's native_handle (the caller takes ownership). The caller
// must free the native_handle with native_handle_close() and
// native_handle_delete().
native_handle* readNativeHandle() const;
// Retrieve a file descriptor from the parcel. This returns the raw fd
// in the parcel, which you do not own -- use dup() to get your own copy.
int readFileDescriptor() const;
const flat_binder_object* readObject(bool nullMetaData) const;
// Explicitly close all file descriptors in the parcel.
void closeFileDescriptors();
typedef void (*release_func)(Parcel* parcel,
const uint8_t* data, size_t dataSize,
const size_t* objects, size_t objectsSize,
void* cookie);
const uint8_t* ipcData() const;
size_t ipcDataSize() const;
const size_t* ipcObjects() const;
size_t ipcObjectsCount() const;
void ipcSetDataReference(const uint8_t* data, size_t dataSize,
const size_t* objects, size_t objectsCount,
release_func relFunc, void* relCookie);
void print(TextOutput& to, uint32_t flags = 0) const;
private:
Parcel(const Parcel& o);
Parcel& operator=(const Parcel& o);
status_t finishWrite(size_t len);
void releaseObjects();
void acquireObjects();
status_t growData(size_t len);
status_t restartWrite(size_t desired);
status_t continueWrite(size_t desired);
void freeDataNoInit();
void initState();
void scanForFds() const;
template<class T>
status_t readAligned(T *pArg) const;
template<class T> T readAligned() const;
template<class T>
status_t writeAligned(T val);
status_t mError;
uint8_t* mData;
size_t mDataSize;
size_t mDataCapacity;
mutable size_t mDataPos;
size_t* mObjects;
size_t mObjectsSize;
size_t mObjectsCapacity;
mutable size_t mNextObjectHint;
mutable bool mFdsKnown;
mutable bool mHasFds;
release_func mOwner;
void* mOwnerCookie;
};
// ---------------------------------------------------------------------------
inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
{
parcel.print(to);
return to;
}
// ---------------------------------------------------------------------------
// Generic acquire and release of objects.
void acquire_object(const sp<ProcessState>& proc,
const flat_binder_object& obj, const void* who);
void release_object(const sp<ProcessState>& proc,
const flat_binder_object& obj, const void* who);
void flatten_binder(const sp<ProcessState>& proc,
const sp<IBinder>& binder, flat_binder_object* out);
void flatten_binder(const sp<ProcessState>& proc,
const wp<IBinder>& binder, flat_binder_object* out);
status_t unflatten_binder(const sp<ProcessState>& proc,
const flat_binder_object& flat, sp<IBinder>* out);
status_t unflatten_binder(const sp<ProcessState>& proc,
const flat_binder_object& flat, wp<IBinder>* out);
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_PARCEL_H
+68
View File
@@ -0,0 +1,68 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BINDER_PERMISSION_H
#define BINDER_PERMISSION_H
#include <stdint.h>
#include <unistd.h>
#include <utils/SortedVector.h>
#include <utils/String16.h>
#include <utils/threads.h>
namespace android {
// ---------------------------------------------------------------------------
/*
* Permission caches the result of the permission check for the given
* permission name and the provided uid/pid. It also handles a few
* known cases efficiently (caller is in the same process or is root).
* The package manager does something similar but lives in dalvik world
* and is therefore extremely slow to access.
*/
class Permission
{
public:
Permission(char const* name);
Permission(const String16& name);
Permission(const Permission& rhs);
virtual ~Permission();
bool operator < (const Permission& rhs) const;
// checks the current binder call's caller has access to this permission
bool checkCalling() const;
// checks the specified pid/uid has access to this permission
bool check(pid_t pid, uid_t uid) const;
protected:
virtual bool doCheckPermission(pid_t pid, uid_t uid) const;
private:
Permission& operator = (const Permission& rhs) const;
const String16 mPermissionName;
mutable SortedVector<uid_t> mGranted;
const pid_t mPid;
mutable Mutex mLock;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif /* BINDER_PERMISSION_H */
+117
View File
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_PROCESS_STATE_H
#define ANDROID_PROCESS_STATE_H
#include <binder/IBinder.h>
#include <utils/KeyedVector.h>
#include <utils/String8.h>
#include <utils/String16.h>
#include <utils/threads.h>
// ---------------------------------------------------------------------------
namespace android {
// Global variables
extern int mArgC;
extern const char* const* mArgV;
extern int mArgLen;
class IPCThreadState;
class ProcessState : public virtual RefBase
{
public:
static sp<ProcessState> self();
static void setSingleProcess(bool singleProcess);
void setContextObject(const sp<IBinder>& object);
sp<IBinder> getContextObject(const sp<IBinder>& caller);
void setContextObject(const sp<IBinder>& object,
const String16& name);
sp<IBinder> getContextObject(const String16& name,
const sp<IBinder>& caller);
bool supportsProcesses() const;
void startThreadPool();
typedef bool (*context_check_func)(const String16& name,
const sp<IBinder>& caller,
void* userData);
bool isContextManager(void) const;
bool becomeContextManager(
context_check_func checkFunc,
void* userData);
sp<IBinder> getStrongProxyForHandle(int32_t handle);
wp<IBinder> getWeakProxyForHandle(int32_t handle);
void expungeHandle(int32_t handle, IBinder* binder);
void setArgs(int argc, const char* const argv[]);
int getArgC() const;
const char* const* getArgV() const;
void setArgV0(const char* txt);
void spawnPooledThread(bool isMain);
private:
friend class IPCThreadState;
ProcessState();
~ProcessState();
ProcessState(const ProcessState& o);
ProcessState& operator=(const ProcessState& o);
struct handle_entry {
IBinder* binder;
RefBase::weakref_type* refs;
};
handle_entry* lookupHandleLocked(int32_t handle);
int mDriverFD;
void* mVMStart;
mutable Mutex mLock; // protects everything below.
Vector<handle_entry>mHandleToObject;
bool mManagesContexts;
context_check_func mBinderContextCheckFunc;
void* mBinderContextUserData;
KeyedVector<String16, sp<IBinder> >
mContexts;
String8 mRootDir;
bool mThreadPoolStarted;
volatile int32_t mThreadPoolSeq;
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_PROCESS_STATE_H
+281
View File
@@ -0,0 +1,281 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_CAMERA_H
#define ANDROID_HARDWARE_CAMERA_H
#include <utils/Timers.h>
#include <camera/ICameraClient.h>
namespace android {
class ISurface;
/*
* A set of bit masks for specifying how the received preview frames are
* handled before the previewCallback() call.
*
* The least significant 3 bits of an "int" value are used for this purpose:
*
* ..... 0 0 0
* ^ ^ ^
* | | |---------> determine whether the callback is enabled or not
* | |-----------> determine whether the callback is one-shot or not
* |-------------> determine whether the frame is copied out or not
*
* WARNING:
* When a frame is sent directly without copying, it is the frame receiver's
* responsiblity to make sure that the frame data won't get corrupted by
* subsequent preview frames filled by the camera. This flag is recommended
* only when copying out data brings significant performance price and the
* handling/processing of the received frame data is always faster than
* the preview frame rate so that data corruption won't occur.
*
* For instance,
* 1. 0x00 disables the callback. In this case, copy out and one shot bits
* are ignored.
* 2. 0x01 enables a callback without copying out the received frames. A
* typical use case is the Camcorder application to avoid making costly
* frame copies.
* 3. 0x05 is enabling a callback with frame copied out repeatedly. A typical
* use case is the Camera application.
* 4. 0x07 is enabling a callback with frame copied out only once. A typical use
* case is the Barcode scanner application.
*/
#define FRAME_CALLBACK_FLAG_ENABLE_MASK 0x01
#define FRAME_CALLBACK_FLAG_ONE_SHOT_MASK 0x02
#define FRAME_CALLBACK_FLAG_COPY_OUT_MASK 0x04
// Typical use cases
#define FRAME_CALLBACK_FLAG_NOOP 0x00
#define FRAME_CALLBACK_FLAG_CAMCORDER 0x01
#define FRAME_CALLBACK_FLAG_CAMERA 0x05
#define FRAME_CALLBACK_FLAG_BARCODE_SCANNER 0x07
// msgType in notifyCallback and dataCallback functions
enum {
CAMERA_MSG_ERROR = 0x001,
CAMERA_MSG_SHUTTER = 0x002,
CAMERA_MSG_FOCUS = 0x004,
CAMERA_MSG_ZOOM = 0x008,
CAMERA_MSG_PREVIEW_FRAME = 0x010,
CAMERA_MSG_VIDEO_FRAME = 0x020,
CAMERA_MSG_POSTVIEW_FRAME = 0x040,
CAMERA_MSG_RAW_IMAGE = 0x080,
CAMERA_MSG_COMPRESSED_IMAGE = 0x100,
CAMERA_MSG_STATS_DATA = 0x200,
CAMERA_MSG_META_DATA = 0x400,
CAMERA_MSG_ALL_MSGS = 0x7FF
};
// cmdType in sendCommand functions
enum {
CAMERA_CMD_START_SMOOTH_ZOOM = 1,
CAMERA_CMD_STOP_SMOOTH_ZOOM = 2,
// Set the clockwise rotation of preview display (setPreviewDisplay) in
// degrees. This affects the preview frames and the picture displayed after
// snapshot. This method is useful for portrait mode applications. Note that
// preview display of front-facing cameras is flipped horizontally before
// the rotation, that is, the image is reflected along the central vertical
// axis of the camera sensor. So the users can see themselves as looking
// into a mirror.
//
// This does not affect the order of byte array of CAMERA_MSG_PREVIEW_FRAME,
// CAMERA_MSG_VIDEO_FRAME, CAMERA_MSG_POSTVIEW_FRAME, CAMERA_MSG_RAW_IMAGE,
// or CAMERA_MSG_COMPRESSED_IMAGE. This is not allowed to be set during
// preview.
CAMERA_CMD_SET_DISPLAY_ORIENTATION = 3,
CAMERA_CMD_HISTOGRAM_ON = 4,
CAMERA_CMD_HISTOGRAM_OFF = 5,
CAMERA_CMD_HISTOGRAM_SEND_DATA = 6,
CAMERA_CMD_FACE_DETECTION_ON = 7,
CAMERA_CMD_FACE_DETECTION_OFF = 8,
CAMERA_CMD_SEND_META_DATA = 9,
};
// camera fatal errors
enum {
CAMERA_ERROR_UKNOWN = 1,
CAMERA_ERROR_RESOURCE = 2,
CAMERA_ERROR_SERVER_DIED = 100
};
enum {
CAMERA_FACING_BACK = 0, /* The facing of the camera is opposite to that of the screen. */
CAMERA_FACING_FRONT = 1 /* The facing of the camera is the same as that of the screen. */
};
enum {
CAMERA_SUPPORT_MODE_2D = 0x01, /* Camera Sensor supports 2D mode. */
CAMERA_SUPPORT_MODE_3D = 0x02, /* Camera Sensor supports 3D mode. */
CAMERA_SUPPORT_MODE_NONZSL = 0x04, /* Camera Sensor in NON-ZSL mode. */
CAMERA_SUPPORT_MODE_ZSL = 0x08 /* Camera Sensor supports ZSL mode. */
};
struct CameraInfo {
/**
* The direction that the camera faces to. It should be
* CAMERA_FACING_BACK or CAMERA_FACING_FRONT.
*/
int facing;
int mode;
/**
* The orientation of the camera image. The value is the angle that the
* camera image needs to be rotated clockwise so it shows correctly on
* the display in its natural orientation. It should be 0, 90, 180, or 270.
*
* For example, suppose a device has a naturally tall screen. The
* back-facing camera sensor is mounted in landscape. You are looking at
* the screen. If the top side of the camera sensor is aligned with the
* right edge of the screen in natural orientation, the value should be
* 90. If the top side of a front-facing camera sensor is aligned with
* the right of the screen, the value should be 270.
*/
int orientation;
};
class ICameraService;
class ICamera;
class Surface;
class Mutex;
class String8;
// ref-counted object for callbacks
class CameraListener: virtual public RefBase
{
public:
virtual void notify(int32_t msgType, int32_t ext1, int32_t ext2) = 0;
virtual void postData(int32_t msgType, const sp<IMemory>& dataPtr) = 0;
virtual void postDataTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr) = 0;
};
class Camera : public BnCameraClient, public IBinder::DeathRecipient
{
public:
// construct a camera client from an existing remote
static sp<Camera> create(const sp<ICamera>& camera);
static int32_t getNumberOfCameras();
static status_t getCameraInfo(int cameraId,
struct CameraInfo* cameraInfo);
static sp<Camera> connect(int cameraId, int mode=CAMERA_SUPPORT_MODE_2D);
~Camera();
void init();
status_t reconnect();
void disconnect();
status_t lock();
status_t unlock();
status_t getStatus() { return mStatus; }
// pass the buffered ISurface to the camera service
status_t setPreviewDisplay(const sp<Surface>& surface);
status_t setPreviewDisplay(const sp<ISurface>& surface);
// query the recording buffer information from HAL layer.
status_t getBufferInfo(sp<IMemory>& Frame, size_t *alignedSize);
//encode the YUV data
void encodeData();
// start preview mode, must call setPreviewDisplay first
status_t startPreview();
// stop preview mode
void stopPreview();
// get preview state
bool previewEnabled();
// start recording mode, must call setPreviewDisplay first
status_t startRecording();
// stop recording mode
void stopRecording();
// get recording state
bool recordingEnabled();
// release a recording frame
void releaseRecordingFrame(const sp<IMemory>& mem);
// autoFocus - status returned from callback
status_t autoFocus();
// cancel auto focus
status_t cancelAutoFocus();
// take a picture - picture returned from callback
status_t takePicture();
// set preview/capture parameters - key/value pairs
status_t setParameters(const String8& params);
// get preview/capture parameters - key/value pairs
String8 getParameters() const;
// send command to camera driver
status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2);
void setListener(const sp<CameraListener>& listener);
void setPreviewCallbackFlags(int preview_callback_flag);
// ICameraClient interface
virtual void notifyCallback(int32_t msgType, int32_t ext, int32_t ext2);
virtual void dataCallback(int32_t msgType, const sp<IMemory>& dataPtr);
virtual void dataCallbackTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr);
sp<ICamera> remote();
// start Livesnapshot, must be in recording mode
status_t takeLiveSnapshot();
private:
Camera();
Camera(const Camera&);
Camera& operator=(const Camera);
virtual void binderDied(const wp<IBinder>& who);
class DeathNotifier: public IBinder::DeathRecipient
{
public:
DeathNotifier() {
}
virtual void binderDied(const wp<IBinder>& who);
};
static sp<DeathNotifier> mDeathNotifier;
// helper function to obtain camera service handle
static const sp<ICameraService>& getCameraService();
sp<ICamera> mCamera;
status_t mStatus;
sp<CameraListener> mListener;
friend class DeathNotifier;
static Mutex mLock;
static sp<ICameraService> mCameraService;
};
}; // namespace android
#endif
@@ -0,0 +1,251 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_CAMERA_HARDWARE_INTERFACE_H
#define ANDROID_HARDWARE_CAMERA_HARDWARE_INTERFACE_H
#include <binder/IMemory.h>
#include <utils/RefBase.h>
#include <surfaceflinger/ISurface.h>
#include <camera/Camera.h>
#include <camera/CameraParameters.h>
namespace android {
class Overlay;
/**
* The size of image for display.
*/
typedef struct image_rect_struct
{
uint32_t width; /* Image width */
uint32_t height; /* Image height */
} image_rect_type;
typedef void (*notify_callback)(int32_t msgType,
int32_t ext1,
int32_t ext2,
void* user);
typedef void (*data_callback)(int32_t msgType,
const sp<IMemory>& dataPtr,
void* user);
typedef void (*data_callback_timestamp)(nsecs_t timestamp,
int32_t msgType,
const sp<IMemory>& dataPtr,
void* user);
/**
* CameraHardwareInterface.h defines the interface to the
* camera hardware abstraction layer, used for setting and getting
* parameters, live previewing, and taking pictures.
*
* It is a referenced counted interface with RefBase as its base class.
* CameraService calls openCameraHardware() to retrieve a strong pointer to the
* instance of this interface and may be called multiple times. The
* following steps describe a typical sequence:
*
* -# After CameraService calls openCameraHardware(), getParameters() and
* setParameters() are used to initialize the camera instance.
* CameraService calls getPreviewHeap() to establish access to the
* preview heap so it can be registered with SurfaceFlinger for
* efficient display updating while in preview mode.
* -# startPreview() is called. The camera instance then periodically
* sends the message CAMERA_MSG_PREVIEW_FRAME (if enabled) each time
* a new preview frame is available. If data callback code needs to use
* this memory after returning, it must copy the data.
*
* Prior to taking a picture, CameraService calls autofocus(). When auto
* focusing has completed, the camera instance sends a CAMERA_MSG_FOCUS notification,
* which informs the application whether focusing was successful. The camera instance
* only sends this message once and it is up to the application to call autoFocus()
* again if refocusing is desired.
*
* CameraService calls takePicture() to request the camera instance take a
* picture. At this point, if a shutter, postview, raw, and/or compressed callback
* is desired, the corresponding message must be enabled. As with CAMERA_MSG_PREVIEW_FRAME,
* any memory provided in a data callback must be copied if it's needed after returning.
*/
class CameraHardwareInterface : public virtual RefBase {
public:
virtual ~CameraHardwareInterface() { }
/** Return the IMemoryHeap for the preview image heap */
virtual sp<IMemoryHeap> getPreviewHeap() const = 0;
/** Return the IMemoryHeap for the raw image heap */
virtual sp<IMemoryHeap> getRawHeap() const = 0;
/** Set the notification and data callbacks */
virtual void setCallbacks(notify_callback notify_cb,
data_callback data_cb,
data_callback_timestamp data_cb_timestamp,
void* user) = 0;
/**
* The following three functions all take a msgtype,
* which is a bitmask of the messages defined in
* include/ui/Camera.h
*/
/**
* Enable a message, or set of messages.
*/
virtual void enableMsgType(int32_t msgType) = 0;
/**
* Disable a message, or a set of messages.
*/
virtual void disableMsgType(int32_t msgType) = 0;
/**
* Query whether a message, or a set of messages, is enabled.
* Note that this is operates as an AND, if any of the messages
* queried are off, this will return false.
*/
virtual bool msgTypeEnabled(int32_t msgType) = 0;
/**
* Start preview mode.
*/
virtual status_t startPreview() = 0;
/**
* Query the recording buffer information from HAL.
* This is needed because the opencore expects the buffer
* information before starting the recording.
*/
virtual status_t getBufferInfo(sp<IMemory>& Frame, size_t *alignedSize) = 0;
/**
* Encode the YUV data.
*/
virtual void encodeData() = 0;
/**
* Only used if overlays are used for camera preview.
*/
virtual bool useOverlay() {return false;}
virtual status_t setOverlay(const sp<Overlay> &overlay) {return BAD_VALUE;}
/**
* Stop a previously started preview.
*/
virtual void stopPreview() = 0;
/**
* Returns true if preview is enabled.
*/
virtual bool previewEnabled() = 0;
/**
* Start record mode. When a record image is available a CAMERA_MSG_VIDEO_FRAME
* message is sent with the corresponding frame. Every record frame must be released
* by calling releaseRecordingFrame().
*/
virtual status_t startRecording() = 0;
/**
* Stop a previously started recording.
*/
virtual void stopRecording() = 0;
/**
* Returns true if recording is enabled.
*/
virtual bool recordingEnabled() = 0;
/**
* Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
*/
virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0;
/**
* Start auto focus, the notification callback routine is called
* with CAMERA_MSG_FOCUS once when focusing is complete. autoFocus()
* will be called again if another auto focus is needed.
*/
virtual status_t autoFocus() = 0;
/**
* Cancels auto-focus function. If the auto-focus is still in progress,
* this function will cancel it. Whether the auto-focus is in progress
* or not, this function will return the focus position to the default.
* If the camera does not support auto-focus, this is a no-op.
*/
virtual status_t cancelAutoFocus() = 0;
/**
* Take a picture.
*/
virtual status_t takePicture() = 0;
/**
* Cancel a picture that was started with takePicture. Calling this
* method when no picture is being taken is a no-op.
*/
virtual status_t cancelPicture() = 0;
/**
* Set the camera parameters. This returns BAD_VALUE if any parameter is
* invalid or not supported. */
virtual status_t setParameters(const CameraParameters& params) = 0;
/** Return the camera parameters. */
virtual CameraParameters getParameters() const = 0;
/**
* Send command to camera driver.
*/
virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
/**
* Release the hardware resources owned by this object. Note that this is
* *not* done in the destructor.
*/
virtual void release() = 0;
/**
* Dump state of the camera hardware
*/
virtual status_t dump(int fd, const Vector<String16>& args) const = 0;
/**
* Take a LiveSnapshot - Picture while recording
*/
virtual status_t takeLiveSnapshot() = 0;
};
/**
* The functions need to be provided by the camera HAL.
*
* If getNumberOfCameras() returns N, the valid cameraId for getCameraInfo()
* and openCameraHardware() is 0 to N-1.
*/
extern "C" int HAL_getNumberOfCameras();
extern "C" void HAL_getCameraInfo(int cameraId, struct CameraInfo* cameraInfo);
/* HAL should return NULL if it fails to open camera hardware. */
extern "C" sp<CameraHardwareInterface> HAL_openCameraHardware(int cameraId, int mode);
/* Returns whether the camera is in 3D mode or not */
extern "C" int HAL_isIn3DMode();
}; // namespace android
#endif
+585
View File
@@ -0,0 +1,585 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* Copyright (c) 2011 The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_CAMERA_PARAMETERS_H
#define ANDROID_HARDWARE_CAMERA_PARAMETERS_H
#include <utils/KeyedVector.h>
#include <utils/String8.h>
namespace android {
struct Size {
int width;
int height;
Size() {
width = 0;
height = 0;
}
Size(int w, int h) {
width = w;
height = h;
}
};
struct FPSRange{
int minFPS;
int maxFPS;
FPSRange(){
minFPS=0;
maxFPS=0;
};
FPSRange(int min,int max){
minFPS=min;
maxFPS=max;
};
};
class CameraParameters
{
public:
CameraParameters();
CameraParameters(const String8 &params) { unflatten(params); }
~CameraParameters();
String8 flatten() const;
void unflatten(const String8 &params);
void set(const char *key, const char *value);
void set(const char *key, int value);
void setFloat(const char *key, float value);
const char *get(const char *key) const;
int getInt(const char *key) const;
float getFloat(const char *key) const;
void remove(const char *key);
void setPreviewSize(int width, int height);
void getPreviewSize(int *width, int *height) const;
void getSupportedPreviewSizes(Vector<Size> &sizes) const;
void setPreviewFrameRate(int fps);
int getPreviewFrameRate() const;
void getPreviewFpsRange(int *min_fps, int *max_fps) const;
void setPreviewFrameRateMode(const char *mode);
const char *getPreviewFrameRateMode() const;
void setPreviewFormat(const char *format);
const char *getPreviewFormat() const;
void setPictureSize(int width, int height);
void getPictureSize(int *width, int *height) const;
void getSupportedPictureSizes(Vector<Size> &sizes) const;
void setPictureFormat(const char *format);
const char *getPictureFormat() const;
void setTouchIndexAec(int x, int y);
void getTouchIndexAec(int *x, int *y) const;
void setTouchIndexAf(int x, int y);
void getTouchIndexAf(int *x, int *y) const;
void dump() const;
status_t dump(int fd, const Vector<String16>& args) const;
// Parameter keys to communicate between camera application and driver.
// The access (read/write, read only, or write only) is viewed from the
// perspective of applications, not driver.
// Preview frame size in pixels (width x height).
// Example value: "480x320". Read/Write.
static const char KEY_PREVIEW_SIZE[];
// Supported preview frame sizes in pixels.
// Example value: "800x600,480x320". Read only.
static const char KEY_SUPPORTED_PREVIEW_SIZES[];
// Supported PREVIEW/RECORDING SIZES IN HIGH FRAME RATE recording, sizes in pixels.
// Example value: "800x480,432x320". Read only.
static const char KEY_SUPPORTED_HFR_SIZES[];
// The current minimum and maximum preview fps. This controls the rate of
// preview frames received (CAMERA_MSG_PREVIEW_FRAME). The minimum and
// maximum fps must be one of the elements from
// KEY_SUPPORTED_PREVIEW_FPS_RANGE parameter.
// Example value: "10500,26623"
static const char KEY_PREVIEW_FPS_RANGE[];
// The supported preview fps (frame-per-second) ranges. Each range contains
// a minimum fps and maximum fps. If minimum fps equals to maximum fps, the
// camera outputs frames in fixed frame rate. If not, the camera outputs
// frames in auto frame rate. The actual frame rate fluctuates between the
// minimum and the maximum. The list has at least one element. The list is
// sorted from small to large (first by maximum fps and then minimum fps).
// Example value: "(10500,26623),(15000,26623),(30000,30000)"
static const char KEY_SUPPORTED_PREVIEW_FPS_RANGE[];
// The image format for preview frames. See CAMERA_MSG_PREVIEW_FRAME in
// frameworks/base/include/camera/Camera.h.
// Example value: "yuv420sp" or PIXEL_FORMAT_XXX constants. Read/write.
static const char KEY_PREVIEW_FORMAT[];
// Supported image formats for preview frames.
// Example value: "yuv420sp,yuv422i-yuyv". Read only.
static const char KEY_SUPPORTED_PREVIEW_FORMATS[];
// Number of preview frames per second. This is the target frame rate. The
// actual frame rate depends on the driver.
// Example value: "15". Read/write.
static const char KEY_PREVIEW_FRAME_RATE[];
// Supported number of preview frames per second.
// Example value: "24,15,10". Read.
static const char KEY_SUPPORTED_PREVIEW_FRAME_RATES[];
// The mode of preview frame rate.
// Example value: "frame-rate-auto, frame-rate-fixed".
static const char KEY_PREVIEW_FRAME_RATE_MODE[];
static const char KEY_SUPPORTED_PREVIEW_FRAME_RATE_MODES[];
static const char KEY_PREVIEW_FRAME_RATE_AUTO_MODE[];
static const char KEY_PREVIEW_FRAME_RATE_FIXED_MODE[];
// The dimensions for captured pictures in pixels (width x height).
// Example value: "1024x768". Read/write.
static const char KEY_PICTURE_SIZE[];
// Supported dimensions for captured pictures in pixels.
// Example value: "2048x1536,1024x768". Read only.
static const char KEY_SUPPORTED_PICTURE_SIZES[];
// The image format for captured pictures. See CAMERA_MSG_COMPRESSED_IMAGE
// in frameworks/base/include/camera/Camera.h.
// Example value: "jpeg" or PIXEL_FORMAT_XXX constants. Read/write.
static const char KEY_PICTURE_FORMAT[];
// Supported image formats for captured pictures.
// Example value: "jpeg,rgb565". Read only.
static const char KEY_SUPPORTED_PICTURE_FORMATS[];
// The width (in pixels) of EXIF thumbnail in Jpeg picture.
// Example value: "512". Read/write.
static const char KEY_JPEG_THUMBNAIL_WIDTH[];
// The height (in pixels) of EXIF thumbnail in Jpeg picture.
// Example value: "384". Read/write.
static const char KEY_JPEG_THUMBNAIL_HEIGHT[];
// Supported EXIF thumbnail sizes (width x height). 0x0 means not thumbnail
// in EXIF.
// Example value: "512x384,320x240,0x0". Read only.
static const char KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES[];
// The quality of the EXIF thumbnail in Jpeg picture. The range is 1 to 100,
// with 100 being the best.
// Example value: "90". Read/write.
static const char KEY_JPEG_THUMBNAIL_QUALITY[];
// Jpeg quality of captured picture. The range is 1 to 100, with 100 being
// the best.
// Example value: "90". Read/write.
static const char KEY_JPEG_QUALITY[];
// The rotation angle in degrees relative to the orientation of the camera.
// This affects the pictures returned from CAMERA_MSG_COMPRESSED_IMAGE. The
// camera driver may set orientation in the EXIF header without rotating the
// picture. Or the driver may rotate the picture and the EXIF thumbnail. If
// the Jpeg picture is rotated, the orientation in the EXIF header will be
// missing or 1 (row #0 is top and column #0 is left side).
//
// Note that the JPEG pictures of front-facing cameras are not mirrored
// as in preview display.
//
// For example, suppose the natural orientation of the device is portrait.
// The device is rotated 270 degrees clockwise, so the device orientation is
// 270. Suppose a back-facing camera sensor is mounted in landscape and the
// top side of the camera sensor is aligned with the right edge of the
// display in natural orientation. So the camera orientation is 90. The
// rotation should be set to 0 (270 + 90).
//
// Example value: "0" or "90" or "180" or "270". Write only.
static const char KEY_ROTATION[];
// GPS latitude coordinate. GPSLatitude and GPSLatitudeRef will be stored in
// JPEG EXIF header.
// Example value: "25.032146" or "-33.462809". Write only.
static const char KEY_GPS_LATITUDE[];
// GPS longitude coordinate. GPSLongitude and GPSLongitudeRef will be stored
// in JPEG EXIF header.
// Example value: "121.564448" or "-70.660286". Write only.
static const char KEY_GPS_LONGITUDE[];
// GPS altitude. GPSAltitude and GPSAltitudeRef will be stored in JPEG EXIF
// header.
// Example value: "21.0" or "-5". Write only.
static const char KEY_GPS_ALTITUDE[];
static const char KEY_SKIN_TONE_ENHANCEMENT[] ;
static const char KEY_SUPPORTED_SKIN_TONE_ENHANCEMENT_MODES[] ;
// GPS timestamp (UTC in seconds since January 1, 1970). This should be
// stored in JPEG EXIF header.
// Example value: "1251192757". Write only.
static const char KEY_GPS_TIMESTAMP[];
// GPS Processing Method
// Example value: "GPS" or "NETWORK". Write only.
static const char KEY_GPS_PROCESSING_METHOD[];
// Current white balance setting.
// Example value: "auto" or WHITE_BALANCE_XXX constants. Read/write.
static const char KEY_WHITE_BALANCE[];
// Supported white balance settings.
// Example value: "auto,incandescent,daylight". Read only.
static const char KEY_SUPPORTED_WHITE_BALANCE[];
// Current color effect setting.
// Example value: "none" or EFFECT_XXX constants. Read/write.
static const char KEY_EFFECT[];
// Supported color effect settings.
// Example value: "none,mono,sepia". Read only.
static const char KEY_SUPPORTED_EFFECTS[];
//Touch Af/AEC settings.
static const char KEY_TOUCH_AF_AEC[];
static const char KEY_SUPPORTED_TOUCH_AF_AEC[];
//Touch Index for AEC.
static const char KEY_TOUCH_INDEX_AEC[];
//Touch Index for AF.
static const char KEY_TOUCH_INDEX_AF[];
// Current antibanding setting.
// Example value: "auto" or ANTIBANDING_XXX constants. Read/write.
static const char KEY_ANTIBANDING[];
// Supported antibanding settings.
// Example value: "auto,50hz,60hz,off". Read only.
static const char KEY_SUPPORTED_ANTIBANDING[];
// Current scene mode.
// Example value: "auto" or SCENE_MODE_XXX constants. Read/write.
static const char KEY_SCENE_MODE[];
// Supported scene mode settings.
// Example value: "auto,night,fireworks". Read only.
static const char KEY_SUPPORTED_SCENE_MODES[];
// Current auto scene detection mode.
// Example value: "off" or SCENE_DETECT_XXX constants. Read/write.
static const char KEY_SCENE_DETECT[];
// Supported auto scene detection settings.
// Example value: "off,backlight,snow/cloudy". Read only.
static const char KEY_SUPPORTED_SCENE_DETECT[];
// Current flash mode.
// Example value: "auto" or FLASH_MODE_XXX constants. Read/write.
static const char KEY_FLASH_MODE[];
// Supported flash modes.
// Example value: "auto,on,off". Read only.
static const char KEY_SUPPORTED_FLASH_MODES[];
// Current focus mode. This will not be empty. Applications should call
// CameraHardwareInterface.autoFocus to start the focus if focus mode is
// FOCUS_MODE_AUTO or FOCUS_MODE_MACRO.
// Example value: "auto" or FOCUS_MODE_XXX constants. Read/write.
static const char KEY_FOCUS_MODE[];
// Supported focus modes.
// Example value: "auto,macro,fixed". Read only.
static const char KEY_SUPPORTED_FOCUS_MODES[];
// Focal length in millimeter.
// Example value: "4.31". Read only.
static const char KEY_FOCAL_LENGTH[];
// Horizontal angle of view in degrees.
// Example value: "54.8". Read only.
static const char KEY_HORIZONTAL_VIEW_ANGLE[];
// Vertical angle of view in degrees.
// Example value: "42.5". Read only.
static const char KEY_VERTICAL_VIEW_ANGLE[];
// Exposure compensation index. 0 means exposure is not adjusted.
// Example value: "0" or "5". Read/write.
static const char KEY_EXPOSURE_COMPENSATION[];
// The maximum exposure compensation index (>=0).
// Example value: "6". Read only.
static const char KEY_MAX_EXPOSURE_COMPENSATION[];
// The minimum exposure compensation index (<=0).
// Example value: "-6". Read only.
static const char KEY_MIN_EXPOSURE_COMPENSATION[];
// The exposure compensation step. Exposure compensation index multiply by
// step eqals to EV. Ex: if exposure compensation index is 6 and step is
// 0.3333, EV is -2.
// Example value: "0.333333333" or "0.5". Read only.
static const char KEY_EXPOSURE_COMPENSATION_STEP[];
// Current zoom value.
// Example value: "0" or "6". Read/write.
static const char KEY_ZOOM[];
// Maximum zoom value.
// Example value: "6". Read only.
static const char KEY_MAX_ZOOM[];
// The zoom ratios of all zoom values. The zoom ratio is in 1/100
// increments. Ex: a zoom of 3.2x is returned as 320. The number of list
// elements is KEY_MAX_ZOOM + 1. The first element is always 100. The last
// element is the zoom ratio of zoom value KEY_MAX_ZOOM.
// Example value: "100,150,200,250,300,350,400". Read only.
static const char KEY_ZOOM_RATIOS[];
// Whether zoom is supported. Zoom is supported if the value is "true". Zoom
// is not supported if the value is not "true" or the key does not exist.
// Example value: "true". Read only.
static const char KEY_ZOOM_SUPPORTED[];
// Whether if smooth zoom is supported. Smooth zoom is supported if the
// value is "true". It is not supported if the value is not "true" or the
// key does not exist.
// See CAMERA_CMD_START_SMOOTH_ZOOM, CAMERA_CMD_STOP_SMOOTH_ZOOM, and
// CAMERA_MSG_ZOOM in frameworks/base/include/camera/Camera.h.
// Example value: "true". Read only.
static const char KEY_SMOOTH_ZOOM_SUPPORTED[];
// The distances (in meters) from the camera to where an object appears to
// be in focus. The object is sharpest at the optimal focus distance. The
// depth of field is the far focus distance minus near focus distance.
//
// Focus distances may change after starting auto focus, canceling auto
// focus, or starting the preview. Applications can read this anytime to get
// the latest focus distances. If the focus mode is FOCUS_MODE_CONTINUOUS,
// focus distances may change from time to time.
//
// This is intended to estimate the distance between the camera and the
// subject. After autofocus, the subject distance may be within near and far
// focus distance. However, the precision depends on the camera hardware,
// autofocus algorithm, the focus area, and the scene. The error can be
// large and it should be only used as a reference.
//
// Far focus distance > optimal focus distance > near focus distance. If
// the far focus distance is infinity, the value should be "Infinity" (case
// sensitive). The format is three float values separated by commas. The
// first is near focus distance. The second is optimal focus distance. The
// third is far focus distance.
// Example value: "0.95,1.9,Infinity" or "0.049,0.05,0.051". Read only.
static const char KEY_FOCUS_DISTANCES[];
// The image format for video frames. See CAMERA_MSG_VIDEO_FRAME in
// frameworks/base/include/camera/Camera.h.
// Example value: "yuv420sp" or PIXEL_FORMAT_XXX constants. Read only.
static const char KEY_VIDEO_FRAME_FORMAT[];
static const char KEY_ISO_MODE[];
static const char KEY_SUPPORTED_ISO_MODES[];
static const char KEY_LENSSHADE[] ;
static const char KEY_SUPPORTED_LENSSHADE_MODES[] ;
static const char KEY_AUTO_EXPOSURE[];
static const char KEY_SUPPORTED_AUTO_EXPOSURE[];
static const char KEY_GPS_LATITUDE_REF[];
static const char KEY_GPS_LONGITUDE_REF[];
static const char KEY_GPS_ALTITUDE_REF[];
static const char KEY_GPS_STATUS[];
static const char KEY_EXIF_DATETIME[];
static const char KEY_MEMORY_COLOR_ENHANCEMENT[];
static const char KEY_SUPPORTED_MEM_COLOR_ENHANCE_MODES[];
static const char KEY_VIDEO_HIGH_FRAME_RATE[];
static const char KEY_SUPPORTED_VIDEO_HIGH_FRAME_RATE_MODES[];
static const char KEY_HIGH_DYNAMIC_RANGE_IMAGING[];
static const char KEY_SUPPORTED_HDR_IMAGING_MODES[];
// Value for KEY_ZOOM_SUPPORTED or KEY_SMOOTH_ZOOM_SUPPORTED.
static const char TRUE[];
// Value for KEY_FOCUS_DISTANCES.
static const char FOCUS_DISTANCE_INFINITY[];
// DENOISE
static const char KEY_DENOISE[];
static const char KEY_SUPPORTED_DENOISE[];
//Selectable zone AF.
static const char KEY_SELECTABLE_ZONE_AF[];
static const char KEY_SUPPORTED_SELECTABLE_ZONE_AF[];
//Face Detection
static const char KEY_FACE_DETECTION[];
static const char KEY_SUPPORTED_FACE_DETECTION[];
//Redeye Reduction
static const char KEY_REDEYE_REDUCTION[];
static const char KEY_SUPPORTED_REDEYE_REDUCTION[];
// Values for white balance settings.
static const char WHITE_BALANCE_AUTO[];
static const char WHITE_BALANCE_INCANDESCENT[];
static const char WHITE_BALANCE_FLUORESCENT[];
static const char WHITE_BALANCE_WARM_FLUORESCENT[];
static const char WHITE_BALANCE_DAYLIGHT[];
static const char WHITE_BALANCE_CLOUDY_DAYLIGHT[];
static const char WHITE_BALANCE_TWILIGHT[];
static const char WHITE_BALANCE_SHADE[];
// Values for effect settings.
static const char EFFECT_NONE[];
static const char EFFECT_MONO[];
static const char EFFECT_NEGATIVE[];
static const char EFFECT_SOLARIZE[];
static const char EFFECT_SEPIA[];
static const char EFFECT_POSTERIZE[];
static const char EFFECT_WHITEBOARD[];
static const char EFFECT_BLACKBOARD[];
static const char EFFECT_AQUA[];
static const char EFFECT_EMBOSS[];
static const char EFFECT_SKETCH[];
static const char EFFECT_NEON[];
// Values for Touch AF/AEC
static const char TOUCH_AF_AEC_OFF[] ;
static const char TOUCH_AF_AEC_ON[] ;
// Values for antibanding settings.
static const char ANTIBANDING_AUTO[];
static const char ANTIBANDING_50HZ[];
static const char ANTIBANDING_60HZ[];
static const char ANTIBANDING_OFF[];
// Values for flash mode settings.
// Flash will not be fired.
static const char FLASH_MODE_OFF[];
// Flash will be fired automatically when required. The flash may be fired
// during preview, auto-focus, or snapshot depending on the driver.
static const char FLASH_MODE_AUTO[];
// Flash will always be fired during snapshot. The flash may also be
// fired during preview or auto-focus depending on the driver.
static const char FLASH_MODE_ON[];
// Flash will be fired in red-eye reduction mode.
static const char FLASH_MODE_RED_EYE[];
// Constant emission of light during preview, auto-focus and snapshot.
// This can also be used for video recording.
static const char FLASH_MODE_TORCH[];
// Values for scene mode settings.
static const char SCENE_MODE_AUTO[];
static const char SCENE_MODE_ACTION[];
static const char SCENE_MODE_PORTRAIT[];
static const char SCENE_MODE_LANDSCAPE[];
static const char SCENE_MODE_NIGHT[];
static const char SCENE_MODE_NIGHT_PORTRAIT[];
static const char SCENE_MODE_THEATRE[];
static const char SCENE_MODE_BEACH[];
static const char SCENE_MODE_SNOW[];
static const char SCENE_MODE_SUNSET[];
static const char SCENE_MODE_STEADYPHOTO[];
static const char SCENE_MODE_FIREWORKS[];
static const char SCENE_MODE_SPORTS[];
static const char SCENE_MODE_PARTY[];
static const char SCENE_MODE_CANDLELIGHT[];
static const char SCENE_MODE_BACKLIGHT[];
static const char SCENE_MODE_FLOWERS[];
static const char SCENE_MODE_AR[];
// Applications are looking for a barcode. Camera driver will be optimized
// for barcode reading.
static const char SCENE_MODE_BARCODE[];
// Values for auto scene detection settings.
static const char SCENE_DETECT_OFF[];
static const char SCENE_DETECT_ON[];
// Formats for setPreviewFormat and setPictureFormat.
static const char PIXEL_FORMAT_YUV422SP[];
static const char PIXEL_FORMAT_YUV420SP[]; // NV21
static const char PIXEL_FORMAT_YUV420SP_ADRENO[]; // ADRENO
static const char PIXEL_FORMAT_YUV422I[]; // YUY2
static const char PIXEL_FORMAT_RGB565[];
static const char PIXEL_FORMAT_JPEG[];
static const char PIXEL_FORMAT_RAW[];
static const char PIXEL_FORMAT_YV12[]; // NV21
// Values for focus mode settings.
// Auto-focus mode. Applications should call
// CameraHardwareInterface.autoFocus to start the focus in this mode.
static const char FOCUS_MODE_AUTO[];
// Focus is set at infinity. Applications should not call
// CameraHardwareInterface.autoFocus in this mode.
static const char FOCUS_MODE_INFINITY[];
// Macro (close-up) focus mode. Applications should call
// CameraHardwareInterface.autoFocus to start the focus in this mode.
static const char FOCUS_MODE_MACRO[];
// Focus is fixed. The camera is always in this mode if the focus is not
// adjustable. If the camera has auto-focus, this mode can fix the
// focus, which is usually at hyperfocal distance. Applications should
// not call CameraHardwareInterface.autoFocus in this mode.
static const char FOCUS_MODE_FIXED[];
// Extended depth of field (EDOF). Focusing is done digitally and
// continuously. Applications should not call
// CameraHardwareInterface.autoFocus in this mode.
static const char FOCUS_MODE_EDOF[];
// Continuous auto focus mode intended for video recording. The camera
// continuously tries to focus. This is ideal for shooting video.
// Applications still can call CameraHardwareInterface.takePicture in this
// mode but the subject may not be in focus. Auto focus starts when the
// parameter is set. Applications should not call
// CameraHardwareInterface.autoFocus in this mode. To stop continuous focus,
// applications should change the focus mode to other modes.
static const char FOCUS_MODE_CONTINUOUS_VIDEO[];
// Normal focus mode. Applications should call
// CameraHardwareInterface.autoFocus to start the focus in this mode.
static const char FOCUS_MODE_NORMAL[];
static const char ISO_AUTO[];
static const char ISO_HJR[] ;
static const char ISO_100[];
static const char ISO_200[] ;
static const char ISO_400[];
static const char ISO_800[];
static const char ISO_1600[];
// Values for Lens Shading
static const char LENSSHADE_ENABLE[] ;
static const char LENSSHADE_DISABLE[] ;
// Values for auto exposure settings.
static const char AUTO_EXPOSURE_FRAME_AVG[];
static const char AUTO_EXPOSURE_CENTER_WEIGHTED[];
static const char AUTO_EXPOSURE_SPOT_METERING[];
static const char KEY_SHARPNESS[];
static const char KEY_MAX_SHARPNESS[];
static const char KEY_CONTRAST[];
static const char KEY_MAX_CONTRAST[];
static const char KEY_SATURATION[];
static const char KEY_MAX_SATURATION[];
static const char KEY_HISTOGRAM[] ;
static const char KEY_SUPPORTED_HISTOGRAM_MODES[] ;
// Values for HISTOGRAM
static const char HISTOGRAM_ENABLE[] ;
static const char HISTOGRAM_DISABLE[] ;
// Values for SKIN TONE ENHANCEMENT
static const char SKIN_TONE_ENHANCEMENT_ENABLE[] ;
static const char SKIN_TONE_ENHANCEMENT_DISABLE[] ;
// Values for Denoise
static const char DENOISE_OFF[] ;
static const char DENOISE_ON[] ;
// Values for auto exposure settings.
static const char SELECTABLE_ZONE_AF_AUTO[];
static const char SELECTABLE_ZONE_AF_SPOT_METERING[];
static const char SELECTABLE_ZONE_AF_CENTER_WEIGHTED[];
static const char SELECTABLE_ZONE_AF_FRAME_AVERAGE[];
// Values for Face Detection settings.
static const char FACE_DETECTION_OFF[];
static const char FACE_DETECTION_ON[];
// Values for MCE settings.
static const char MCE_ENABLE[];
static const char MCE_DISABLE[];
// Values for HFR settings.
static const char VIDEO_HFR_OFF[];
static const char VIDEO_HFR_2X[];
static const char VIDEO_HFR_3X[];
static const char VIDEO_HFR_4X[];
// Values for Redeye Reduction settings.
static const char REDEYE_REDUCTION_ENABLE[];
static const char REDEYE_REDUCTION_DISABLE[];
// Values for HDR settings.
static const char HDR_ENABLE[];
static const char HDR_DISABLE[];
enum {
CAMERA_ORIENTATION_UNKNOWN = 0,
CAMERA_ORIENTATION_PORTRAIT = 1,
CAMERA_ORIENTATION_LANDSCAPE = 2,
};
int getOrientation() const;
void setOrientation(int orientation);
void setPreviewFpsRange(int minFPS,int maxFPS);
void getSupportedHfrSizes(Vector<Size> &sizes) const;
private:
DefaultKeyedVector<String8,String8> mMap;
};
}; // namespace android
#endif
+117
View File
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_ICAMERA_H
#define ANDROID_HARDWARE_ICAMERA_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <surfaceflinger/ISurface.h>
#include <binder/IMemory.h>
#include <utils/String8.h>
#include <camera/Camera.h>
namespace android {
class ICameraClient;
class ICamera: public IInterface
{
public:
DECLARE_META_INTERFACE(Camera);
virtual void disconnect() = 0;
// connect new client with existing camera remote
virtual status_t connect(const sp<ICameraClient>& client) = 0;
// prevent other processes from using this ICamera interface
virtual status_t lock() = 0;
// allow other processes to use this ICamera interface
virtual status_t unlock() = 0;
// pass the buffered ISurface to the camera service
virtual status_t setPreviewDisplay(const sp<ISurface>& surface) = 0;
// set the preview callback flag to affect how the received frames from
// preview are handled.
virtual void setPreviewCallbackFlag(int flag) = 0;
// get the recording buffer information from HAL layer.
virtual status_t getBufferInfo(sp<IMemory>& Frame, size_t *alignedSize) = 0;
//encode the YUV data
virtual void encodeData() = 0;
// start preview mode, must call setPreviewDisplay first
virtual status_t startPreview() = 0;
// stop preview mode
virtual void stopPreview() = 0;
// get preview state
virtual bool previewEnabled() = 0;
// start recording mode
virtual status_t startRecording() = 0;
// stop recording mode
virtual void stopRecording() = 0;
// get recording state
virtual bool recordingEnabled() = 0;
// release a recording frame
virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0;
// auto focus
virtual status_t autoFocus() = 0;
// cancel auto focus
virtual status_t cancelAutoFocus() = 0;
// take a picture
virtual status_t takePicture() = 0;
// set preview/capture parameters - key/value pairs
virtual status_t setParameters(const String8& params) = 0;
// get preview/capture parameters - key/value pairs
virtual String8 getParameters() const = 0;
// send command to camera driver
virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
// takeLiveSnapshot
virtual status_t takeLiveSnapshot() = 0;
};
// ----------------------------------------------------------------------------
class BnCamera: public BnInterface<ICamera>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif
+51
View File
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_ICAMERA_APP_H
#define ANDROID_HARDWARE_ICAMERA_APP_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IMemory.h>
#include <utils/Timers.h>
namespace android {
class ICameraClient: public IInterface
{
public:
DECLARE_META_INTERFACE(CameraClient);
virtual void notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2) = 0;
virtual void dataCallback(int32_t msgType, const sp<IMemory>& data) = 0;
virtual void dataCallbackTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& data) = 0;
};
// ----------------------------------------------------------------------------
class BnCameraClient: public BnInterface<ICameraClient>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif
+61
View File
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_ICAMERASERVICE_H
#define ANDROID_HARDWARE_ICAMERASERVICE_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <camera/ICameraClient.h>
#include <camera/ICamera.h>
namespace android {
class ICameraService : public IInterface
{
public:
enum {
GET_NUMBER_OF_CAMERAS = IBinder::FIRST_CALL_TRANSACTION,
GET_CAMERA_INFO,
CONNECT
};
public:
DECLARE_META_INTERFACE(CameraService);
virtual int32_t getNumberOfCameras() = 0;
virtual status_t getCameraInfo(int cameraId,
struct CameraInfo* cameraInfo) = 0;
virtual sp<ICamera> connect(const sp<ICameraClient>& cameraClient,
int cameraId, int mode) = 0;
};
// ----------------------------------------------------------------------------
class BnCameraService: public BnInterface<ICameraService>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif
+57
View File
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_ISENSOR_EVENT_CONNECTION_H
#define ANDROID_GUI_ISENSOR_EVENT_CONNECTION_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------------
class SensorChannel;
class ISensorEventConnection : public IInterface
{
public:
DECLARE_META_INTERFACE(SensorEventConnection);
virtual sp<SensorChannel> getSensorChannel() const = 0;
virtual status_t enableDisable(int handle, bool enabled) = 0;
virtual status_t setEventRate(int handle, nsecs_t ns) = 0;
};
// ----------------------------------------------------------------------------
class BnSensorEventConnection : public BnInterface<ISensorEventConnection>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_ISENSOR_EVENT_CONNECTION_H
+57
View File
@@ -0,0 +1,57 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_ISENSORSERVER_H
#define ANDROID_GUI_ISENSORSERVER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------------
class Sensor;
class ISensorEventConnection;
class ISensorServer : public IInterface
{
public:
DECLARE_META_INTERFACE(SensorServer);
virtual Vector<Sensor> getSensorList() = 0;
virtual sp<ISensorEventConnection> createSensorEventConnection() = 0;
};
// ----------------------------------------------------------------------------
class BnSensorServer : public BnInterface<ISensorServer>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_ISENSORSERVER_H
+91
View File
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_SENSOR_H
#define ANDROID_GUI_SENSOR_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/String8.h>
#include <utils/Flattenable.h>
#include <hardware/sensors.h>
#include <android/sensor.h>
// ----------------------------------------------------------------------------
// Concrete types for the NDK
struct ASensor { };
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
class Parcel;
// ----------------------------------------------------------------------------
class Sensor : public ASensor, public Flattenable
{
public:
enum {
TYPE_ACCELEROMETER = ASENSOR_TYPE_ACCELEROMETER,
TYPE_MAGNETIC_FIELD = ASENSOR_TYPE_MAGNETIC_FIELD,
TYPE_GYROSCOPE = ASENSOR_TYPE_GYROSCOPE,
TYPE_LIGHT = ASENSOR_TYPE_LIGHT,
TYPE_PROXIMITY = ASENSOR_TYPE_PROXIMITY
};
Sensor();
Sensor(struct sensor_t const* hwSensor);
virtual ~Sensor();
const String8& getName() const;
const String8& getVendor() const;
int32_t getHandle() const;
int32_t getType() const;
float getMinValue() const;
float getMaxValue() const;
float getResolution() const;
float getPowerUsage() const;
int32_t getMinDelay() const;
// Flattenable interface
virtual size_t getFlattenedSize() const;
virtual size_t getFdCount() const;
virtual status_t flatten(void* buffer, size_t size,
int fds[], size_t count) const;
virtual status_t unflatten(void const* buffer, size_t size,
int fds[], size_t count);
private:
String8 mName;
String8 mVendor;
int32_t mHandle;
int32_t mType;
float mMinValue;
float mMaxValue;
float mResolution;
float mPower;
int32_t mMinDelay;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SENSOR_H
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_SENSOR_CHANNEL_H
#define ANDROID_GUI_SENSOR_CHANNEL_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
namespace android {
// ----------------------------------------------------------------------------
class Parcel;
class SensorChannel : public RefBase
{
public:
SensorChannel();
SensorChannel(const Parcel& data);
virtual ~SensorChannel();
int getFd() const;
ssize_t write(void const* vaddr, size_t size);
ssize_t read(void* vaddr, size_t size);
status_t writeToParcel(Parcel* reply) const;
private:
int mSendFd;
mutable int mReceiveFd;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SENSOR_CHANNEL_H
+82
View File
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_SENSOR_EVENT_QUEUE_H
#define ANDROID_SENSOR_EVENT_QUEUE_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/Timers.h>
#include <gui/SensorChannel.h>
// ----------------------------------------------------------------------------
struct ALooper;
struct ASensorEvent;
// Concrete types for the NDK
struct ASensorEventQueue {
ALooper* looper;
};
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
class ISensorEventConnection;
class Sensor;
class Looper;
// ----------------------------------------------------------------------------
class SensorEventQueue : public ASensorEventQueue, public RefBase
{
public:
SensorEventQueue(const sp<ISensorEventConnection>& connection);
virtual ~SensorEventQueue();
virtual void onFirstRef();
int getFd() const;
ssize_t write(ASensorEvent const* events, size_t numEvents);
ssize_t read(ASensorEvent* events, size_t numEvents);
status_t waitForEvent() const;
status_t wake() const;
status_t enableSensor(Sensor const* sensor) const;
status_t disableSensor(Sensor const* sensor) const;
status_t setEventRate(Sensor const* sensor, nsecs_t ns) const;
// these are here only to support SensorManager.java
status_t enableSensor(int32_t handle, int32_t us) const;
status_t disableSensor(int32_t handle) const;
private:
sp<Looper> getLooper() const;
sp<ISensorEventConnection> mSensorEventConnection;
sp<SensorChannel> mSensorChannel;
mutable Mutex mLock;
mutable sp<Looper> mLooper;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SENSOR_EVENT_QUEUE_H
+63
View File
@@ -0,0 +1,63 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_SENSOR_MANAGER_H
#define ANDROID_GUI_SENSOR_MANAGER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/Singleton.h>
#include <utils/Vector.h>
#include <gui/SensorEventQueue.h>
// ----------------------------------------------------------------------------
// Concrete types for the NDK
struct ASensorManager { };
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
class ISensorServer;
class Sensor;
class SensorEventQueue;
// ----------------------------------------------------------------------------
class SensorManager : public ASensorManager, public Singleton<SensorManager>
{
public:
SensorManager();
~SensorManager();
ssize_t getSensorList(Sensor const* const** list) const;
Sensor const* getDefaultSensor(int type);
sp<SensorEventQueue> createEventQueue();
private:
sp<ISensorServer> mSensorServer;
Sensor const** mSensorList;
Vector<Sensor> mSensors;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SENSOR_MANAGER_H
+470
View File
@@ -0,0 +1,470 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_AUDIOEFFECT_H
#define ANDROID_AUDIOEFFECT_H
#include <stdint.h>
#include <sys/types.h>
#include <media/IAudioFlinger.h>
#include <media/IEffect.h>
#include <media/IEffectClient.h>
#include <media/EffectApi.h>
#include <media/AudioSystem.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------------
class effect_param_cblk_t;
// ----------------------------------------------------------------------------
class AudioEffect : public RefBase
{
public:
/*
* Static methods for effect libraries management.
*/
/*
* Loads the effect library which path is given as first argument.
* This must be the full path of a dynamic library (.so) implementing one or
* more effect engines and exposing the effect library interface described in
* EffectApi.h. The function returns a handle on the library for use by
* further call to unloadEffectLibrary() to unload the library.
*
* Parameters:
* libPath: full path of the dynamic library file in the file system.
* handle: address where to return the library handle
*
* Returned status (from utils/Errors.h) can be:
* NO_ERROR successful operation.
* PERMISSION_DENIED could not get AudioFlinger interface or
* application does not have permission to configure audio
* NO_INIT effect factory not initialized or
* library could not be loaded or
* library does not implement required functions
* BAD_VALUE invalid libPath string or handle
*
* Returned value:
* *handle updated with library handle
*/
static status_t loadEffectLibrary(const char *libPath, int *handle);
/*
* Unloads the effect library which handle is given as argument.
*
* Parameters:
* handle: library handle
*
* Returned status (from utils/Errors.h) can be:
* NO_ERROR successful operation.
* PERMISSION_DENIED could not get AudioFlinger interface or
* application does not have permission to configure audio
* NO_INIT effect factory not initialized
* BAD_VALUE invalid handle
*/
static status_t unloadEffectLibrary(int handle);
/*
* Static methods for effects enumeration.
*/
/*
* Returns the number of effects available. This method together
* with queryEffect() is used to enumerate all effects:
* The enumeration sequence is:
* queryNumberEffects(&num_effects);
* for (i = 0; i < num_effects; i++)
* queryEffect(i,...);
*
* Parameters:
* numEffects: address where the number of effects should be returned.
*
* Returned status (from utils/Errors.h) can be:
* NO_ERROR successful operation.
* PERMISSION_DENIED could not get AudioFlinger interface
* NO_INIT effect library failed to initialize
* BAD_VALUE invalid numEffects pointer
*
* Returned value
* *numEffects: updated with number of effects available
*/
static status_t queryNumberEffects(uint32_t *numEffects);
/*
* Returns an effect descriptor during effect
* enumeration.
*
* Parameters:
* index: index of the queried effect.
* descriptor: address where the effect descriptor should be returned.
*
* Returned status (from utils/Errors.h) can be:
* NO_ERROR successful operation.
* PERMISSION_DENIED could not get AudioFlinger interface
* NO_INIT effect library failed to initialize
* BAD_VALUE invalid descriptor pointer or index
* INVALID_OPERATION effect list has changed since last execution of queryNumberEffects()
*
* Returned value
* *descriptor: updated with effect descriptor
*/
static status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor);
/*
* Returns the descriptor for the specified effect uuid.
*
* Parameters:
* uuid: pointer to effect uuid.
* descriptor: address where the effect descriptor should be returned.
*
* Returned status (from utils/Errors.h) can be:
* NO_ERROR successful operation.
* PERMISSION_DENIED could not get AudioFlinger interface
* NO_INIT effect library failed to initialize
* BAD_VALUE invalid uuid or descriptor pointers
* NAME_NOT_FOUND no effect with this uuid found
*
* Returned value
* *descriptor updated with effect descriptor
*/
static status_t getEffectDescriptor(effect_uuid_t *uuid, effect_descriptor_t *descriptor);
/*
* Events used by callback function (effect_callback_t).
*/
enum event_type {
EVENT_CONTROL_STATUS_CHANGED = 0,
EVENT_ENABLE_STATUS_CHANGED = 1,
EVENT_PARAMETER_CHANGED = 2,
EVENT_ERROR = 3
};
/* Callback function notifying client application of a change in effect engine state or
* configuration.
* An effect engine can be shared by several applications but only one has the control
* of the engine activity and configuration at a time.
* The EVENT_CONTROL_STATUS_CHANGED event is received when an application loses or
* retrieves the control of the effect engine. Loss of control happens
* if another application requests the use of the engine by creating an AudioEffect for
* the same effect type but with a higher priority. Control is returned when the
* application having the control deletes its AudioEffect object.
* The EVENT_ENABLE_STATUS_CHANGED event is received by all applications not having the
* control of the effect engine when the effect is enabled or disabled.
* The EVENT_PARAMETER_CHANGED event is received by all applications not having the
* control of the effect engine when an effect parameter is changed.
* The EVENT_ERROR event is received when the media server process dies.
*
* Parameters:
*
* event: type of event notified (see enum AudioEffect::event_type).
* user: Pointer to context for use by the callback receiver.
* info: Pointer to optional parameter according to event type:
* - EVENT_CONTROL_STATUS_CHANGED: boolean indicating if control is granted (true)
* or stolen (false).
* - EVENT_ENABLE_STATUS_CHANGED: boolean indicating if effect is now enabled (true)
* or disabled (false).
* - EVENT_PARAMETER_CHANGED: pointer to a effect_param_t structure.
* - EVENT_ERROR: status_t indicating the error (DEAD_OBJECT when media server dies).
*/
typedef void (*effect_callback_t)(int32_t event, void* user, void *info);
/* Constructor.
* AudioEffect is the base class for creating and controlling an effect engine from
* the application process. Creating an AudioEffect object will create the effect engine
* in the AudioFlinger if no engine of the specified type exists. If one exists, this engine
* will be used. The application creating the AudioEffect object (or a derived class like
* Reverb for instance) will either receive control of the effect engine or not, depending
* on the priority parameter. If priority is higher than the priority used by the current
* effect engine owner, the control will be transfered to the new application. Otherwise
* control will remain to the previous application. In this case, the new application will be
* notified of changes in effect engine state or control ownership by the effect callback.
* After creating the AudioEffect, the application must call the initCheck() method and
* check the creation status before trying to control the effect engine (see initCheck()).
* If the effect is to be applied to an AudioTrack or MediaPlayer only the application
* must specify the audio session ID corresponding to this player.
*/
/* Simple Constructor.
*/
AudioEffect();
/* Constructor.
*
* Parameters:
*
* type: type of effect created: can be null if uuid is specified. This corresponds to
* the OpenSL ES interface implemented by this effect.
* uuid: Uuid of effect created: can be null if type is specified. This uuid corresponds to
* a particular implementation of an effect type.
* priority: requested priority for effect control: the priority level corresponds to the
* value of priority parameter: negative values indicate lower priorities, positive values
* higher priorities, 0 being the normal priority.
* cbf: optional callback function (see effect_callback_t)
* user: pointer to context for use by the callback receiver.
* sessionID: audio session this effect is associated to. If 0, the effect will be global to
* the output mix. If not 0, the effect will be applied to all players
* (AudioTrack or MediaPLayer) within the same audio session.
* output: HAL audio output stream to which this effect must be attached. Leave at 0 for
* automatic output selection by AudioFlinger.
*/
AudioEffect(const effect_uuid_t *type,
const effect_uuid_t *uuid = NULL,
int32_t priority = 0,
effect_callback_t cbf = 0,
void* user = 0,
int sessionId = 0,
audio_io_handle_t output = 0
);
/* Constructor.
* Same as above but with type and uuid specified by character strings
*/
AudioEffect(const char *typeStr,
const char *uuidStr = NULL,
int32_t priority = 0,
effect_callback_t cbf = 0,
void* user = 0,
int sessionId = 0,
audio_io_handle_t output = 0
);
/* Terminates the AudioEffect and unregisters it from AudioFlinger.
* The effect engine is also destroyed if this AudioEffect was the last controlling
* the engine.
*/
~AudioEffect();
/* Initialize an uninitialized AudioEffect.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR or ALREADY_EXISTS: successful initialization
* - INVALID_OPERATION: AudioEffect is already initialized
* - BAD_VALUE: invalid parameter
* - NO_INIT: audio flinger or audio hardware not initialized
* */
status_t set(const effect_uuid_t *type,
const effect_uuid_t *uuid = NULL,
int32_t priority = 0,
effect_callback_t cbf = 0,
void* user = 0,
int sessionId = 0,
audio_io_handle_t output = 0
);
/* Result of constructing the AudioEffect. This must be checked
* before using any AudioEffect API.
* initCheck() can return:
* - NO_ERROR: the effect engine is successfully created and the application has control.
* - ALREADY_EXISTS: the effect engine is successfully created but the application does not
* have control.
* - NO_INIT: the effect creation failed.
*
*/
status_t initCheck() const;
/* Returns the unique effect Id for the controlled effect engine. This ID is unique
* system wide and is used for instance in the case of auxiliary effects to attach
* the effect to an AudioTrack or MediaPlayer.
*
*/
int32_t id() const { return mId; }
/* Returns a descriptor for the effect (see effect_descriptor_t in EffectApi.h).
*/
effect_descriptor_t descriptor() const;
/* Returns effect control priority of this AudioEffect object.
*/
int32_t priority() const { return mPriority; }
/* Enables or disables the effect engine.
*
* Parameters:
* enabled: requested enable state.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the application does not have control of the effect engine or the
* effect is already in the requested state.
*/
virtual status_t setEnabled(bool enabled);
bool getEnabled() const;
/* Sets a parameter value.
*
* Parameters:
* param: pointer to effect_param_t structure containing the parameter
* and its value (See EffectApi.h).
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation.
* - INVALID_OPERATION: the application does not have control of the effect engine.
* - BAD_VALUE: invalid parameter identifier or value.
* - DEAD_OBJECT: the effect engine has been deleted.
*/
virtual status_t setParameter(effect_param_t *param);
/* Prepare a new parameter value that will be set by next call to
* setParameterCommit(). This method can be used to set multiple parameters
* in a synchronous manner or to avoid multiple binder calls for each
* parameter.
*
* Parameters:
* param: pointer to effect_param_t structure containing the parameter
* and its value (See EffectApi.h).
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation.
* - INVALID_OPERATION: the application does not have control of the effect engine.
* - NO_MEMORY: no more space available in shared memory used for deferred parameter
* setting.
*/
virtual status_t setParameterDeferred(effect_param_t *param);
/* Commit all parameter values previously prepared by setParameterDeferred().
*
* Parameters:
* none
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation.
* - INVALID_OPERATION: No new parameter values ready for commit.
* - BAD_VALUE: invalid parameter identifier or value: there is no indication
* as to which of the parameters caused this error.
* - DEAD_OBJECT: the effect engine has been deleted.
*/
virtual status_t setParameterCommit();
/* Gets a parameter value.
*
* Parameters:
* param: pointer to effect_param_t structure containing the parameter
* and the returned value (See EffectApi.h).
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation.
* - INVALID_OPERATION: the AudioEffect was not successfully initialized.
* - BAD_VALUE: invalid parameter identifier.
* - DEAD_OBJECT: the effect engine has been deleted.
*/
virtual status_t getParameter(effect_param_t *param);
/* Sends a command and receives a response to/from effect engine.
* See EffectApi.h for details on effect command() function, valid command codes
* and formats.
*/
virtual status_t command(uint32_t cmdCode,
uint32_t cmdSize,
void *cmdData,
uint32_t *replySize,
void *replyData);
/*
* Utility functions.
*/
/* Converts the string passed as first argument to the effect_uuid_t
* pointed to by second argument
*/
static status_t stringToGuid(const char *str, effect_uuid_t *guid);
/* Converts the effect_uuid_t pointed to by first argument to the
* string passed as second argument
*/
static status_t guidToString(const effect_uuid_t *guid, char *str, size_t maxLen);
protected:
volatile int32_t mEnabled; // enable state
int32_t mSessionId; // audio session ID
int32_t mPriority; // priority for effect control
status_t mStatus; // effect status
effect_callback_t mCbf; // callback function for status, control and
// parameter changes notifications
void* mUserData; // client context for callback function
effect_descriptor_t mDescriptor; // effect descriptor
int32_t mId; // system wide unique effect engine instance ID
private:
// Implements the IEffectClient interface
class EffectClient : public android::BnEffectClient, public android::IBinder::DeathRecipient
{
public:
EffectClient(AudioEffect *effect) : mEffect(effect){}
// IEffectClient
virtual void controlStatusChanged(bool controlGranted) {
mEffect->controlStatusChanged(controlGranted);
}
virtual void enableStatusChanged(bool enabled) {
mEffect->enableStatusChanged(enabled);
}
virtual void commandExecuted(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t replySize,
void *pReplyData) {
mEffect->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
}
// IBinder::DeathRecipient
virtual void binderDied(const wp<IBinder>& who) {mEffect->binderDied();}
private:
AudioEffect *mEffect;
};
friend class EffectClient;
// IEffectClient
void controlStatusChanged(bool controlGranted);
void enableStatusChanged(bool enabled);
void commandExecuted(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t replySize,
void *pReplyData);
void binderDied();
sp<IEffect> mIEffect; // IEffect binder interface
sp<EffectClient> mIEffectClient; // IEffectClient implementation
sp<IMemory> mCblkMemory; // shared memory for deferred parameter setting
effect_param_cblk_t* mCblk; // control block for deferred parameter setting
};
}; // namespace android
#endif // ANDROID_AUDIOEFFECT_H
+390
View File
@@ -0,0 +1,390 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AUDIORECORD_H_
#define AUDIORECORD_H_
#include <stdint.h>
#include <sys/types.h>
#include <media/IAudioFlinger.h>
#include <media/IAudioRecord.h>
#include <media/AudioTrack.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <binder/IMemory.h>
#include <utils/threads.h>
namespace android {
// ----------------------------------------------------------------------------
class AudioRecord
{
public:
static const int DEFAULT_SAMPLE_RATE = 8000;
/* Events used by AudioRecord callback function (callback_t).
*
* to keep in sync with frameworks/base/media/java/android/media/AudioRecord.java
*/
enum event_type {
EVENT_MORE_DATA = 0, // Request to reqd more data from PCM buffer.
EVENT_OVERRUN = 1, // PCM buffer overrun occured.
EVENT_MARKER = 2, // Record head is at the specified marker position
// (See setMarkerPosition()).
EVENT_NEW_POS = 3, // Record head is at a new position
// (See setPositionUpdatePeriod()).
};
/* Create Buffer on the stack and pass it to obtainBuffer()
* and releaseBuffer().
*/
class Buffer
{
public:
enum {
MUTE = 0x00000001
};
uint32_t flags;
int channelCount;
int format;
size_t frameCount;
size_t size;
union {
void* raw;
short* i16;
int8_t* i8;
};
};
/* These are static methods to control the system-wide AudioFlinger
* only privileged processes can have access to them
*/
// static status_t setMasterMute(bool mute);
/* As a convenience, if a callback is supplied, a handler thread
* is automatically created with the appropriate priority. This thread
* invokes the callback when a new buffer becomes ready or an overrun condition occurs.
* Parameters:
*
* event: type of event notified (see enum AudioRecord::event_type).
* user: Pointer to context for use by the callback receiver.
* info: Pointer to optional parameter according to event type:
* - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read
* more bytes than indicated by 'size' field and update 'size' if less bytes are
* read.
* - EVENT_OVERRUN: unused.
* - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
* - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
*/
typedef void (*callback_t)(int event, void* user, void *info);
/* Returns the minimum frame count required for the successful creation of
* an AudioRecord object.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - NO_INIT: audio server or audio hardware not initialized
* - BAD_VALUE: unsupported configuration
*/
static status_t getMinFrameCount(int* frameCount,
uint32_t sampleRate,
int format,
int channelCount);
/* Constructs an uninitialized AudioRecord. No connection with
* AudioFlinger takes place.
*/
AudioRecord();
/* Creates an AudioRecord track and registers it with AudioFlinger.
* Once created, the track needs to be started before it can be used.
* Unspecified values are set to the audio hardware's current
* values.
*
* Parameters:
*
* inputSource: Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT).
* sampleRate: Track sampling rate in Hz.
* format: Audio format (e.g AudioSystem::PCM_16_BIT for signed
* 16 bits per sample).
* channels: Channel mask: see AudioSystem::audio_channels.
* frameCount: Total size of track PCM buffer in frames. This defines the
* latency of the track.
* flags: A bitmask of acoustic values from enum record_flags. It enables
* AGC, NS, and IIR.
* cbf: Callback function. If not null, this function is called periodically
* to provide new PCM data.
* notificationFrames: The callback function is called each time notificationFrames PCM
* frames are ready in record track output buffer.
* user Context for use by the callback receiver.
*/
enum record_flags {
RECORD_AGC_ENABLE = 1,
RECORD_NS_ENABLE = 2,
RECORD_IIR_ENABLE = 4
};
AudioRecord(int inputSource,
uint32_t sampleRate = 0,
int format = 0,
uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
int frameCount = 0,
uint32_t flags = 0,
callback_t cbf = 0,
void* user = 0,
int notificationFrames = 0,
int sessionId = 0);
/* Terminates the AudioRecord and unregisters it from AudioFlinger.
* Also destroys all resources assotiated with the AudioRecord.
*/
~AudioRecord();
/* Initialize an uninitialized AudioRecord.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful intialization
* - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
* - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
* - NO_INIT: audio server or audio hardware not initialized
* - PERMISSION_DENIED: recording is not allowed for the requesting process
* */
status_t set(int inputSource = 0,
uint32_t sampleRate = 0,
int format = 0,
uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
int frameCount = 0,
uint32_t flags = 0,
callback_t cbf = 0,
void* user = 0,
int notificationFrames = 0,
bool threadCanCallJava = false,
int sessionId = 0);
/* Result of constructing the AudioRecord. This must be checked
* before using any AudioRecord API (except for set()), using
* an uninitialized AudioRecord produces undefined results.
* See set() method above for possible return codes.
*/
status_t initCheck() const;
/* Returns this track's latency in milliseconds.
* This includes the latency due to AudioRecord buffer size
* and audio hardware driver.
*/
uint32_t latency() const;
/* getters, see constructor */
int format() const;
int channelCount() const;
int channels() const;
uint32_t frameCount() const;
int frameSize() const;
int inputSource() const;
/* After it's created the track is not active. Call start() to
* make it active. If set, the callback will start being called.
*/
status_t start();
/* Stop a track. If set, the callback will cease being called and
* obtainBuffer returns STOPPED. Note that obtainBuffer() still works
* and will fill up buffers until the pool is exhausted.
*/
status_t stop();
bool stopped() const;
/* get sample rate for this record track
*/
uint32_t getSampleRate();
/* Sets marker position. When record reaches the number of frames specified,
* a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
* with marker == 0 cancels marker notification callback.
* If the AudioRecord has been opened with no callback function associated,
* the operation will fail.
*
* Parameters:
*
* marker: marker position expressed in frames.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioRecord has no callback installed.
*/
status_t setMarkerPosition(uint32_t marker);
status_t getMarkerPosition(uint32_t *marker);
/* Sets position update period. Every time the number of frames specified has been recorded,
* a callback with event type EVENT_NEW_POS is called.
* Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
* callback.
* If the AudioRecord has been opened with no callback function associated,
* the operation will fail.
*
* Parameters:
*
* updatePeriod: position update notification period expressed in frames.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioRecord has no callback installed.
*/
status_t setPositionUpdatePeriod(uint32_t updatePeriod);
status_t getPositionUpdatePeriod(uint32_t *updatePeriod);
/* Gets record head position. The position is the total number of frames
* recorded since record start.
*
* Parameters:
*
* position: Address where to return record head position within AudioRecord buffer.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - BAD_VALUE: position is NULL
*/
status_t getPosition(uint32_t *position);
/* returns a handle on the audio input used by this AudioRecord.
*
* Parameters:
* none.
*
* Returned value:
* handle on audio hardware input
*/
audio_io_handle_t getInput();
/* returns the audio session ID associated to this AudioRecord.
*
* Parameters:
* none.
*
* Returned value:
* AudioRecord session ID.
*/
int getSessionId();
/* obtains a buffer of "frameCount" frames. The buffer must be
* filled entirely. If the track is stopped, obtainBuffer() returns
* STOPPED instead of NO_ERROR as long as there are buffers availlable,
* at which point NO_MORE_BUFFERS is returned.
* Buffers will be returned until the pool (buffercount())
* is exhausted, at which point obtainBuffer() will either block
* or return WOULD_BLOCK depending on the value of the "blocking"
* parameter.
*/
enum {
NO_MORE_BUFFERS = 0x80000001,
STOPPED = 1
};
status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
void releaseBuffer(Buffer* audioBuffer);
/* As a convenience we provide a read() interface to the audio buffer.
* This is implemented on top of lockBuffer/unlockBuffer.
*/
ssize_t read(void* buffer, size_t size);
/* Return the amount of input frames lost in the audio driver since the last call of this function.
* Audio driver is expected to reset the value to 0 and restart counting upon returning the current value by this function call.
* Such loss typically occurs when the user space process is blocked longer than the capacity of audio driver buffers.
* Unit: the number of input audio frames
*/
unsigned int getInputFramesLost();
private:
/* copying audio tracks is not allowed */
AudioRecord(const AudioRecord& other);
AudioRecord& operator = (const AudioRecord& other);
/* a small internal class to handle the callback */
class ClientRecordThread : public Thread
{
public:
ClientRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
private:
friend class AudioRecord;
virtual bool threadLoop();
virtual status_t readyToRun() { return NO_ERROR; }
virtual void onFirstRef() {}
AudioRecord& mReceiver;
Mutex mLock;
};
bool processAudioBuffer(const sp<ClientRecordThread>& thread);
status_t openRecord(uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
audio_io_handle_t input);
sp<IAudioRecord> mAudioRecord;
sp<IMemory> mCblkMemory;
sp<ClientRecordThread> mClientRecordThread;
Mutex mRecordThreadLock;
uint32_t mFrameCount;
audio_track_cblk_t* mCblk;
int32_t mFormat;
uint8_t mChannelCount;
uint8_t mInputSource;
uint8_t mReserved;
status_t mStatus;
uint32_t mLatency;
volatile int32_t mActive;
callback_t mCbf;
void* mUserData;
uint32_t mNotificationFrames;
uint32_t mRemainingFrames;
uint32_t mMarkerPosition;
bool mMarkerReached;
uint32_t mNewPosition;
uint32_t mUpdatePeriod;
uint32_t mFlags;
uint32_t mChannels;
audio_io_handle_t mInput;
bool mFirstread;
int mSessionId;
};
}; // namespace android
#endif /*AUDIORECORD_H_*/
+538
View File
@@ -0,0 +1,538 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_AUDIOSYSTEM_H_
#define ANDROID_AUDIOSYSTEM_H_
#include <utils/RefBase.h>
#include <utils/threads.h>
#include <media/IAudioFlinger.h>
namespace android {
typedef void (*audio_error_callback)(status_t err);
typedef int audio_io_handle_t;
class IAudioPolicyService;
class String8;
class AudioSystem
{
public:
enum stream_type {
DEFAULT =-1,
VOICE_CALL = 0,
SYSTEM = 1,
RING = 2,
MUSIC = 3,
ALARM = 4,
NOTIFICATION = 5,
BLUETOOTH_SCO = 6,
ENFORCED_AUDIBLE = 7, // Sounds that cannot be muted by user and must be routed to speaker
DTMF = 8,
TTS = 9,
FM = 10,
NUM_STREAM_TYPES
};
// Audio sub formats (see AudioSystem::audio_format).
enum pcm_sub_format {
PCM_SUB_16_BIT = 0x1, // must be 1 for backward compatibility
PCM_SUB_8_BIT = 0x2, // must be 2 for backward compatibility
};
// MP3 sub format field definition : can use 11 LSBs in the same way as MP3 frame header to specify
// bit rate, stereo mode, version...
enum mp3_sub_format {
//TODO
};
// AMR NB/WB sub format field definition: specify frame block interleaving, bandwidth efficient or octet aligned,
// encoding mode for recording...
enum amr_sub_format {
//TODO
};
// AAC sub format field definition: specify profile or bitrate for recording...
enum aac_sub_format {
//TODO
};
// VORBIS sub format field definition: specify quality for recording...
enum vorbis_sub_format {
//TODO
};
// Audio format consists in a main format field (upper 8 bits) and a sub format field (lower 24 bits).
// The main format indicates the main codec type. The sub format field indicates options and parameters
// for each format. The sub format is mainly used for record to indicate for instance the requested bitrate
// or profile. It can also be used for certain formats to give informations not present in the encoded
// audio stream (e.g. octet alignement for AMR).
enum audio_format {
INVALID_FORMAT = -1,
FORMAT_DEFAULT = 0,
PCM = 0x00000000, // must be 0 for backward compatibility
MP3 = 0x01000000,
AMR_NB = 0x02000000,
AMR_WB = 0x03000000,
AAC = 0x04000000,
HE_AAC_V1 = 0x05000000,
HE_AAC_V2 = 0x06000000,
VORBIS = 0x07000000,
EVRC = 0x08000000,
QCELP = 0x09000000,
VOIP_PCM_INPUT = 0x0A000000,
MAIN_FORMAT_MASK = 0xFF000000,
SUB_FORMAT_MASK = 0x00FFFFFF,
// Aliases
PCM_16_BIT = (PCM|PCM_SUB_16_BIT),
PCM_8_BIT = (PCM|PCM_SUB_8_BIT)
};
// Channel mask definitions must be kept in sync with JAVA values in /media/java/android/media/AudioFormat.java
enum audio_channels {
// output channels
CHANNEL_OUT_FRONT_LEFT = 0x4,
CHANNEL_OUT_FRONT_RIGHT = 0x8,
CHANNEL_OUT_FRONT_CENTER = 0x10,
CHANNEL_OUT_LOW_FREQUENCY = 0x20,
CHANNEL_OUT_BACK_LEFT = 0x40,
CHANNEL_OUT_BACK_RIGHT = 0x80,
CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x100,
CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x200,
CHANNEL_OUT_BACK_CENTER = 0x400,
CHANNEL_OUT_MONO = CHANNEL_OUT_FRONT_LEFT,
CHANNEL_OUT_STEREO = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT),
CHANNEL_OUT_QUAD = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT),
CHANNEL_OUT_SURROUND = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_BACK_CENTER),
CHANNEL_OUT_5POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT),
CHANNEL_OUT_7POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER),
CHANNEL_OUT_ALL = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER | CHANNEL_OUT_BACK_CENTER),
// input channels
CHANNEL_IN_LEFT = 0x4,
CHANNEL_IN_RIGHT = 0x8,
CHANNEL_IN_FRONT = 0x10,
CHANNEL_IN_BACK = 0x20,
CHANNEL_IN_LEFT_PROCESSED = 0x40,
CHANNEL_IN_RIGHT_PROCESSED = 0x80,
CHANNEL_IN_FRONT_PROCESSED = 0x100,
CHANNEL_IN_BACK_PROCESSED = 0x200,
CHANNEL_IN_PRESSURE = 0x400,
CHANNEL_IN_X_AXIS = 0x800,
CHANNEL_IN_Y_AXIS = 0x1000,
CHANNEL_IN_Z_AXIS = 0x2000,
CHANNEL_IN_VOICE_UPLINK = 0x4000,
CHANNEL_IN_VOICE_DNLINK = 0x8000,
CHANNEL_IN_MONO = CHANNEL_IN_FRONT,
CHANNEL_IN_STEREO = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT),
CHANNEL_IN_ALL = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT | CHANNEL_IN_FRONT | CHANNEL_IN_BACK|
CHANNEL_IN_LEFT_PROCESSED | CHANNEL_IN_RIGHT_PROCESSED | CHANNEL_IN_FRONT_PROCESSED | CHANNEL_IN_BACK_PROCESSED|
CHANNEL_IN_PRESSURE | CHANNEL_IN_X_AXIS | CHANNEL_IN_Y_AXIS | CHANNEL_IN_Z_AXIS |
CHANNEL_IN_VOICE_UPLINK | CHANNEL_IN_VOICE_DNLINK)
};
enum audio_mode {
MODE_INVALID = -2,
MODE_CURRENT = -1,
MODE_NORMAL = 0,
MODE_RINGTONE,
MODE_IN_CALL,
MODE_IN_COMMUNICATION,
NUM_MODES // not a valid entry, denotes end-of-list
};
enum audio_in_acoustics {
AGC_ENABLE = 0x0001,
AGC_DISABLE = 0,
NS_ENABLE = 0x0002,
NS_DISABLE = 0,
TX_IIR_ENABLE = 0x0004,
TX_DISABLE = 0
};
// special audio session values
enum audio_sessions {
SESSION_OUTPUT_STAGE = -1, // session for effects attached to a particular output stream
// (value must be less than 0)
SESSION_OUTPUT_MIX = 0, // session for effects applied to output mix. These effects can
// be moved by audio policy manager to another output stream
// (value must be 0)
};
/* These are static methods to control the system-wide AudioFlinger
* only privileged processes can have access to them
*/
// mute/unmute microphone
static status_t muteMicrophone(bool state);
static status_t isMicrophoneMuted(bool *state);
// set/get master volume
static status_t setMasterVolume(float value);
static status_t getMasterVolume(float* volume);
// mute/unmute audio outputs
static status_t setMasterMute(bool mute);
static status_t getMasterMute(bool* mute);
// set/get stream volume on specified output
static status_t setStreamVolume(int stream, float value, int output);
static status_t getStreamVolume(int stream, float* volume, int output);
// mute/unmute stream
static status_t setStreamMute(int stream, bool mute);
static status_t getStreamMute(int stream, bool* mute);
// set audio mode in audio hardware (see AudioSystem::audio_mode)
static status_t setMode(int mode);
// returns true in *state if tracks are active on the specified stream
static status_t isStreamActive(int stream, bool *state);
// set/get audio hardware parameters. The function accepts a list of parameters
// key value pairs in the form: key1=value1;key2=value2;...
// Some keys are reserved for standard parameters (See AudioParameter class).
static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
static String8 getParameters(audio_io_handle_t ioHandle, const String8& keys);
static void setErrorCallback(audio_error_callback cb);
// helper function to obtain AudioFlinger service handle
static const sp<IAudioFlinger>& get_audio_flinger();
static float linearToLog(int volume);
static int logToLinear(float volume);
static status_t getOutputSamplingRate(int* samplingRate, int stream = DEFAULT);
static status_t getOutputFrameCount(int* frameCount, int stream = DEFAULT);
static status_t getOutputLatency(uint32_t* latency, int stream = DEFAULT);
static bool routedToA2dpOutput(int streamType);
static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
size_t* buffSize);
static status_t setVoiceVolume(float volume);
static status_t setFmVolume(float volume);
// return the number of audio frames written by AudioFlinger to audio HAL and
// audio dsp to DAC since the output on which the specificed stream is playing
// has exited standby.
// returned status (from utils/Errors.h) can be:
// - NO_ERROR: successful operation, halFrames and dspFrames point to valid data
// - INVALID_OPERATION: Not supported on current hardware platform
// - BAD_VALUE: invalid parameter
// NOTE: this feature is not supported on all hardware platforms and it is
// necessary to check returned status before using the returned values.
static status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream = DEFAULT);
static unsigned int getInputFramesLost(audio_io_handle_t ioHandle);
static int newAudioSessionId();
//
// AudioPolicyService interface
//
enum audio_devices {
// output devices
DEVICE_OUT_EARPIECE = 0x1,
DEVICE_OUT_SPEAKER = 0x2,
DEVICE_OUT_WIRED_HEADSET = 0x4,
DEVICE_OUT_WIRED_HEADPHONE = 0x8,
DEVICE_OUT_BLUETOOTH_SCO = 0x10,
DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20,
DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40,
DEVICE_OUT_BLUETOOTH_A2DP = 0x80,
DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200,
DEVICE_OUT_AUX_DIGITAL = 0x400,
DEVICE_OUT_FM = 0x800,
DEVICE_OUT_ANC_HEADSET = 0x1000,
DEVICE_OUT_ANC_HEADPHONE = 0x2000,
DEVICE_OUT_FM_TX = 0x4000,
DEVICE_OUT_DEFAULT = 0x8000,
// Since no free bits available in output device , using free bits from input device list
DEVICE_OUT_DIRECTOUTPUT = 0x8000000,
DEVICE_OUT_ALL = (DEVICE_OUT_EARPIECE | DEVICE_OUT_SPEAKER | DEVICE_OUT_WIRED_HEADSET |
DEVICE_OUT_WIRED_HEADPHONE | DEVICE_OUT_FM | DEVICE_OUT_BLUETOOTH_SCO | DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
DEVICE_OUT_BLUETOOTH_SCO_CARKIT | DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER | DEVICE_OUT_AUX_DIGITAL | DEVICE_OUT_FM |
DEVICE_OUT_ANC_HEADSET | DEVICE_OUT_ANC_HEADPHONE | DEVICE_OUT_FM_TX | DEVICE_OUT_DIRECTOUTPUT |
DEVICE_OUT_DEFAULT),
DEVICE_OUT_ALL_A2DP = (DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
// input devices
DEVICE_IN_COMMUNICATION = 0x10000,
DEVICE_IN_AMBIENT = 0x20000,
DEVICE_IN_BUILTIN_MIC = 0x40000,
DEVICE_IN_VOICE_CALL = 0x80000,
DEVICE_IN_BACK_MIC = 0x100000,
DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x200000,
DEVICE_IN_WIRED_HEADSET = 0x400000,
DEVICE_IN_AUX_DIGITAL = 0x800000,
DEVICE_IN_ANC_HEADSET = 0x1000000,
DEVICE_IN_FM_RX = 0x2000000,
DEVICE_IN_FM_RX_A2DP = 0x4000000,
DEVICE_IN_DEFAULT = 0x80000000,
DEVICE_IN_ALL = (DEVICE_IN_COMMUNICATION | DEVICE_IN_AMBIENT | DEVICE_IN_BUILTIN_MIC |
DEVICE_IN_BLUETOOTH_SCO_HEADSET | DEVICE_IN_WIRED_HEADSET | DEVICE_IN_AUX_DIGITAL |
DEVICE_IN_VOICE_CALL | DEVICE_IN_BACK_MIC | DEVICE_IN_FM_RX | DEVICE_IN_FM_RX_A2DP | DEVICE_IN_ANC_HEADSET | DEVICE_IN_DEFAULT)
};
// device connection states used for setDeviceConnectionState()
enum device_connection_state {
DEVICE_STATE_UNAVAILABLE,
DEVICE_STATE_AVAILABLE,
NUM_DEVICE_STATES
};
// request to open a direct output with getOutput() (by opposition to sharing an output with other AudioTracks)
enum output_flags {
OUTPUT_FLAG_INDIRECT = 0x0,
OUTPUT_FLAG_DIRECT = 0x1,
OUTPUT_FLAG_SESSION = 0x2
};
// device categories used for setForceUse()
enum forced_config {
FORCE_NONE,
FORCE_SPEAKER,
FORCE_HEADPHONES,
FORCE_BT_SCO,
FORCE_BT_A2DP,
FORCE_WIRED_ACCESSORY,
FORCE_BT_CAR_DOCK,
FORCE_BT_DESK_DOCK,
NUM_FORCE_CONFIG,
FORCE_DEFAULT = FORCE_NONE
};
// usages used for setForceUse()
enum force_use {
FOR_COMMUNICATION,
FOR_MEDIA,
FOR_RECORD,
FOR_DOCK,
NUM_FORCE_USE
};
// types of io configuration change events received with ioConfigChanged()
enum io_config_event {
OUTPUT_OPENED,
OUTPUT_CLOSED,
OUTPUT_CONFIG_CHANGED,
INPUT_OPENED,
INPUT_CLOSED,
INPUT_CONFIG_CHANGED,
STREAM_CONFIG_CHANGED,
A2DP_OUTPUT_STATE,
EFFECT_CONFIG_CHANGED,
NUM_CONFIG_EVENTS
};
// audio output descritor used to cache output configurations in client process to avoid frequent calls
// through IAudioFlinger
class OutputDescriptor {
public:
OutputDescriptor()
: samplingRate(0), format(0), channels(0), frameCount(0), latency(0) {}
uint32_t samplingRate;
int32_t format;
int32_t channels;
size_t frameCount;
uint32_t latency;
};
//
// IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
//
static status_t setDeviceConnectionState(audio_devices device, device_connection_state state, const char *device_address);
static device_connection_state getDeviceConnectionState(audio_devices device, const char *device_address);
static status_t setPhoneState(int state);
static status_t setRingerMode(uint32_t mode, uint32_t mask);
static status_t setForceUse(force_use usage, forced_config config);
static forced_config getForceUse(force_use usage);
static audio_io_handle_t getOutput(stream_type stream,
uint32_t samplingRate = 0,
uint32_t format = FORMAT_DEFAULT,
uint32_t channels = CHANNEL_OUT_STEREO,
output_flags flags = OUTPUT_FLAG_INDIRECT);
static audio_io_handle_t getSession(stream_type stream,
uint32_t format = FORMAT_DEFAULT,
output_flags flags = OUTPUT_FLAG_DIRECT,
int32_t sessionId = -1);
static void closeSession(audio_io_handle_t output);
static status_t pauseSession(audio_io_handle_t output, stream_type stream);
static status_t resumeSession(audio_io_handle_t output, stream_type stream);
static status_t startOutput(audio_io_handle_t output,
AudioSystem::stream_type stream,
int session = 0);
static status_t stopOutput(audio_io_handle_t output,
AudioSystem::stream_type stream,
int session = 0);
static void releaseOutput(audio_io_handle_t output);
static audio_io_handle_t getInput(int inputSource,
uint32_t samplingRate = 0,
uint32_t format = FORMAT_DEFAULT,
uint32_t channels = CHANNEL_IN_MONO,
audio_in_acoustics acoustics = (audio_in_acoustics)0);
static status_t startInput(audio_io_handle_t input);
static status_t stopInput(audio_io_handle_t input);
static void releaseInput(audio_io_handle_t input);
static status_t initStreamVolume(stream_type stream,
int indexMin,
int indexMax);
static status_t setStreamVolumeIndex(stream_type stream, int index);
static status_t getStreamVolumeIndex(stream_type stream, int *index);
static uint32_t getStrategyForStream(stream_type stream);
static audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
static status_t registerEffect(effect_descriptor_t *desc,
audio_io_handle_t output,
uint32_t strategy,
int session,
int id);
static status_t unregisterEffect(int id);
static const sp<IAudioPolicyService>& get_audio_policy_service();
// ----------------------------------------------------------------------------
static uint32_t popCount(uint32_t u);
static bool isOutputDevice(audio_devices device);
static bool isInputDevice(audio_devices device);
static bool isA2dpDevice(audio_devices device);
static bool isBluetoothScoDevice(audio_devices device);
static bool isLowVisibility(stream_type stream);
static bool isOutputChannel(uint32_t channel);
static bool isInputChannel(uint32_t channel);
static bool isValidFormat(uint32_t format);
static bool isLinearPCM(uint32_t format);
static bool isModeInCall();
private:
class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
{
public:
AudioFlingerClient() {
}
// DeathRecipient
virtual void binderDied(const wp<IBinder>& who);
// IAudioFlingerClient
// indicate a change in the configuration of an output or input: keeps the cached
// values for output/input parameters upto date in client process
virtual void ioConfigChanged(int event, int ioHandle, void *param2);
};
class AudioPolicyServiceClient: public IBinder::DeathRecipient
{
public:
AudioPolicyServiceClient() {
}
// DeathRecipient
virtual void binderDied(const wp<IBinder>& who);
};
static sp<AudioFlingerClient> gAudioFlingerClient;
static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient;
friend class AudioFlingerClient;
friend class AudioPolicyServiceClient;
static Mutex gLock;
static sp<IAudioFlinger> gAudioFlinger;
static audio_error_callback gAudioErrorCallback;
static size_t gInBuffSize;
// previous parameters for recording buffer size queries
static uint32_t gPrevInSamplingRate;
static int gPrevInFormat;
static int gPrevInChannelCount;
static int gPhoneState;
static sp<IAudioPolicyService> gAudioPolicyService;
// mapping between stream types and outputs
static DefaultKeyedVector<int, audio_io_handle_t> gStreamOutputMap;
// list of output descritor containing cached parameters (sampling rate, framecount, channel count...)
static DefaultKeyedVector<audio_io_handle_t, OutputDescriptor *> gOutputs;
};
class AudioParameter {
public:
AudioParameter() {}
AudioParameter(const String8& keyValuePairs);
virtual ~AudioParameter();
// reserved parameter keys for changing standard parameters with setParameters() function.
// Using these keys is mandatory for AudioFlinger to properly monitor audio output/input
// configuration changes and act accordingly.
// keyRouting: to change audio routing, value is an int in AudioSystem::audio_devices
// keySamplingRate: to change sampling rate routing, value is an int
// keyFormat: to change audio format, value is an int in AudioSystem::audio_format
// keyChannels: to change audio channel configuration, value is an int in AudioSystem::audio_channels
// keyFrameCount: to change audio output frame count, value is an int
// keyInputSource: to change audio input source, value is an int in audio_source
// (defined in media/mediarecorder.h)
static const char *keyRouting;
static const char *keySamplingRate;
static const char *keyFormat;
static const char *keyChannels;
static const char *keyFrameCount;
static const char *keyInputSource;
String8 toString();
status_t add(const String8& key, const String8& value);
status_t addInt(const String8& key, const int value);
status_t addFloat(const String8& key, const float value);
status_t remove(const String8& key);
status_t get(const String8& key, String8& value);
status_t getInt(const String8& key, int& value);
status_t getFloat(const String8& key, float& value);
status_t getAt(size_t index, String8& key, String8& value);
size_t size() { return mParameters.size(); }
private:
String8 mKeyValuePairs;
KeyedVector <String8, String8> mParameters;
};
}; // namespace android
#endif /*ANDROID_AUDIOSYSTEM_H_*/
+517
View File
@@ -0,0 +1,517 @@
/*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_AUDIOTRACK_H
#define ANDROID_AUDIOTRACK_H
#include <stdint.h>
#include <sys/types.h>
#include <media/IAudioFlinger.h>
#include <media/IAudioTrack.h>
#include <media/AudioSystem.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <binder/IMemory.h>
#include <utils/threads.h>
namespace android {
// ----------------------------------------------------------------------------
class audio_track_cblk_t;
// ----------------------------------------------------------------------------
class AudioTrack
{
public:
enum channel_index {
MONO = 0,
LEFT = 0,
RIGHT = 1
};
/* Events used by AudioTrack callback function (audio_track_cblk_t).
*/
enum event_type {
EVENT_MORE_DATA = 0, // Request to write more data to PCM buffer.
EVENT_UNDERRUN = 1, // PCM buffer underrun occured.
EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from loop start if loop count was not 0.
EVENT_MARKER = 3, // Playback head is at the specified marker position (See setMarkerPosition()).
EVENT_NEW_POS = 4, // Playback head is at a new position (See setPositionUpdatePeriod()).
EVENT_BUFFER_END = 5 // Playback head is at the end of the buffer.
};
/* Create Buffer on the stack and pass it to obtainBuffer()
* and releaseBuffer().
*/
class Buffer
{
public:
enum {
MUTE = 0x00000001
};
uint32_t flags;
int channelCount;
int format;
size_t frameCount;
size_t size;
union {
void* raw;
short* i16;
int8_t* i8;
};
};
/* As a convenience, if a callback is supplied, a handler thread
* is automatically created with the appropriate priority. This thread
* invokes the callback when a new buffer becomes availlable or an underrun condition occurs.
* Parameters:
*
* event: type of event notified (see enum AudioTrack::event_type).
* user: Pointer to context for use by the callback receiver.
* info: Pointer to optional parameter according to event type:
* - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
* more bytes than indicated by 'size' field and update 'size' if less bytes are
* written.
* - EVENT_UNDERRUN: unused.
* - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
* - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
* - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
* - EVENT_BUFFER_END: unused.
*/
typedef void (*callback_t)(int event, void* user, void *info);
/* Returns the minimum frame count required for the successful creation of
* an AudioTrack object.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - NO_INIT: audio server or audio hardware not initialized
*/
static status_t getMinFrameCount(int* frameCount,
int streamType =-1,
uint32_t sampleRate = 0);
/* Constructs an uninitialized AudioTrack. No connection with
* AudioFlinger takes place.
*/
AudioTrack();
/* Creates an audio track and registers it with AudioFlinger.
* Once created, the track needs to be started before it can be used.
* Unspecified values are set to the audio hardware's current
* values.
*
* Parameters:
*
* streamType: Select the type of audio stream this track is attached to
* (e.g. AudioSystem::MUSIC).
* sampleRate: Track sampling rate in Hz.
* format: Audio format (e.g AudioSystem::PCM_16_BIT for signed
* 16 bits per sample).
* channels: Channel mask: see AudioSystem::audio_channels.
* frameCount: Total size of track PCM buffer in frames. This defines the
* latency of the track.
* flags: Reserved for future use.
* cbf: Callback function. If not null, this function is called periodically
* to request new PCM data.
* notificationFrames: The callback function is called each time notificationFrames PCM
* frames have been comsumed from track input buffer.
* user Context for use by the callback receiver.
*/
AudioTrack( int streamType,
uint32_t sampleRate = 0,
int format = 0,
int channels = 0,
int frameCount = 0,
uint32_t flags = 0,
callback_t cbf = 0,
void* user = 0,
int notificationFrames = 0,
int sessionId = 0);
/* Creates an audio track and registers it with AudioFlinger. With this constructor,
* The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
* identified by the argument sharedBuffer. This prototype is for static buffer playback.
* PCM data must be present into memory before the AudioTrack is started.
* The Write() and Flush() methods are not supported in this case.
* It is recommented to pass a callback function to be notified of playback end by an
* EVENT_UNDERRUN event.
*/
AudioTrack( int streamType,
uint32_t sampleRate = 0,
int format = 0,
int channels = 0,
const sp<IMemory>& sharedBuffer = 0,
uint32_t flags = 0,
callback_t cbf = 0,
void* user = 0,
int notificationFrames = 0,
int sessionId = 0);
/* Creates an audio track and registers it with AudioFlinger. With this constructor,
* session ID of compressed stream can be registered AudioFlinger and AudioHardware,
* for routing purpose.
*/
AudioTrack( int streamType,
uint32_t sampleRate = 0,
int format = 0,
int channels = 0,
uint32_t flags = 0,
int sessionId = 0,
int lpaSessionId =-1);
/* Terminates the AudioTrack and unregisters it from AudioFlinger.
* Also destroys all resources assotiated with the AudioTrack.
*/
~AudioTrack();
/* Initialize an uninitialized AudioTrack.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful intialization
* - INVALID_OPERATION: AudioTrack is already intitialized
* - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
* - NO_INIT: audio server or audio hardware not initialized
* */
status_t set(int streamType =-1,
uint32_t sampleRate = 0,
int format = 0,
int channels = 0,
int frameCount = 0,
uint32_t flags = 0,
callback_t cbf = 0,
void* user = 0,
int notificationFrames = 0,
const sp<IMemory>& sharedBuffer = 0,
bool threadCanCallJava = false,
int sessionId = 0);
/* Initialize an AudioTrack and registers session Id for Tunneled audio decoding.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful intialization
* - INVALID_OPERATION: AudioTrack is already intitialized
* - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
* - NO_INIT: audio server or audio hardware not initialized
* */
status_t set(int streamType =-1,
uint32_t sampleRate = 0,
int format = 0,
int channels = 0,
uint32_t flags = 0,
int sessionId = 0,
int lpaSessionId =-1);
/* Result of constructing the AudioTrack. This must be checked
* before using any AudioTrack API (except for set()), using
* an uninitialized AudioTrack produces undefined results.
* See set() method above for possible return codes.
*/
status_t initCheck() const;
/* Returns this track's latency in milliseconds.
* This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
* and audio hardware driver.
*/
uint32_t latency() const;
/* getters, see constructor */
int streamType() const;
int format() const;
int channelCount() const;
uint32_t frameCount() const;
int frameSize() const;
sp<IMemory>& sharedBuffer();
/* After it's created the track is not active. Call start() to
* make it active. If set, the callback will start being called.
*/
void start();
/* Stop a track. If set, the callback will cease being called and
* obtainBuffer returns STOPPED. Note that obtainBuffer() still works
* and will fill up buffers until the pool is exhausted.
*/
void stop();
bool stopped() const;
/* flush a stopped track. All pending buffers are discarded.
* This function has no effect if the track is not stoped.
*/
void flush();
/* Pause a track. If set, the callback will cease being called and
* obtainBuffer returns STOPPED. Note that obtainBuffer() still works
* and will fill up buffers until the pool is exhausted.
*/
void pause();
/* mute or unmutes this track.
* While mutted, the callback, if set, is still called.
*/
void mute(bool);
bool muted() const;
/* set volume for this track, mostly used for games' sound effects
* left and right volumes. Levels must be <= 1.0.
*/
status_t setVolume(float left, float right);
void getVolume(float* left, float* right);
/* set the send level for this track. An auxiliary effect should be attached
* to the track with attachEffect(). Level must be <= 1.0.
*/
status_t setAuxEffectSendLevel(float level);
void getAuxEffectSendLevel(float* level);
/* set sample rate for this track, mostly used for games' sound effects
*/
status_t setSampleRate(int sampleRate);
uint32_t getSampleRate();
/* Enables looping and sets the start and end points of looping.
*
* Parameters:
*
* loopStart: loop start expressed as the number of PCM frames played since AudioTrack start.
* loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start.
* loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
* active loop. loopCount = -1 means infinite looping.
*
* For proper operation the following condition must be respected:
* (loopEnd-loopStart) <= framecount()
*/
status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
/* Sets marker position. When playback reaches the number of frames specified, a callback with event
* type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification
* callback.
* If the AudioTrack has been opened with no callback function associated, the operation will fail.
*
* Parameters:
*
* marker: marker position expressed in frames.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioTrack has no callback installed.
*/
status_t setMarkerPosition(uint32_t marker);
status_t getMarkerPosition(uint32_t *marker);
/* Sets position update period. Every time the number of frames specified has been played,
* a callback with event type EVENT_NEW_POS is called.
* Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
* callback.
* If the AudioTrack has been opened with no callback function associated, the operation will fail.
*
* Parameters:
*
* updatePeriod: position update notification period expressed in frames.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioTrack has no callback installed.
*/
status_t setPositionUpdatePeriod(uint32_t updatePeriod);
status_t getPositionUpdatePeriod(uint32_t *updatePeriod);
/* Sets playback head position within AudioTrack buffer. The new position is specified
* in number of frames.
* This method must be called with the AudioTrack in paused or stopped state.
* Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
* Therefore using this method makes sense only when playing a "static" audio buffer
* as opposed to streaming.
* The getPosition() method on the other hand returns the total number of frames played since
* playback start.
*
* Parameters:
*
* position: New playback head position within AudioTrack buffer.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioTrack is not stopped.
* - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
*/
status_t setPosition(uint32_t position);
status_t getPosition(uint32_t *position);
/* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
* rewriting the buffer before restarting playback after a stop.
* This method must be called with the AudioTrack in paused or stopped state.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioTrack is not stopped.
*/
status_t reload();
/* returns a handle on the audio output used by this AudioTrack.
*
* Parameters:
* none.
*
* Returned value:
* handle on audio hardware output
*/
audio_io_handle_t getOutput();
/* returns the unique ID associated to this track.
*
* Parameters:
* none.
*
* Returned value:
* AudioTrack ID.
*/
int getSessionId();
/* Attach track auxiliary output to specified effect. Used effectId = 0
* to detach track from effect.
*
* Parameters:
*
* effectId: effectId obtained from AudioEffect::id().
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the effect is not an auxiliary effect.
* - BAD_VALUE: The specified effect ID is invalid
*/
status_t attachAuxEffect(int effectId);
/* obtains a buffer of "frameCount" frames. The buffer must be
* filled entirely. If the track is stopped, obtainBuffer() returns
* STOPPED instead of NO_ERROR as long as there are buffers availlable,
* at which point NO_MORE_BUFFERS is returned.
* Buffers will be returned until the pool (buffercount())
* is exhausted, at which point obtainBuffer() will either block
* or return WOULD_BLOCK depending on the value of the "blocking"
* parameter.
*/
enum {
NO_MORE_BUFFERS = 0x80000001,
STOPPED = 1
};
status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
void releaseBuffer(Buffer* audioBuffer);
/* As a convenience we provide a write() interface to the audio buffer.
* This is implemented on top of lockBuffer/unlockBuffer. For best
* performance
*
*/
ssize_t write(const void* buffer, size_t size);
/*
* Dumps the state of an audio track.
*/
status_t dump(int fd, const Vector<String16>& args) const;
private:
/* copying audio tracks is not allowed */
AudioTrack(const AudioTrack& other);
AudioTrack& operator = (const AudioTrack& other);
/* a small internal class to handle the callback */
class AudioTrackThread : public Thread
{
public:
AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
private:
friend class AudioTrack;
virtual bool threadLoop();
virtual status_t readyToRun();
virtual void onFirstRef();
AudioTrack& mReceiver;
Mutex mLock;
};
bool processAudioBuffer(const sp<AudioTrackThread>& thread);
status_t createTrack(int streamType,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
const sp<IMemory>& sharedBuffer,
audio_io_handle_t output,
bool enforceFrameCount);
sp<IAudioTrack> mAudioTrack;
sp<IMemory> mCblkMemory;
sp<AudioTrackThread> mAudioTrackThread;
float mVolume[2];
float mSendLevel;
uint32_t mFrameCount;
audio_track_cblk_t* mCblk;
uint8_t mStreamType;
uint8_t mFormat;
uint8_t mChannelCount;
uint8_t mMuted;
uint32_t mChannels;
status_t mStatus;
uint32_t mLatency;
volatile int32_t mActive;
callback_t mCbf;
void* mUserData;
uint32_t mNotificationFramesReq; // requested number of frames between each notification callback
uint32_t mNotificationFramesAct; // actual number of frames between each notification callback
sp<IMemory> mSharedBuffer;
int mLoopCount;
uint32_t mRemainingFrames;
uint32_t mMarkerPosition;
bool mMarkerReached;
uint32_t mNewPosition;
uint32_t mUpdatePeriod;
uint32_t mFlags;
audio_io_handle_t mAudioSession;
int mSessionId;
int mAuxEffectId;
};
}; // namespace android
#endif // ANDROID_AUDIOTRACK_H
+802
View File
@@ -0,0 +1,802 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTAPI_H_
#define ANDROID_EFFECTAPI_H_
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#if __cplusplus
extern "C" {
#endif
/////////////////////////////////////////////////
// Effect control interface
/////////////////////////////////////////////////
// The effect control interface is exposed by each effect engine implementation. It consists of
// a set of functions controlling the configuration, activation and process of the engine.
// The functions are grouped in a structure of type effect_interface_s:
// struct effect_interface_s {
// effect_process_t process;
// effect_command_t command;
// };
// effect_interface_t: Effect control interface handle.
// The effect_interface_t serves two purposes regarding the implementation of the effect engine:
// - 1 it is the address of a pointer to an effect_interface_s structure where the functions
// of the effect control API for a particular effect are located.
// - 2 it is the address of the context of a particular effect instance.
// A typical implementation in the effect library would define a structure as follows:
// struct effect_module_s {
// const struct effect_interface_s *itfe;
// effect_config_t config;
// effect_context_t context;
// }
// The implementation of EffectCreate() function would then allocate a structure of this
// type and return its address as effect_interface_t
typedef struct effect_interface_s **effect_interface_t;
// Effect API version 1.0
#define EFFECT_API_VERSION 0x0100 // Format 0xMMmm MM: Major version, mm: minor version
// Maximum length of character strings in structures defines by this API.
#define EFFECT_STRING_LEN_MAX 64
//
//--- Effect descriptor structure effect_descriptor_t
//
// Unique effect ID (can be generated from the following site:
// http://www.itu.int/ITU-T/asn1/uuid.html)
// This format is used for both "type" and "uuid" fields of the effect descriptor structure.
// - When used for effect type and the engine is implementing and effect corresponding to a standard
// OpenSL ES interface, this ID must be the one defined in OpenSLES_IID.h for that interface.
// - When used as uuid, it should be a unique UUID for this particular implementation.
typedef struct effect_uuid_s {
uint32_t timeLow;
uint16_t timeMid;
uint16_t timeHiAndVersion;
uint16_t clockSeq;
uint8_t node[6];
} effect_uuid_t;
// NULL UUID definition (matches SL_IID_NULL_)
#define EFFECT_UUID_INITIALIZER { 0xec7178ec, 0xe5e1, 0x4432, 0xa3f4, \
{ 0x46, 0x57, 0xe6, 0x79, 0x52, 0x10 } }
static const effect_uuid_t EFFECT_UUID_NULL_ = EFFECT_UUID_INITIALIZER;
const effect_uuid_t * const EFFECT_UUID_NULL = &EFFECT_UUID_NULL_;
const char * const EFFECT_UUID_NULL_STR = "ec7178ec-e5e1-4432-a3f4-4657e6795210";
// The effect descriptor contains necessary information to facilitate the enumeration of the effect
// engines present in a library.
typedef struct effect_descriptor_s {
effect_uuid_t type; // UUID of to the OpenSL ES interface implemented by this effect
effect_uuid_t uuid; // UUID for this particular implementation
uint16_t apiVersion; // Version of the effect API implemented: matches EFFECT_API_VERSION
uint32_t flags; // effect engine capabilities/requirements flags (see below)
uint16_t cpuLoad; // CPU load indication (see below)
uint16_t memoryUsage; // Data Memory usage (see below)
char name[EFFECT_STRING_LEN_MAX]; // human readable effect name
char implementor[EFFECT_STRING_LEN_MAX]; // human readable effect implementor name
} effect_descriptor_t;
// CPU load and memory usage indication: each effect implementation must provide an indication of
// its CPU and memory usage for the audio effect framework to limit the number of effects
// instantiated at a given time on a given platform.
// The CPU load is expressed in 0.1 MIPS units as estimated on an ARM9E core (ARMv5TE) with 0 WS.
// The memory usage is expressed in KB and includes only dynamically allocated memory
// Definitions for flags field of effect descriptor.
// +---------------------------+-----------+-----------------------------------
// | description | bits | values
// +---------------------------+-----------+-----------------------------------
// | connection mode | 0..1 | 0 insert: after track process
// | | | 1 auxiliary: connect to track auxiliary
// | | | output and use send level
// | | | 2 replace: replaces track process function;
// | | | must implement SRC, volume and mono to stereo.
// | | | 3 reserved
// +---------------------------+-----------+-----------------------------------
// | insertion preference | 2..4 | 0 none
// | | | 1 first of the chain
// | | | 2 last of the chain
// | | | 3 exclusive (only effect in the insert chain)
// | | | 4..7 reserved
// +---------------------------+-----------+-----------------------------------
// | Volume management | 5..6 | 0 none
// | | | 1 implements volume control
// | | | 2 requires volume indication
// | | | 3 reserved
// +---------------------------+-----------+-----------------------------------
// | Device indication | 7..8 | 0 none
// | | | 1 requires device updates
// | | | 2..3 reserved
// +---------------------------+-----------+-----------------------------------
// | Sample input mode | 9..10 | 0 direct: process() function or EFFECT_CMD_CONFIGURE
// | | | command must specify a buffer descriptor
// | | | 1 provider: process() function uses the
// | | | bufferProvider indicated by the
// | | | EFFECT_CMD_CONFIGURE command to request input.
// | | | buffers.
// | | | 2 both: both input modes are supported
// | | | 3 reserved
// +---------------------------+-----------+-----------------------------------
// | Sample output mode | 11..12 | 0 direct: process() function or EFFECT_CMD_CONFIGURE
// | | | command must specify a buffer descriptor
// | | | 1 provider: process() function uses the
// | | | bufferProvider indicated by the
// | | | EFFECT_CMD_CONFIGURE command to request output
// | | | buffers.
// | | | 2 both: both output modes are supported
// | | | 3 reserved
// +---------------------------+-----------+-----------------------------------
// | Hardware acceleration | 13..15 | 0 No hardware acceleration
// | | | 1 non tunneled hw acceleration: the process() function
// | | | reads the samples, send them to HW accelerated
// | | | effect processor, reads back the processed samples
// | | | and returns them to the output buffer.
// | | | 2 tunneled hw acceleration: the process() function is
// | | | transparent. The effect interface is only used to
// | | | control the effect engine. This mode is relevant for
// | | | global effects actually applied by the audio
// | | | hardware on the output stream.
// +---------------------------+-----------+-----------------------------------
// | Audio Mode indication | 16..17 | 0 none
// | | | 1 requires audio mode updates
// | | | 2..3 reserved
// +---------------------------+-----------+-----------------------------------
// Insert mode
#define EFFECT_FLAG_TYPE_MASK 0x00000003
#define EFFECT_FLAG_TYPE_INSERT 0x00000000
#define EFFECT_FLAG_TYPE_AUXILIARY 0x00000001
#define EFFECT_FLAG_TYPE_REPLACE 0x00000002
// Insert preference
#define EFFECT_FLAG_INSERT_MASK 0x0000001C
#define EFFECT_FLAG_INSERT_ANY 0x00000000
#define EFFECT_FLAG_INSERT_FIRST 0x00000004
#define EFFECT_FLAG_INSERT_LAST 0x00000008
#define EFFECT_FLAG_INSERT_EXCLUSIVE 0x0000000C
// Volume control
#define EFFECT_FLAG_VOLUME_MASK 0x00000060
#define EFFECT_FLAG_VOLUME_CTRL 0x00000020
#define EFFECT_FLAG_VOLUME_IND 0x00000040
#define EFFECT_FLAG_VOLUME_NONE 0x00000000
// Device indication
#define EFFECT_FLAG_DEVICE_MASK 0x00000180
#define EFFECT_FLAG_DEVICE_IND 0x00000080
#define EFFECT_FLAG_DEVICE_NONE 0x00000000
// Sample input modes
#define EFFECT_FLAG_INPUT_MASK 0x00000600
#define EFFECT_FLAG_INPUT_DIRECT 0x00000000
#define EFFECT_FLAG_INPUT_PROVIDER 0x00000200
#define EFFECT_FLAG_INPUT_BOTH 0x00000400
// Sample output modes
#define EFFECT_FLAG_OUTPUT_MASK 0x00001800
#define EFFECT_FLAG_OUTPUT_DIRECT 0x00000000
#define EFFECT_FLAG_OUTPUT_PROVIDER 0x00000800
#define EFFECT_FLAG_OUTPUT_BOTH 0x00001000
// Hardware acceleration mode
#define EFFECT_FLAG_HW_ACC_MASK 0x00006000
#define EFFECT_FLAG_HW_ACC_SIMPLE 0x00002000
#define EFFECT_FLAG_HW_ACC_TUNNEL 0x00004000
// Audio mode indication
#define EFFECT_FLAG_AUDIO_MODE_MASK 0x00018000
#define EFFECT_FLAG_AUDIO_MODE_IND 0x00008000
#define EFFECT_FLAG_AUDIO_MODE_NONE 0x00000000
// Forward definition of type audio_buffer_t
typedef struct audio_buffer_s audio_buffer_t;
////////////////////////////////////////////////////////////////////////////////
//
// Function: process
//
// Description: Effect process function. Takes input samples as specified
// (count and location) in input buffer descriptor and output processed
// samples as specified in output buffer descriptor. If the buffer descriptor
// is not specified the function must use either the buffer or the
// buffer provider function installed by the EFFECT_CMD_CONFIGURE command.
// The effect framework will call the process() function after the EFFECT_CMD_ENABLE
// command is received and until the EFFECT_CMD_DISABLE is received. When the engine
// receives the EFFECT_CMD_DISABLE command it should turn off the effect gracefully
// and when done indicate that it is OK to stop calling the process() function by
// returning the -ENODATA status.
//
// NOTE: the process() function implementation should be "real-time safe" that is
// it should not perform blocking calls: malloc/free, sleep, read/write/open/close,
// pthread_cond_wait/pthread_mutex_lock...
//
// Input:
// effect_interface_t: handle to the effect interface this function
// is called on.
// inBuffer: buffer descriptor indicating where to read samples to process.
// If NULL, use the configuration passed by EFFECT_CMD_CONFIGURE command.
//
// inBuffer: buffer descriptor indicating where to write processed samples.
// If NULL, use the configuration passed by EFFECT_CMD_CONFIGURE command.
//
// Output:
// returned value: 0 successful operation
// -ENODATA the engine has finished the disable phase and the framework
// can stop calling process()
// -EINVAL invalid interface handle or
// invalid input/output buffer description
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_process_t)(effect_interface_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer);
////////////////////////////////////////////////////////////////////////////////
//
// Function: command
//
// Description: Send a command and receive a response to/from effect engine.
//
// Input:
// effect_interface_t: handle to the effect interface this function
// is called on.
// cmdCode: command code: the command can be a standardized command defined in
// effect_command_e (see below) or a proprietary command.
// cmdSize: size of command in bytes
// pCmdData: pointer to command data
// pReplyData: pointer to reply data
//
// Input/Output:
// replySize: maximum size of reply data as input
// actual size of reply data as output
//
// Output:
// returned value: 0 successful operation
// -EINVAL invalid interface handle or
// invalid command/reply size or format according to command code
// The return code should be restricted to indicate problems related to the this
// API specification. Status related to the execution of a particular command should be
// indicated as part of the reply field.
//
// *pReplyData updated with command response
//
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_command_t)(effect_interface_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData);
// Effect control interface definition
struct effect_interface_s {
effect_process_t process;
effect_command_t command;
};
//
//--- Standardized command codes for command() function
//
enum effect_command_e {
EFFECT_CMD_INIT, // initialize effect engine
EFFECT_CMD_CONFIGURE, // configure effect engine (see effect_config_t)
EFFECT_CMD_RESET, // reset effect engine
EFFECT_CMD_ENABLE, // enable effect process
EFFECT_CMD_DISABLE, // disable effect process
EFFECT_CMD_SET_PARAM, // set parameter immediately (see effect_param_t)
EFFECT_CMD_SET_PARAM_DEFERRED, // set parameter deferred
EFFECT_CMD_SET_PARAM_COMMIT, // commit previous set parameter deferred
EFFECT_CMD_GET_PARAM, // get parameter
EFFECT_CMD_SET_DEVICE, // set audio device (see audio_device_e)
EFFECT_CMD_SET_VOLUME, // set volume
EFFECT_CMD_SET_AUDIO_MODE, // set the audio mode (normal, ring, ...)
EFFECT_CMD_FIRST_PROPRIETARY = 0x10000 // first proprietary command code
};
//==================================================================================================
// command: EFFECT_CMD_INIT
//--------------------------------------------------------------------------------------------------
// description:
// Initialize effect engine: All configurations return to default
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_CONFIGURE
//--------------------------------------------------------------------------------------------------
// description:
// Apply new audio parameters configurations for input and output buffers
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_config_t)
// data: effect_config_t
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_RESET
//--------------------------------------------------------------------------------------------------
// description:
// Reset the effect engine. Keep configuration but resets state and buffer content
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_ENABLE
//--------------------------------------------------------------------------------------------------
// description:
// Enable the process. Called by the framework before the first call to process()
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_DISABLE
//--------------------------------------------------------------------------------------------------
// description:
// Disable the process. Called by the framework after the last call to process()
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_PARAM
//--------------------------------------------------------------------------------------------------
// description:
// Set a parameter and apply it immediately
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_param_t) + size of param and value
// data: effect_param_t + param + value. See effect_param_t definition below for value offset
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_SET_PARAM_DEFERRED
//--------------------------------------------------------------------------------------------------
// description:
// Set a parameter but apply it only when receiving EFFECT_CMD_SET_PARAM_COMMIT command
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_param_t) + size of param and value
// data: effect_param_t + param + value. See effect_param_t definition below for value offset
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_SET_PARAM_COMMIT
//--------------------------------------------------------------------------------------------------
// description:
// Apply all previously received EFFECT_CMD_SET_PARAM_DEFERRED commands
//--------------------------------------------------------------------------------------------------
// command format:
// size: 0
// data: N/A
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(int)
// data: status
//==================================================================================================
// command: EFFECT_CMD_GET_PARAM
//--------------------------------------------------------------------------------------------------
// description:
// Get a parameter value
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(effect_param_t) + size of param
// data: effect_param_t + param
//--------------------------------------------------------------------------------------------------
// reply format:
// size: sizeof(effect_param_t) + size of param and value
// data: effect_param_t + param + value. See effect_param_t definition below for value offset
//==================================================================================================
// command: EFFECT_CMD_SET_DEVICE
//--------------------------------------------------------------------------------------------------
// description:
// Set the rendering device the audio output path is connected to. See audio_device_e for device
// values.
// The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this
// command when the device changes
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: audio_device_e
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_SET_VOLUME
//--------------------------------------------------------------------------------------------------
// description:
// Set and get volume. Used by audio framework to delegate volume control to effect engine.
// The effect implementation must set EFFECT_FLAG_VOLUME_IND or EFFECT_FLAG_VOLUME_CTRL flag in
// its descriptor to receive this command before every call to process() function
// If EFFECT_FLAG_VOLUME_CTRL flag is set in the effect descriptor, the effect engine must return
// the volume that should be applied before the effect is processed. The overall volume (the volume
// actually applied by the effect engine multiplied by the returned value) should match the value
// indicated in the command.
//--------------------------------------------------------------------------------------------------
// command format:
// size: n * sizeof(uint32_t)
// data: volume for each channel defined in effect_config_t for output buffer expressed in
// 8.24 fixed point format
//--------------------------------------------------------------------------------------------------
// reply format:
// size: n * sizeof(uint32_t) / 0
// data: - if EFFECT_FLAG_VOLUME_CTRL is set in effect descriptor:
// volume for each channel defined in effect_config_t for output buffer expressed in
// 8.24 fixed point format
// - if EFFECT_FLAG_VOLUME_CTRL is not set in effect descriptor:
// N/A
// It is legal to receive a null pointer as pReplyData in which case the effect framework has
// delegated volume control to another effect
//==================================================================================================
// command: EFFECT_CMD_SET_AUDIO_MODE
//--------------------------------------------------------------------------------------------------
// description:
// Set the audio mode. The effect implementation must set EFFECT_FLAG_AUDIO_MODE_IND flag in its
// descriptor to receive this command when the audio mode changes.
//--------------------------------------------------------------------------------------------------
// command format:
// size: sizeof(uint32_t)
// data: audio_mode_e
//--------------------------------------------------------------------------------------------------
// reply format:
// size: 0
// data: N/A
//==================================================================================================
// command: EFFECT_CMD_FIRST_PROPRIETARY
//--------------------------------------------------------------------------------------------------
// description:
// All proprietary effect commands must use command codes above this value. The size and format of
// command and response fields is free in this case
//==================================================================================================
// Audio buffer descriptor used by process(), bufferProvider() functions and buffer_config_t
// structure. Multi-channel audio is always interleaved. The channel order is from LSB to MSB with
// regard to the channel mask definition in audio_channels_e e.g :
// Stereo: left, right
// 5 point 1: front left, front right, front center, low frequency, back left, back right
// The buffer size is expressed in frame count, a frame being composed of samples for all
// channels at a given time. Frame size for unspecified format (AUDIO_FORMAT_OTHER) is 8 bit by
// definition
struct audio_buffer_s {
size_t frameCount; // number of frames in buffer
union {
void* raw; // raw pointer to start of buffer
int32_t* s32; // pointer to signed 32 bit data at start of buffer
int16_t* s16; // pointer to signed 16 bit data at start of buffer
uint8_t* u8; // pointer to unsigned 8 bit data at start of buffer
};
};
// The buffer_provider_s structure contains functions that can be used
// by the effect engine process() function to query and release input
// or output audio buffer.
// The getBuffer() function is called to retrieve a buffer where data
// should read from or written to by process() function.
// The releaseBuffer() function MUST be called when the buffer retrieved
// with getBuffer() is not needed anymore.
// The process function should use the buffer provider mechanism to retrieve
// input or output buffer if the inBuffer or outBuffer passed as argument is NULL
// and the buffer configuration (buffer_config_t) given by the EFFECT_CMD_CONFIGURE
// command did not specify an audio buffer.
typedef int32_t (* buffer_function_t)(void *cookie, audio_buffer_t *buffer);
typedef struct buffer_provider_s {
buffer_function_t getBuffer; // retrieve next buffer
buffer_function_t releaseBuffer; // release used buffer
void *cookie; // for use by client of buffer provider functions
} buffer_provider_t;
// The buffer_config_s structure specifies the input or output audio format
// to be used by the effect engine. It is part of the effect_config_t
// structure that defines both input and output buffer configurations and is
// passed by the EFFECT_CMD_CONFIGURE command.
typedef struct buffer_config_s {
audio_buffer_t buffer; // buffer for use by process() function if not passed explicitly
uint32_t samplingRate; // sampling rate
uint32_t channels; // channel mask (see audio_channels_e)
buffer_provider_t bufferProvider; // buffer provider
uint8_t format; // Audio format (see audio_format_e)
uint8_t accessMode; // read/write or accumulate in buffer (effect_buffer_access_e)
uint16_t mask; // indicates which of the above fields is valid
} buffer_config_t;
// Sample format
enum audio_format_e {
SAMPLE_FORMAT_PCM_S15, // PCM signed 16 bits
SAMPLE_FORMAT_PCM_U8, // PCM unsigned 8 bits
SAMPLE_FORMAT_PCM_S7_24, // PCM signed 7.24 fixed point representation
SAMPLE_FORMAT_OTHER // other format (e.g. compressed)
};
// Channel mask
enum audio_channels_e {
CHANNEL_FRONT_LEFT = 0x1, // front left channel
CHANNEL_FRONT_RIGHT = 0x2, // front right channel
CHANNEL_FRONT_CENTER = 0x4, // front center channel
CHANNEL_LOW_FREQUENCY = 0x8, // low frequency channel
CHANNEL_BACK_LEFT = 0x10, // back left channel
CHANNEL_BACK_RIGHT = 0x20, // back right channel
CHANNEL_FRONT_LEFT_OF_CENTER = 0x40, // front left of center channel
CHANNEL_FRONT_RIGHT_OF_CENTER = 0x80, // front right of center channel
CHANNEL_BACK_CENTER = 0x100, // back center channel
CHANNEL_MONO = CHANNEL_FRONT_LEFT,
CHANNEL_STEREO = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT),
CHANNEL_QUAD = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT),
CHANNEL_SURROUND = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER),
CHANNEL_5POINT1 = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT),
CHANNEL_7POINT1 = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT |
CHANNEL_FRONT_LEFT_OF_CENTER | CHANNEL_FRONT_RIGHT_OF_CENTER),
};
// Match this table with AudioSystem::audio_devices
// Render device
enum audio_device_e {
DEVICE_EARPIECE = 0x1, // earpiece
DEVICE_SPEAKER = 0x2, // speaker
DEVICE_WIRED_HEADSET = 0x4, // wired headset, with microphone
DEVICE_WIRED_HEADPHONE = 0x8, // wired headphone, without microphone
DEVICE_BLUETOOTH_SCO = 0x10, // generic bluetooth SCO
DEVICE_BLUETOOTH_SCO_HEADSET = 0x20, // bluetooth SCO headset
DEVICE_BLUETOOTH_SCO_CARKIT = 0x40, // bluetooth SCO car kit
DEVICE_BLUETOOTH_A2DP = 0x80, // generic bluetooth A2DP
DEVICE_BLUETOOTH_A2DP_HEADPHONES = 0x100, // bluetooth A2DP headphones
DEVICE_BLUETOOTH_A2DP_SPEAKER = 0x200, // bluetooth A2DP speakers
DEVICE_AUX_DIGITAL = 0x400, // digital output
DEVICE_AUX_HDMI = 0x800,
DEVICE_FM = 0x1000,
DEVICE_ANC_HEADSET = 0x2000,
DEVICE_ANC_HEADPHONE = 0x4000,
DEVICE_FM_TX = 0x8000,
};
// Audio mode
enum audio_mode_e {
AUDIO_MODE_NORMAL, // device idle
AUDIO_MODE_RINGTONE, // device ringing
AUDIO_MODE_IN_CALL // audio call connected (VoIP or telephony)
};
// Values for "accessMode" field of buffer_config_t:
// overwrite, read only, accumulate (read/modify/write)
enum effect_buffer_access_e {
EFFECT_BUFFER_ACCESS_WRITE,
EFFECT_BUFFER_ACCESS_READ,
EFFECT_BUFFER_ACCESS_ACCUMULATE
};
// Values for bit field "mask" in buffer_config_t. If a bit is set, the corresponding field
// in buffer_config_t must be taken into account when executing the EFFECT_CMD_CONFIGURE command
#define EFFECT_CONFIG_BUFFER 0x0001 // buffer field must be taken into account
#define EFFECT_CONFIG_SMP_RATE 0x0002 // samplingRate field must be taken into account
#define EFFECT_CONFIG_CHANNELS 0x0004 // channels field must be taken into account
#define EFFECT_CONFIG_FORMAT 0x0008 // format field must be taken into account
#define EFFECT_CONFIG_ACC_MODE 0x0010 // accessMode field must be taken into account
#define EFFECT_CONFIG_PROVIDER 0x0020 // bufferProvider field must be taken into account
#define EFFECT_CONFIG_ALL (EFFECT_CONFIG_BUFFER | EFFECT_CONFIG_SMP_RATE | \
EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT | \
EFFECT_CONFIG_ACC_MODE | EFFECT_CONFIG_PROVIDER)
// effect_config_s structure describes the format of the pCmdData argument of EFFECT_CMD_CONFIGURE
// command to configure audio parameters and buffers for effect engine input and output.
typedef struct effect_config_s {
buffer_config_t inputCfg;
buffer_config_t outputCfg;;
} effect_config_t;
// effect_param_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_PARAM
// command and pCmdData and pReplyData of EFFECT_CMD_GET_PARAM command.
// psize and vsize represent the actual size of parameter and value.
//
// NOTE: the start of value field inside the data field is always on a 32 bit boundary:
//
// +-----------+
// | status | sizeof(int)
// +-----------+
// | psize | sizeof(int)
// +-----------+
// | vsize | sizeof(int)
// +-----------+
// | | | |
// ~ parameter ~ > psize |
// | | | > ((psize - 1)/sizeof(int) + 1) * sizeof(int)
// +-----------+ |
// | padding | |
// +-----------+
// | | |
// ~ value ~ > vsize
// | | |
// +-----------+
typedef struct effect_param_s {
int32_t status; // Transaction status (unused for command, used for reply)
uint32_t psize; // Parameter size
uint32_t vsize; // Value size
char data[]; // Start of Parameter + Value data
} effect_param_t;
/////////////////////////////////////////////////
// Effect library interface
/////////////////////////////////////////////////
// An effect library is required to implement and expose the following functions
// to enable effect enumeration and instantiation. The name of these functions must be as
// specified here as the effect framework will get the function address with dlsym():
//
// - effect_QueryNumberEffects_t EffectQueryNumberEffects;
// - effect_QueryEffect_t EffectQueryEffect;
// - effect_CreateEffect_t EffectCreate;
// - effect_ReleaseEffect_t EffectRelease;
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectQueryNumberEffects
//
// Description: Returns the number of different effects exposed by the
// library. Each effect must have a unique effect uuid (see
// effect_descriptor_t). This function together with EffectQueryEffect()
// is used to enumerate all effects present in the library.
//
// Input/Output:
// pNumEffects: address where the number of effects should be returned.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid pNumEffects
// *pNumEffects: updated with number of effects in library
//
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_QueryNumberEffects_t)(uint32_t *pNumEffects);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectQueryEffect
//
// Description: Returns the descriptor of the effect engine which index is
// given as first argument.
// See effect_descriptor_t for details on effect descriptors.
// This function together with EffectQueryNumberEffects() is used to enumerate all
// effects present in the library. The enumeration sequence is:
// EffectQueryNumberEffects(&num_effects);
// for (i = 0; i < num_effects; i++)
// EffectQueryEffect(i,...);
//
// Input/Output:
// index: index of the effect
// pDescriptor: address where to return the effect descriptor.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid pDescriptor or index
// -ENOSYS effect list has changed since last execution of
// EffectQueryNumberEffects()
// -ENOENT no more effect available
// *pDescriptor: updated with the effect descriptor.
//
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_QueryEffect_t)(uint32_t index,
effect_descriptor_t *pDescriptor);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectCreate
//
// Description: Creates an effect engine of the specified type and returns an
// effect control interface on this engine. The function will allocate the
// resources for an instance of the requested effect engine and return
// a handle on the effect control interface.
//
// Input:
// uuid: pointer to the effect uuid.
// sessionId: audio session to which this effect instance will be attached. All effects
// created with the same session ID are connected in series and process the same signal
// stream. Knowing that two effects are part of the same effect chain can help the
// library implement some kind of optimizations.
// ioId: identifies the output or input stream this effect is directed to at audio HAL.
// For future use especially with tunneled HW accelerated effects
//
// Input/Output:
// pInterface: address where to return the effect interface.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid pEffectUuid or pInterface
// -ENOENT no effect with this uuid found
// *pInterface: updated with the effect interface handle.
//
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_CreateEffect_t)(effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_interface_t *pInterface);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectRelease
//
// Description: Releases the effect engine whose handle is given as argument.
// All resources allocated to this particular instance of the effect are
// released.
//
// Input:
// interface: handle on the effect interface to be released.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV library failed to initialize
// -EINVAL invalid interface handle
//
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_ReleaseEffect_t)(effect_interface_t interface);
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTAPI_H_*/
+43
View File
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTBASSBOOSTAPI_H_
#define ANDROID_EFFECTBASSBOOSTAPI_H_
#include <media/EffectApi.h>
#if __cplusplus
extern "C" {
#endif
#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_BASSBOOST_ = { 0x0634f220, 0xddd4, 0x11db, 0xa0fc, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_BASSBOOST = &SL_IID_BASSBOOST_;
#endif //OPENSL_ES_H_
/* enumerated parameter settings for BassBoost effect */
typedef enum
{
BASSBOOST_PARAM_STRENGTH_SUPPORTED,
BASSBOOST_PARAM_STRENGTH
} t_bassboost_params;
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTBASSBOOSTAPI_H_*/
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTENVIRONMENTALREVERBAPI_H_
#define ANDROID_EFFECTENVIRONMENTALREVERBAPI_H_
#include <media/EffectApi.h>
#if __cplusplus
extern "C" {
#endif
#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_ENVIRONMENTALREVERB_ = { 0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, { 0x4e, 0x23, 0x4d, 0x6, 0x83, 0x9e } };
const effect_uuid_t * const SL_IID_ENVIRONMENTALREVERB = &SL_IID_ENVIRONMENTALREVERB_;
#endif //OPENSL_ES_H_
/* enumerated parameter settings for environmental reverb effect */
typedef enum
{
// Parameters below are as defined in OpenSL ES specification for environmental reverb interface
REVERB_PARAM_ROOM_LEVEL, // in millibels, range -6000 to 0
REVERB_PARAM_ROOM_HF_LEVEL, // in millibels, range -4000 to 0
REVERB_PARAM_DECAY_TIME, // in milliseconds, range 100 to 20000
REVERB_PARAM_DECAY_HF_RATIO, // in permilles, range 100 to 1000
REVERB_PARAM_REFLECTIONS_LEVEL, // in millibels, range -6000 to 0
REVERB_PARAM_REFLECTIONS_DELAY, // in milliseconds, range 0 to 65
REVERB_PARAM_REVERB_LEVEL, // in millibels, range -6000 to 0
REVERB_PARAM_REVERB_DELAY, // in milliseconds, range 0 to 65
REVERB_PARAM_DIFFUSION, // in permilles, range 0 to 1000
REVERB_PARAM_DENSITY, // in permilles, range 0 to 1000
REVERB_PARAM_PROPERTIES,
REVERB_PARAM_BYPASS
} t_env_reverb_params;
//t_reverb_settings is equal to SLEnvironmentalReverbSettings defined in OpenSL ES specification.
typedef struct s_reverb_settings {
int16_t roomLevel;
int16_t roomHFLevel;
uint32_t decayTime;
int16_t decayHFRatio;
int16_t reflectionsLevel;
uint32_t reflectionsDelay;
int16_t reverbLevel;
uint32_t reverbDelay;
int16_t diffusion;
int16_t density;
} __attribute__((packed)) t_reverb_settings;
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTENVIRONMENTALREVERBAPI_H_*/
+58
View File
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTEQUALIZERAPI_H_
#define ANDROID_EFFECTEQUALIZERAPI_H_
#include <media/EffectApi.h>
#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_EQUALIZER_ = { 0x0bed4300, 0xddd6, 0x11db, 0x8f34, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_EQUALIZER = &SL_IID_EQUALIZER_;
#endif //OPENSL_ES_H_
#if __cplusplus
extern "C" {
#endif
/* enumerated parameters for Equalizer effect */
typedef enum
{
EQ_PARAM_NUM_BANDS, // Gets the number of frequency bands that the equalizer supports.
EQ_PARAM_LEVEL_RANGE, // Returns the minimum and maximum band levels supported.
EQ_PARAM_BAND_LEVEL, // Gets/Sets the gain set for the given equalizer band.
EQ_PARAM_CENTER_FREQ, // Gets the center frequency of the given band.
EQ_PARAM_BAND_FREQ_RANGE, // Gets the frequency range of the given frequency band.
EQ_PARAM_GET_BAND, // Gets the band that has the most effect on the given frequency.
EQ_PARAM_CUR_PRESET, // Gets/Sets the current preset.
EQ_PARAM_GET_NUM_OF_PRESETS, // Gets the total number of presets the equalizer supports.
EQ_PARAM_GET_PRESET_NAME, // Gets the preset name based on the index.
EQ_PARAM_PROPERTIES // Gets/Sets all parameters at a time.
} t_equalizer_params;
//t_equalizer_settings groups all current equalizer setting for backup and restore.
typedef struct s_equalizer_settings {
uint16_t curPreset;
uint16_t numBands;
uint16_t bandLevels[];
} t_equalizer_settings;
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTEQUALIZERAPI_H_*/
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTPRESETREVERBAPI_H_
#define ANDROID_EFFECTPRESETREVERBAPI_H_
#include <media/EffectApi.h>
#if __cplusplus
extern "C" {
#endif
#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_PRESETREVERB_ = { 0x47382d60, 0xddd8, 0x11db, 0xbf3a, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_PRESETREVERB = &SL_IID_PRESETREVERB_;
#endif //OPENSL_ES_H_
/* enumerated parameter settings for preset reverb effect */
typedef enum
{
REVERB_PARAM_PRESET
} t_preset_reverb_params;
typedef enum
{
REVERB_PRESET_NONE,
REVERB_PRESET_SMALLROOM,
REVERB_PRESET_MEDIUMROOM,
REVERB_PRESET_LARGEROOM,
REVERB_PRESET_MEDIUMHALL,
REVERB_PRESET_LARGEHALL,
REVERB_PRESET_PLATE,
REVERB_PRESET_LAST = REVERB_PRESET_PLATE
} t_reverb_presets;
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTPRESETREVERBAPI_H_*/
+43
View File
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTVIRTUALIZERAPI_H_
#define ANDROID_EFFECTVIRTUALIZERAPI_H_
#include <media/EffectApi.h>
#if __cplusplus
extern "C" {
#endif
#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_VIRTUALIZER_ = { 0x37cc2c00, 0xdddd, 0x11db, 0x8577, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_VIRTUALIZER = &SL_IID_VIRTUALIZER_;
#endif //OPENSL_ES_H_
/* enumerated parameter settings for virtualizer effect */
typedef enum
{
VIRTUALIZER_PARAM_STRENGTH_SUPPORTED,
VIRTUALIZER_PARAM_STRENGTH
} t_virtualizer_params;
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTVIRTUALIZERAPI_H_*/
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTVISUALIZERAPI_H_
#define ANDROID_EFFECTVISUALIZERAPI_H_
#include <media/EffectApi.h>
#if __cplusplus
extern "C" {
#endif
#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_VISUALIZATION_ =
{ 0xe46b26a0, 0xdddd, 0x11db, 0x8afd, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_VISUALIZATION = &SL_IID_VISUALIZATION_;
#endif //OPENSL_ES_H_
#define VISUALIZER_CAPTURE_SIZE_MAX 1024 // maximum capture size in samples
#define VISUALIZER_CAPTURE_SIZE_MIN 128 // minimum capture size in samples
/* enumerated parameters for Visualizer effect */
typedef enum
{
VISU_PARAM_CAPTURE_SIZE, // Sets the number PCM samples in the capture.
} t_visualizer_params;
/* commands */
typedef enum
{
VISU_CMD_CAPTURE = EFFECT_CMD_FIRST_PROPRIETARY, // Gets the latest PCM capture.
}t_visualizer_cmds;
// VISU_CMD_CAPTURE retrieves the latest PCM snapshot captured by the visualizer engine.
// It returns the number of samples specified by VISU_PARAM_CAPTURE_SIZE
// in 8 bit unsigned format (0 = 0x80)
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTVISUALIZERAPI_H_*/
+221
View File
@@ -0,0 +1,221 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_EFFECTSFACTORYAPI_H_
#define ANDROID_EFFECTSFACTORYAPI_H_
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#include <media/EffectApi.h>
#if __cplusplus
extern "C" {
#endif
/////////////////////////////////////////////////
// Effect factory interface
/////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectQueryNumberEffects
//
// Description: Returns the number of different effects in all loaded libraries.
// Each effect must have a different effect uuid (see
// effect_descriptor_t). This function together with EffectQueryEffect()
// is used to enumerate all effects present in all loaded libraries.
// Each time EffectQueryNumberEffects() is called, the factory must
// reset the index of the effect descriptor returned by next call to
// EffectQueryEffect() to restart enumeration from the beginning.
//
// Input/Output:
// pNumEffects: address where the number of effects should be returned.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV factory failed to initialize
// -EINVAL invalid pNumEffects
// *pNumEffects: updated with number of effects in factory
//
////////////////////////////////////////////////////////////////////////////////
int EffectQueryNumberEffects(uint32_t *pNumEffects);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectQueryEffect
//
// Description: Returns a descriptor of the next available effect.
// See effect_descriptor_t for a details on effect descriptor.
// This function together with EffectQueryNumberEffects() is used to enumerate all
// effects present in all loaded libraries. The enumeration sequence is:
// EffectQueryNumberEffects(&num_effects);
// for (i = 0; i < num_effects; i++)
// EffectQueryEffect(i,...);
//
// Input/Output:
// pDescriptor: address where to return the effect descriptor.
//
// Output:
// returned value: 0 successful operation.
// -ENOENT no more effect available
// -ENODEV factory failed to initialize
// -EINVAL invalid pDescriptor
// -ENOSYS effect list has changed since last execution of EffectQueryNumberEffects()
// *pDescriptor: updated with the effect descriptor.
//
////////////////////////////////////////////////////////////////////////////////
int EffectQueryEffect(uint32_t index, effect_descriptor_t *pDescriptor);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectCreate
//
// Description: Creates an effect engine of the specified type and returns an
// effect control interface on this engine. The function will allocate the
// resources for an instance of the requested effect engine and return
// a handler on the effect control interface.
//
// Input:
// pEffectUuid: pointer to the effect uuid.
// sessionId: audio session to which this effect instance will be attached. All effects created
// with the same session ID are connected in series and process the same signal stream.
// Knowing that two effects are part of the same effect chain can help the library implement
// some kind of optimizations.
// ioId: identifies the output or input stream this effect is directed to at audio HAL. For future
// use especially with tunneled HW accelerated effects
//
// Input/Output:
// pInterface: address where to return the effect interface.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV factory failed to initialize
// -EINVAL invalid pEffectUuid or pInterface
// -ENOENT no effect with this uuid found
// *pInterface: updated with the effect interface.
//
////////////////////////////////////////////////////////////////////////////////
int EffectCreate(effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t ioId, effect_interface_t *pInterface);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectRelease
//
// Description: Releases the effect engine whose handler is given as argument.
// All resources allocated to this particular instance of the effect are
// released.
//
// Input:
// interface: handler on the effect interface to be released.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV factory failed to initialize
// -EINVAL invalid interface handler
//
////////////////////////////////////////////////////////////////////////////////
int EffectRelease(effect_interface_t interface);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectLoadLibrary
//
// Description: Loads the effect library which path is given as first argument.
// This must be the full path of a dynamic library (.so) implementing one or
// more effect engines and exposing the effect library interface described in
// EffectApi.h. The function returns a handle on the library for used by
// further call to EffectUnloadLibrary() to unload the library.
//
// Input:
// libPath: full path of the dynamic library file in the file system.
//
// handle: address where to return the library handle
//
// Output:
// returned value: 0 successful operation.
// -ENODEV effect factory not initialized or
// library could not be loaded or
// library does not implement required functions
// -EINVAL invalid libPath string or handle
//
////////////////////////////////////////////////////////////////////////////////
int EffectLoadLibrary(const char *libPath, int *handle);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectUnloadLibrary
//
// Description: Unloads the effect library which handle is given as argument.
//
// Input:
// handle: library handle
//
// Output:
// returned value: 0 successful operation.
// -ENODEV effect factory not initialized
// -ENOENT invalid handle
//
////////////////////////////////////////////////////////////////////////////////
int EffectUnloadLibrary(int handle);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectGetDescriptor
//
// Description: Returns the descriptor of the effect which uuid is pointed
// to by first argument.
//
// Input:
// pEffectUuid: pointer to the effect uuid.
//
// Input/Output:
// pDescriptor: address where to return the effect descriptor.
//
// Output:
// returned value: 0 successful operation.
// -ENODEV factory failed to initialize
// -EINVAL invalid pEffectUuid or pDescriptor
// -ENOENT no effect with this uuid found
// *pDescriptor: updated with the effect descriptor.
//
////////////////////////////////////////////////////////////////////////////////
int EffectGetDescriptor(effect_uuid_t *pEffectUuid, effect_descriptor_t *pDescriptor);
////////////////////////////////////////////////////////////////////////////////
//
// Function: EffectIsNullUuid
//
// Description: Helper function to compare effect uuid to EFFECT_UUID_NULL
//
// Input:
// pEffectUuid: pointer to effect uuid to compare to EFFECT_UUID_NULL.
//
// Output:
// returned value: 0 if uuid is different from EFFECT_UUID_NULL.
// 1 if uuid is equal to EFFECT_UUID_NULL.
//
////////////////////////////////////////////////////////////////////////////////
int EffectIsNullUuid(effect_uuid_t *pEffectUuid);
#if __cplusplus
} // extern "C"
#endif
#endif /*ANDROID_EFFECTSFACTORYAPI_H_*/
+211
View File
@@ -0,0 +1,211 @@
/*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IAUDIOFLINGER_H
#define ANDROID_IAUDIOFLINGER_H
#include <stdint.h>
#include <sys/types.h>
#include <unistd.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <media/IAudioTrack.h>
#include <media/IAudioRecord.h>
#include <media/IAudioFlingerClient.h>
#include <media/EffectApi.h>
#include <media/IEffect.h>
#include <media/IEffectClient.h>
#include <utils/String8.h>
namespace android {
// ----------------------------------------------------------------------------
class IAudioFlinger : public IInterface
{
public:
DECLARE_META_INTERFACE(AudioFlinger);
/* create an audio track and registers it with AudioFlinger.
* return null if the track cannot be created.
*/
virtual sp<IAudioTrack> createTrack(
pid_t pid,
int streamType,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
const sp<IMemory>& sharedBuffer,
int output,
int *sessionId,
status_t *status) = 0;
virtual void createSession(
pid_t pid,
uint32_t sampleRate,
int channelCount,
int *sessionId,
status_t *status) = 0;
virtual void deleteSession() = 0;
virtual void applyEffectsOn(
int16_t *buffer1,
int16_t *buffer2,
int size) = 0;
virtual sp<IAudioRecord> openRecord(
pid_t pid,
int input,
uint32_t sampleRate,
int format,
int channelCount,
int frameCount,
uint32_t flags,
int *sessionId,
status_t *status) = 0;
/* query the audio hardware state. This state never changes,
* and therefore can be cached.
*/
virtual uint32_t sampleRate(int output) const = 0;
virtual int channelCount(int output) const = 0;
virtual int format(int output) const = 0;
virtual size_t frameCount(int output) const = 0;
virtual uint32_t latency(int output) const = 0;
/* set/get the audio hardware state. This will probably be used by
* the preference panel, mostly.
*/
virtual status_t setMasterVolume(float value) = 0;
virtual status_t setMasterMute(bool muted) = 0;
virtual float masterVolume() const = 0;
virtual bool masterMute() const = 0;
/* set/get stream type state. This will probably be used by
* the preference panel, mostly.
*/
virtual status_t setStreamVolume(int stream, float value, int output) = 0;
virtual status_t setStreamMute(int stream, bool muted) = 0;
virtual float streamVolume(int stream, int output) const = 0;
virtual bool streamMute(int stream) const = 0;
// set audio mode
virtual status_t setMode(int mode) = 0;
// mic mute/state
virtual status_t setMicMute(bool state) = 0;
virtual bool getMicMute() const = 0;
// is any track active on this stream?
virtual bool isStreamActive(int stream) const = 0;
virtual status_t setParameters(int ioHandle, const String8& keyValuePairs) = 0;
virtual String8 getParameters(int ioHandle, const String8& keys) = 0;
// register a current process for audio output change notifications
virtual void registerClient(const sp<IAudioFlingerClient>& client) = 0;
// retrieve the audio recording buffer size
virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) = 0;
virtual int openOutput(uint32_t *pDevices,
uint32_t *pSamplingRate,
uint32_t *pFormat,
uint32_t *pChannels,
uint32_t *pLatencyMs,
uint32_t flags) = 0;
virtual int openSession(uint32_t *pDevices,
uint32_t *pFormat,
uint32_t flags,
int32_t stream,
int32_t sessionId){return 0;};
virtual status_t pauseSession(int output, int32_t stream) = 0;
virtual status_t resumeSession(int output, int32_t stream) = 0;
virtual status_t closeSession(int output) = 0;
virtual int openDuplicateOutput(int output1, int output2) = 0;
virtual status_t closeOutput(int output) = 0;
virtual status_t suspendOutput(int output) = 0;
virtual status_t restoreOutput(int output) = 0;
virtual int openInput(uint32_t *pDevices,
uint32_t *pSamplingRate,
uint32_t *pFormat,
uint32_t *pChannels,
uint32_t acoustics) = 0;
virtual status_t closeInput(int input) = 0;
virtual status_t setStreamOutput(uint32_t stream, int output) = 0;
virtual status_t setVoiceVolume(float volume) = 0;
virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output) = 0;
virtual unsigned int getInputFramesLost(int ioHandle) = 0;
virtual int newAudioSessionId() = 0;
virtual status_t loadEffectLibrary(const char *libPath, int *handle) = 0;
virtual status_t unloadEffectLibrary(int handle) = 0;
virtual status_t queryNumberEffects(uint32_t *numEffects) = 0;
virtual status_t queryEffect(uint32_t index, effect_descriptor_t *pDescriptor) = 0;
virtual status_t getEffectDescriptor(effect_uuid_t *pEffectUUID, effect_descriptor_t *pDescriptor) = 0;
virtual sp<IEffect> createEffect(pid_t pid,
effect_descriptor_t *pDesc,
const sp<IEffectClient>& client,
int32_t priority,
int output,
int sessionId,
status_t *status,
int *id,
int *enabled) = 0;
virtual status_t moveEffects(int session, int srcOutput, int dstOutput) = 0;
virtual status_t deregisterClient(const sp<IAudioFlingerClient>& client) { return false; };
virtual status_t setFmVolume(float volume) = 0;
};
// ----------------------------------------------------------------------------
class BnAudioFlinger : public BnInterface<IAudioFlinger>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IAUDIOFLINGER_H
+55
View File
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IAUDIOFLINGERCLIENT_H
#define ANDROID_IAUDIOFLINGERCLIENT_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <utils/KeyedVector.h>
namespace android {
// ----------------------------------------------------------------------------
class IAudioFlingerClient : public IInterface
{
public:
DECLARE_META_INTERFACE(AudioFlingerClient);
// Notifies a change of audio input/output configuration.
virtual void ioConfigChanged(int event, int ioHandle, void *param2) = 0;
};
// ----------------------------------------------------------------------------
class BnAudioFlingerClient : public BnInterface<IAudioFlingerClient>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IAUDIOFLINGERCLIENT_H
+109
View File
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IAUDIOPOLICYSERVICE_H
#define ANDROID_IAUDIOPOLICYSERVICE_H
#include <stdint.h>
#include <sys/types.h>
#include <unistd.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <media/AudioSystem.h>
namespace android {
// ----------------------------------------------------------------------------
class IAudioPolicyService : public IInterface
{
public:
DECLARE_META_INTERFACE(AudioPolicyService);
//
// IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
//
virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
AudioSystem::device_connection_state state,
const char *device_address) = 0;
virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
const char *device_address) = 0;
virtual status_t setPhoneState(int state) = 0;
virtual status_t setRingerMode(uint32_t mode, uint32_t mask) = 0;
virtual status_t setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config) = 0;
virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage) = 0;
virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
uint32_t samplingRate = 0,
uint32_t format = AudioSystem::FORMAT_DEFAULT,
uint32_t channels = 0,
AudioSystem::output_flags flags = AudioSystem::OUTPUT_FLAG_INDIRECT) = 0;
virtual audio_io_handle_t getSession(AudioSystem::stream_type stream,
uint32_t format = AudioSystem::FORMAT_DEFAULT,
AudioSystem::output_flags flags = AudioSystem::OUTPUT_FLAG_DIRECT,
int32_t sessionId=-1) { return 0; }
virtual status_t pauseSession(audio_io_handle_t output, AudioSystem::stream_type stream) { return 0; }
virtual status_t resumeSession(audio_io_handle_t output, AudioSystem::stream_type stream) { return 0; }
virtual status_t closeSession(audio_io_handle_t output) = 0;
virtual status_t startOutput(audio_io_handle_t output,
AudioSystem::stream_type stream,
int session = 0) = 0;
virtual status_t stopOutput(audio_io_handle_t output,
AudioSystem::stream_type stream,
int session = 0) = 0;
virtual void releaseOutput(audio_io_handle_t output) = 0;
virtual audio_io_handle_t getInput(int inputSource,
uint32_t samplingRate = 0,
uint32_t format = AudioSystem::FORMAT_DEFAULT,
uint32_t channels = 0,
AudioSystem::audio_in_acoustics acoustics = (AudioSystem::audio_in_acoustics)0) = 0;
virtual status_t startInput(audio_io_handle_t input) = 0;
virtual status_t stopInput(audio_io_handle_t input) = 0;
virtual void releaseInput(audio_io_handle_t input) = 0;
virtual status_t initStreamVolume(AudioSystem::stream_type stream,
int indexMin,
int indexMax) = 0;
virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index) = 0;
virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index) = 0;
virtual uint32_t getStrategyForStream(AudioSystem::stream_type stream) = 0;
virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc) = 0;
virtual status_t registerEffect(effect_descriptor_t *desc,
audio_io_handle_t output,
uint32_t strategy,
int session,
int id) = 0;
virtual status_t unregisterEffect(int id) = 0;
};
// ----------------------------------------------------------------------------
class BnAudioPolicyService : public BnInterface<IAudioPolicyService>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IAUDIOPOLICYSERVICE_H
+68
View File
@@ -0,0 +1,68 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IAUDIORECORD_H_
#define IAUDIORECORD_H_
#include <stdint.h>
#include <sys/types.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <binder/IMemory.h>
namespace android {
// ----------------------------------------------------------------------------
class IAudioRecord : public IInterface
{
public:
DECLARE_META_INTERFACE(AudioRecord);
/* After it's created the track is not active. Call start() to
* make it active. If set, the callback will start being called.
*/
virtual status_t start() = 0;
/* Stop a track. If set, the callback will cease being called and
* obtainBuffer will return an error. Buffers that are already released
* will be processed, unless flush() is called.
*/
virtual void stop() = 0;
/* get this tracks control block */
virtual sp<IMemory> getCblk() const = 0;
};
// ----------------------------------------------------------------------------
class BnAudioRecord : public BnInterface<IAudioRecord>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif /*IAUDIORECORD_H_*/
+89
View File
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IAUDIOTRACK_H
#define ANDROID_IAUDIOTRACK_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <binder/IMemory.h>
namespace android {
// ----------------------------------------------------------------------------
class IAudioTrack : public IInterface
{
public:
DECLARE_META_INTERFACE(AudioTrack);
/* After it's created the track is not active. Call start() to
* make it active. If set, the callback will start being called.
*/
virtual status_t start() = 0;
/* Stop a track. If set, the callback will cease being called and
* obtainBuffer will return an error. Buffers that are already released
* will be processed, unless flush() is called.
*/
virtual void stop() = 0;
/* flush a stopped track. All pending buffers are discarded.
* This function has no effect if the track is not stoped.
*/
virtual void flush() = 0;
/* mute or unmutes this track.
* While mutted, the callback, if set, is still called.
*/
virtual void mute(bool) = 0;
/* Pause a track. If set, the callback will cease being called and
* obtainBuffer will return an error. Buffers that are already released
* will be processed, unless flush() is called.
*/
virtual void pause() = 0;
/* Attach track auxiliary output to specified effect. Use effectId = 0
* to detach track from effect.
*/
virtual status_t attachAuxEffect(int effectId) = 0;
/* get this tracks control block */
virtual sp<IMemory> getCblk() const = 0;
};
// ----------------------------------------------------------------------------
class BnAudioTrack : public BnInterface<IAudioTrack>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IAUDIOTRACK_H
+60
View File
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IEFFECT_H
#define ANDROID_IEFFECT_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IMemory.h>
namespace android {
class IEffect: public IInterface
{
public:
DECLARE_META_INTERFACE(Effect);
virtual status_t enable() = 0;
virtual status_t disable() = 0;
virtual status_t command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *pReplySize,
void *pReplyData) = 0;
virtual void disconnect() = 0;
virtual sp<IMemory> getCblk() const = 0;
};
// ----------------------------------------------------------------------------
class BnEffect: public BnInterface<IEffect>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IEFFECT_H
+54
View File
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IEFFECTCLIENT_H
#define ANDROID_IEFFECTCLIENT_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IMemory.h>
namespace android {
class IEffectClient: public IInterface
{
public:
DECLARE_META_INTERFACE(EffectClient);
virtual void controlStatusChanged(bool controlGranted) = 0;
virtual void enableStatusChanged(bool enabled) = 0;
virtual void commandExecuted(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t replySize,
void *pReplyData) = 0;
};
// ----------------------------------------------------------------------------
class BnEffectClient: public BnInterface<IEffectClient>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IEFFECTCLIENT_H
+61
View File
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IMEDIADEATHNOTIFIER_H
#define ANDROID_IMEDIADEATHNOTIFIER_H
#include <utils/threads.h>
#include <media/IMediaPlayerService.h>
#include <utils/SortedVector.h>
namespace android {
class IMediaDeathNotifier: virtual public RefBase
{
public:
IMediaDeathNotifier() { addObitRecipient(this); }
virtual ~IMediaDeathNotifier() { removeObitRecipient(this); }
virtual void died() = 0;
static const sp<IMediaPlayerService>& getMediaPlayerService();
private:
IMediaDeathNotifier &operator=(const IMediaDeathNotifier &);
IMediaDeathNotifier(const IMediaDeathNotifier &);
static void addObitRecipient(const wp<IMediaDeathNotifier>& recipient);
static void removeObitRecipient(const wp<IMediaDeathNotifier>& recipient);
class DeathNotifier: public IBinder::DeathRecipient
{
public:
DeathNotifier() {}
virtual ~DeathNotifier();
virtual void binderDied(const wp<IBinder>& who);
};
friend class DeathNotifier;
static Mutex sServiceLock;
static sp<IMediaPlayerService> sMediaPlayerService;
static sp<DeathNotifier> sDeathNotifier;
static SortedVector< wp<IMediaDeathNotifier> > sObitRecipients;
};
}; // namespace android
#endif // ANDROID_IMEDIADEATHNOTIFIER_H
@@ -0,0 +1,54 @@
/*
**
** Copyright (C) 2008 The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef ANDROID_IMEDIAMETADATARETRIEVER_H
#define ANDROID_IMEDIAMETADATARETRIEVER_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IMemory.h>
namespace android {
class IMediaMetadataRetriever: public IInterface
{
public:
DECLARE_META_INTERFACE(MediaMetadataRetriever);
virtual void disconnect() = 0;
virtual status_t setDataSource(const char* srcUrl) = 0;
virtual status_t setDataSource(int fd, int64_t offset, int64_t length) = 0;
virtual sp<IMemory> getFrameAtTime(int64_t timeUs, int option) = 0;
virtual sp<IMemory> extractAlbumArt() = 0;
virtual const char* extractMetadata(int keyCode) = 0;
};
// ----------------------------------------------------------------------------
class BnMediaMetadataRetriever: public BnInterface<IMediaMetadataRetriever>
{
public:
virtual status_t onTransact(uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IMEDIAMETADATARETRIEVER_H
+104
View File
@@ -0,0 +1,104 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IMEDIAPLAYER_H
#define ANDROID_IMEDIAPLAYER_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
namespace android {
class Parcel;
class ISurface;
class IMediaPlayer: public IInterface
{
public:
DECLARE_META_INTERFACE(MediaPlayer);
virtual void disconnect() = 0;
virtual status_t setVideoSurface(const sp<ISurface>& surface) = 0;
virtual status_t prepareAsync() = 0;
virtual status_t start() = 0;
virtual status_t stop() = 0;
virtual status_t pause() = 0;
virtual status_t isPlaying(bool* state) = 0;
virtual status_t seekTo(int msec) = 0;
virtual status_t getCurrentPosition(int* msec) = 0;
virtual status_t getDuration(int* msec) = 0;
virtual status_t reset() = 0;
virtual status_t setAudioStreamType(int type) = 0;
virtual status_t setLooping(int loop) = 0;
virtual status_t setVolume(float leftVolume, float rightVolume) = 0;
virtual status_t suspend() = 0;
virtual status_t resume() = 0;
virtual status_t setAuxEffectSendLevel(float level) = 0;
virtual status_t attachAuxEffect(int effectId) = 0;
// Invoke a generic method on the player by using opaque parcels
// for the request and reply.
// @param request Parcel that must start with the media player
// interface token.
// @param[out] reply Parcel to hold the reply data. Cannot be null.
// @return OK if the invocation was made successfully.
virtual status_t invoke(const Parcel& request, Parcel *reply) = 0;
// Set a new metadata filter.
// @param filter A set of allow and drop rules serialized in a Parcel.
// @return OK if the invocation was made successfully.
virtual status_t setMetadataFilter(const Parcel& filter) = 0;
// Retrieve a set of metadata.
// @param update_only Include only the metadata that have changed
// since the last invocation of getMetadata.
// The set is built using the unfiltered
// notifications the native player sent to the
// MediaPlayerService during that period of
// time. If false, all the metadatas are considered.
// @param apply_filter If true, once the metadata set has been built based
// on the value update_only, the current filter is
// applied.
// @param[out] metadata On exit contains a set (possibly empty) of metadata.
// Valid only if the call returned OK.
// @return OK if the invocation was made successfully.
virtual status_t getMetadata(bool update_only,
bool apply_filter,
Parcel *metadata) = 0;
// Sets the given parameters for the player. Parameters are in 'key=value'
// format.
// @param params Key/value pairs of parameters to set for the player.
// @return OK if the invocation was made successfully.
virtual status_t setParameters(const String8& params) = 0;
};
// ----------------------------------------------------------------------------
class BnMediaPlayer: public BnInterface<IMediaPlayer>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IMEDIAPLAYER_H
+48
View File
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IMEDIAPLAYERCLIENT_H
#define ANDROID_IMEDIAPLAYERCLIENT_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
namespace android {
class IMediaPlayerClient: public IInterface
{
public:
DECLARE_META_INTERFACE(MediaPlayerClient);
virtual void notify(int msg, int ext1, int ext2) = 0;
};
// ----------------------------------------------------------------------------
class BnMediaPlayerClient: public BnInterface<IMediaPlayerClient>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IMEDIAPLAYERCLIENT_H
+66
View File
@@ -0,0 +1,66 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IMEDIAPLAYERSERVICE_H
#define ANDROID_IMEDIAPLAYERSERVICE_H
#include <utils/Errors.h> // for status_t
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
#include <utils/String8.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <media/IMediaPlayerClient.h>
#include <media/IMediaPlayer.h>
#include <media/IMediaMetadataRetriever.h>
namespace android {
class IMediaRecorder;
class IOMX;
class IMediaPlayerService: public IInterface
{
public:
DECLARE_META_INTERFACE(MediaPlayerService);
virtual sp<IMediaRecorder> createMediaRecorder(pid_t pid) = 0;
virtual sp<IMediaMetadataRetriever> createMetadataRetriever(pid_t pid) = 0;
virtual sp<IMediaPlayer> create(pid_t pid, const sp<IMediaPlayerClient>& client,
const char* url, const KeyedVector<String8, String8> *headers = NULL,
int audioSessionId = 0) = 0;
virtual sp<IMediaPlayer> create(pid_t pid, const sp<IMediaPlayerClient>& client,
int fd, int64_t offset, int64_t length, int audioSessionId) = 0;
virtual sp<IMemory> decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) = 0;
virtual sp<IMemory> decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) = 0;
virtual sp<IOMX> getOMX() = 0;
};
// ----------------------------------------------------------------------------
class BnMediaPlayerService: public BnInterface<IMediaPlayerService>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IMEDIAPLAYERSERVICE_H
+73
View File
@@ -0,0 +1,73 @@
/*
**
** Copyright 2008, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef ANDROID_IMEDIARECORDER_H
#define ANDROID_IMEDIARECORDER_H
#include <binder/IInterface.h>
namespace android {
class ISurface;
class ICamera;
class IMediaRecorderClient;
class IMediaRecorder: public IInterface
{
public:
DECLARE_META_INTERFACE(MediaRecorder);
virtual status_t setCamera(const sp<ICamera>& camera) = 0;
virtual status_t setPreviewSurface(const sp<ISurface>& surface) = 0;
virtual status_t setVideoSource(int vs) = 0;
virtual status_t setAudioSource(int as) = 0;
virtual status_t setOutputFormat(int of) = 0;
virtual status_t setVideoEncoder(int ve) = 0;
virtual status_t setAudioEncoder(int ae) = 0;
virtual status_t setOutputFile(const char* path) = 0;
virtual status_t setOutputFile(int fd, int64_t offset, int64_t length) = 0;
virtual status_t setVideoSize(int width, int height) = 0;
virtual status_t setVideoFrameRate(int frames_per_second) = 0;
virtual status_t setParameters(const String8& params) = 0;
virtual status_t setListener(const sp<IMediaRecorderClient>& listener) = 0;
virtual status_t setCameraParameters(const String8& params) = 0;
virtual status_t prepare() = 0;
virtual status_t getMaxAmplitude(int* max) = 0;
virtual status_t start() = 0;
virtual status_t stop() = 0;
virtual status_t reset() = 0;
virtual status_t init() = 0;
virtual status_t close() = 0;
virtual status_t release() = 0;
virtual status_t takeLiveSnapshot() = 0;
};
// ----------------------------------------------------------------------------
class BnMediaRecorder: public BnInterface<IMediaRecorder>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IMEDIARECORDER_H
+50
View File
@@ -0,0 +1,50 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IMEDIARECORDERCLIENT_H
#define ANDROID_IMEDIARECORDERCLIENT_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IMemory.h>
namespace android {
class IMediaRecorderClient: public IInterface
{
public:
DECLARE_META_INTERFACE(MediaRecorderClient);
virtual void notify(int msg, int ext1, int ext2) = 0;
virtual void dataCallback(int32_t msgType, const sp<IMemory>& imageData) = 0;
};
// ----------------------------------------------------------------------------
class BnMediaRecorderClient: public BnInterface<IMediaRecorderClient>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IMEDIARECORDERCLIENT_H
+226
View File
@@ -0,0 +1,226 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*--------------------------------------------------------------------------
Copyright (c) 2010, The Linux Foundation. All rights reserved.
--------------------------------------------------------------------------*/
#ifndef ANDROID_IOMX_H_
#define ANDROID_IOMX_H_
#include <binder/IInterface.h>
#include <binder/MemoryHeapBase.h>
#include <utils/List.h>
#include <utils/String8.h>
#include <OMX_Core.h>
#include <OMX_Video.h>
#include "jni.h"
namespace android {
class IMemory;
class IOMXObserver;
class IOMXRenderer;
class ISurface;
class Surface;
class IOMX : public IInterface {
public:
DECLARE_META_INTERFACE(OMX);
typedef void *buffer_id;
typedef void *node_id;
// Given the calling process' pid, returns true iff
// the implementation of the OMX interface lives in the same
// process.
virtual bool livesLocally(pid_t pid) = 0;
struct ComponentInfo {
String8 mName;
List<String8> mRoles;
};
virtual status_t listNodes(List<ComponentInfo> *list) = 0;
virtual status_t allocateNode(
const char *name, const sp<IOMXObserver> &observer,
node_id *node) = 0;
virtual status_t freeNode(node_id node) = 0;
virtual status_t sendCommand(
node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param) = 0;
virtual status_t getParameter(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size) = 0;
virtual status_t setParameter(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size) = 0;
virtual status_t getConfig(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size) = 0;
virtual status_t setConfig(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size) = 0;
virtual status_t useBuffer(
node_id node, OMX_U32 port_index, const sp<IMemory> &params,
buffer_id *buffer) = 0;
// This API clearly only makes sense if the caller lives in the
// same process as the callee, i.e. is the media_server, as the
// returned "buffer_data" pointer is just that, a pointer into local
// address space.
virtual status_t allocateBuffer(
node_id node, OMX_U32 port_index, size_t size,
buffer_id *buffer, void **buffer_data) = 0;
virtual status_t allocateBufferWithBackup(
node_id node, OMX_U32 port_index, const sp<IMemory> &params,
buffer_id *buffer) = 0;
virtual status_t freeBuffer(
node_id node, OMX_U32 port_index, buffer_id buffer) = 0;
virtual status_t fillBuffer(node_id node, buffer_id buffer) = 0;
virtual status_t emptyBuffer(
node_id node,
buffer_id buffer,
OMX_U32 range_offset, OMX_U32 range_length,
OMX_U32 flags, OMX_TICKS timestamp) = 0;
virtual status_t getExtensionIndex(
node_id node,
const char *parameter_name,
OMX_INDEXTYPE *index) = 0;
/* missing flags in below functions */
virtual sp<IOMXRenderer> createRenderer(
const sp<ISurface> &surface,
const char *componentName,
OMX_COLOR_FORMATTYPE colorFormat,
size_t encodedWidth, size_t encodedHeight,
size_t displayWidth, size_t displayHeight,
int32_t rotationDegrees) = 0;
// Note: These methods are _not_ virtual, it exists as a wrapper around
// the virtual "createRenderer" method above facilitating extraction
// of the ISurface from a regular Surface or a java Surface object.
sp<IOMXRenderer> createRenderer(
const sp<Surface> &surface,
const char *componentName,
OMX_COLOR_FORMATTYPE colorFormat,
size_t encodedWidth, size_t encodedHeight,
size_t displayWidth, size_t displayHeight,
int32_t rotationDegrees);
sp<IOMXRenderer> createRendererFromJavaSurface(
JNIEnv *env, jobject javaSurface,
const char *componentName,
OMX_COLOR_FORMATTYPE colorFormat,
size_t encodedWidth, size_t encodedHeight,
size_t displayWidth, size_t displayHeight,
int32_t rotationDegrees);
};
struct omx_message {
enum {
EVENT,
EMPTY_BUFFER_DONE,
FILL_BUFFER_DONE,
REGISTER_BUFFERS
} type;
IOMX::node_id node;
union {
// if type == EVENT
struct {
OMX_EVENTTYPE event;
OMX_U32 data1;
OMX_U32 data2;
} event_data;
// if type == EMPTY_BUFFER_DONE
struct {
IOMX::buffer_id buffer;
} buffer_data;
// if type == FILL_BUFFER_DONE
struct {
IOMX::buffer_id buffer;
OMX_U32 range_offset;
OMX_U32 range_length;
OMX_U32 flags;
OMX_TICKS timestamp;
OMX_PTR platform_private;
OMX_PTR data_ptr;
OMX_U32 pmem_offset;
} extended_buffer_data;
} u;
};
class IOMXObserver : public IInterface {
public:
DECLARE_META_INTERFACE(OMXObserver);
virtual void onMessage(const omx_message &msg) = 0;
virtual void registerBuffers(const sp<IMemoryHeap> &mem) = 0;
};
class IOMXRenderer : public IInterface {
public:
DECLARE_META_INTERFACE(OMXRenderer);
virtual void render(IOMX::buffer_id buffer) = 0;
};
////////////////////////////////////////////////////////////////////////////////
class BnOMX : public BnInterface<IOMX> {
public:
virtual status_t onTransact(
uint32_t code, const Parcel &data, Parcel *reply,
uint32_t flags = 0);
};
class BnOMXObserver : public BnInterface<IOMXObserver> {
public:
virtual status_t onTransact(
uint32_t code, const Parcel &data, Parcel *reply,
uint32_t flags = 0);
};
class BnOMXRenderer : public BnInterface<IOMXRenderer> {
public:
virtual status_t onTransact(
uint32_t code, const Parcel &data, Parcel *reply,
uint32_t flags = 0);
};
} // namespace android
#endif // ANDROID_IOMX_H_
+107
View File
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JETPLAYER_H_
#define JETPLAYER_H_
#include <utils/threads.h>
#include <nativehelper/jni.h>
#include <libsonivox/jet.h>
#include <libsonivox/eas_types.h>
#include "AudioTrack.h"
namespace android {
typedef void (*jetevent_callback)(int eventType, int val1, int val2, void *cookie);
class JetPlayer {
public:
// to keep in sync with the JetPlayer class constants
// defined in frameworks/base/media/java/android/media/JetPlayer.java
static const int JET_EVENT = 1;
static const int JET_USERID_UPDATE = 2;
static const int JET_NUMQUEUEDSEGMENT_UPDATE = 3;
static const int JET_PAUSE_UPDATE = 4;
JetPlayer(jobject javaJetPlayer,
int maxTracks = 32,
int trackBufferSize = 1200);
~JetPlayer();
int init();
int release();
int loadFromFile(const char* url);
int loadFromFD(const int fd, const long long offset, const long long length);
int closeFile();
int play();
int pause();
int queueSegment(int segmentNum, int libNum, int repeatCount, int transpose,
EAS_U32 muteFlags, EAS_U8 userID);
int setMuteFlags(EAS_U32 muteFlags, bool sync);
int setMuteFlag(int trackNum, bool muteFlag, bool sync);
int triggerClip(int clipId);
int clearQueue();
void setEventCallback(jetevent_callback callback);
int getMaxTracks() { return mMaxTracks; };
private:
static int renderThread(void*);
int render();
void fireUpdateOnStatusChange();
void fireEventsFromJetQueue();
JetPlayer() {} // no default constructor
void dump();
void dumpJetStatus(S_JET_STATUS* pJetStatus);
jetevent_callback mEventCallback;
jobject mJavaJetPlayerRef;
Mutex mMutex; // mutex to sync the render and playback thread with the JET calls
pid_t mTid;
Condition mCondition;
volatile bool mRender;
bool mPaused;
EAS_STATE mState;
int* mMemFailedVar;
int mMaxTracks; // max number of MIDI tracks, usually 32
EAS_DATA_HANDLE mEasData;
EAS_FILE_LOCATOR mEasJetFileLoc;
EAS_PCM* mAudioBuffer;// EAS renders the MIDI data into this buffer,
AudioTrack* mAudioTrack; // and we play it in this audio track
int mTrackBufferSize;
S_JET_STATUS mJetStatus;
S_JET_STATUS mPreviousJetStatus;
char mJetFilePath[256];
}; // end class JetPlayer
} // end namespace android
#endif /*JETPLAYER_H_*/
@@ -0,0 +1,55 @@
/*
**
** Copyright (C) 2008 The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef ANDROID_MEDIAMETADATARETRIEVERINTERFACE_H
#define ANDROID_MEDIAMETADATARETRIEVERINTERFACE_H
#include <utils/RefBase.h>
#include <media/mediametadataretriever.h>
#include <private/media/VideoFrame.h>
namespace android {
// Abstract base class
class MediaMetadataRetrieverBase : public RefBase
{
public:
MediaMetadataRetrieverBase() {}
virtual ~MediaMetadataRetrieverBase() {}
virtual status_t setDataSource(const char *url) = 0;
virtual status_t setDataSource(int fd, int64_t offset, int64_t length) = 0;
virtual VideoFrame* getFrameAtTime(int64_t timeUs, int option) = 0;
virtual MediaAlbumArt* extractAlbumArt() = 0;
virtual const char* extractMetadata(int keyCode) = 0;
};
// MediaMetadataRetrieverInterface
class MediaMetadataRetrieverInterface : public MediaMetadataRetrieverBase
{
public:
MediaMetadataRetrieverInterface() {}
virtual ~MediaMetadataRetrieverInterface() {}
virtual VideoFrame* getFrameAtTime(int64_t timeUs, int option) { return NULL; }
virtual MediaAlbumArt* extractAlbumArt() { return NULL; }
virtual const char* extractMetadata(int keyCode) { return NULL; }
};
}; // namespace android
#endif // ANDROID_MEDIAMETADATARETRIEVERINTERFACE_H
+190
View File
@@ -0,0 +1,190 @@
/*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEDIAPLAYERINTERFACE_H
#define ANDROID_MEDIAPLAYERINTERFACE_H
#ifdef __cplusplus
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/KeyedVector.h>
#include <utils/String8.h>
#include <utils/RefBase.h>
#include <media/mediaplayer.h>
#include <media/AudioSystem.h>
#include <media/Metadata.h>
namespace android {
class Parcel;
class ISurface;
template<typename T> class SortedVector;
enum player_type {
PV_PLAYER = 1,
SONIVOX_PLAYER = 2,
STAGEFRIGHT_PLAYER = 4,
// Test players are available only in the 'test' and 'eng' builds.
// The shared library with the test player is passed passed as an
// argument to the 'test:' url in the setDataSource call.
TEST_PLAYER = 5,
};
#define DEFAULT_AUDIOSINK_BUFFERCOUNT 4
#define DEFAULT_AUDIOSINK_BUFFERSIZE 1200
#define DEFAULT_AUDIOSINK_SAMPLERATE 44100
// callback mechanism for passing messages to MediaPlayer object
typedef void (*notify_callback_f)(void* cookie, int msg, int ext1, int ext2);
// abstract base class - use MediaPlayerInterface
class MediaPlayerBase : public RefBase
{
public:
// AudioSink: abstraction layer for audio output
class AudioSink : public RefBase {
public:
// Callback returns the number of bytes actually written to the buffer.
typedef size_t (*AudioCallback)(
AudioSink *audioSink, void *buffer, size_t size, void *cookie);
virtual ~AudioSink() {}
virtual bool ready() const = 0; // audio output is open and ready
virtual bool realtime() const = 0; // audio output is real-time output
virtual ssize_t bufferSize() const = 0;
virtual ssize_t frameCount() const = 0;
virtual ssize_t channelCount() const = 0;
virtual ssize_t frameSize() const = 0;
virtual uint32_t latency() const = 0;
virtual float msecsPerFrame() const = 0;
virtual status_t getPosition(uint32_t *position) = 0;
virtual int getSessionId() = 0;
// If no callback is specified, use the "write" API below to submit
// audio data.
virtual status_t open(
uint32_t sampleRate, int channelCount,
int format=AudioSystem::PCM_16_BIT,
int bufferCount=DEFAULT_AUDIOSINK_BUFFERCOUNT,
AudioCallback cb = NULL,
void *cookie = NULL) = 0;
// API to open a routing session for tunneled audio playback
virtual status_t openSession(
int format, int sessionId, uint32_t sampleRate = 44100, int channels = 2) {return 0;};
virtual void start() = 0;
virtual ssize_t write(const void* buffer, size_t size) = 0;
virtual void stop() = 0;
virtual void flush() = 0;
virtual void pause() = 0;
virtual void pauseSession() {return;};
virtual void resumeSession() {return;};
virtual void close() = 0;
virtual void closeSession() {return;};
};
MediaPlayerBase() : mCookie(0), mNotify(0) {}
virtual ~MediaPlayerBase() {}
virtual status_t initCheck() = 0;
virtual bool hardwareOutput() = 0;
virtual status_t setDataSource(
const char *url,
const KeyedVector<String8, String8> *headers = NULL) = 0;
virtual status_t setDataSource(int fd, int64_t offset, int64_t length) = 0;
virtual status_t setVideoSurface(const sp<ISurface>& surface) = 0;
virtual status_t prepare() = 0;
virtual status_t prepareAsync() = 0;
virtual status_t start() = 0;
virtual status_t stop() = 0;
virtual status_t pause() = 0;
virtual bool isPlaying() = 0;
virtual status_t seekTo(int msec) = 0;
virtual status_t getCurrentPosition(int *msec) = 0;
virtual status_t getDuration(int *msec) = 0;
virtual status_t reset() = 0;
virtual status_t setLooping(int loop) = 0;
virtual player_type playerType() = 0;
virtual status_t suspend() { return INVALID_OPERATION; }
virtual status_t resume() { return INVALID_OPERATION; }
virtual void setNotifyCallback(void* cookie, notify_callback_f notifyFunc) {
mCookie = cookie; mNotify = notifyFunc; }
// Invoke a generic method on the player by using opaque parcels
// for the request and reply.
//
// @param request Parcel that is positioned at the start of the
// data sent by the java layer.
// @param[out] reply Parcel to hold the reply data. Cannot be null.
// @return OK if the call was successful.
virtual status_t invoke(const Parcel& request, Parcel *reply) = 0;
// The Client in the MetadataPlayerService calls this method on
// the native player to retrieve all or a subset of metadata.
//
// @param ids SortedList of metadata ID to be fetch. If empty, all
// the known metadata should be returned.
// @param[inout] records Parcel where the player appends its metadata.
// @return OK if the call was successful.
virtual status_t getMetadata(const media::Metadata::Filter& ids,
Parcel *records) {
return INVALID_OPERATION;
};
virtual void sendEvent(int msg, int ext1=0, int ext2=0) { if (mNotify) mNotify(mCookie, msg, ext1, ext2); }
virtual status_t setParameters(const String8& params) = 0;
protected:
void* mCookie;
notify_callback_f mNotify;
};
// Implement this class for media players that use the AudioFlinger software mixer
class MediaPlayerInterface : public MediaPlayerBase
{
public:
virtual ~MediaPlayerInterface() { }
virtual bool hardwareOutput() { return false; }
virtual void setAudioSink(const sp<AudioSink>& audioSink) { mAudioSink = audioSink; }
protected:
sp<AudioSink> mAudioSink;
};
// Implement this class for media players that output directo to hardware
class MediaPlayerHWInterface : public MediaPlayerBase
{
public:
virtual ~MediaPlayerHWInterface() {}
virtual bool hardwareOutput() { return true; }
virtual status_t setVolume(float leftVolume, float rightVolume) = 0;
virtual status_t setAudioStreamType(int streamType) = 0;
};
}; // namespace android
#endif // __cplusplus
#endif // ANDROID_MEDIAPLAYERINTERFACE_H
+327
View File
@@ -0,0 +1,327 @@
/*
**
** Copyright 2010, The Android Open Source Project.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef ANDROID_MEDIAPROFILES_H
#define ANDROID_MEDIAPROFILES_H
#include <utils/threads.h>
#include <media/mediarecorder.h>
namespace android {
enum camcorder_quality {
CAMCORDER_QUALITY_LOW = 0,
CAMCORDER_QUALITY_HIGH = 1
};
enum video_decoder {
VIDEO_DECODER_WMV,
};
enum audio_decoder {
AUDIO_DECODER_WMA,
};
class MediaProfiles
{
public:
/**
* Returns the singleton instance for subsequence queries.
* or NULL if error.
*/
static MediaProfiles* getInstance();
/**
* Returns the value for the given param name for the given camera at
* the given quality level, or -1 if error.
*
* Supported param name are:
* duration - the recording duration.
* file.format - output file format. see mediarecorder.h for details
* vid.codec - video encoder. see mediarecorder.h for details.
* aud.codec - audio encoder. see mediarecorder.h for details.
* vid.width - video frame width
* vid.height - video frame height
* vid.fps - video frame rate
* vid.bps - video bit rate
* aud.bps - audio bit rate
* aud.hz - audio sample rate
* aud.ch - number of audio channels
*/
int getCamcorderProfileParamByName(const char *name, int cameraId,
camcorder_quality quality) const;
/**
* Returns the output file formats supported.
*/
Vector<output_format> getOutputFileFormats() const;
/**
* Returns the video encoders supported.
*/
Vector<video_encoder> getVideoEncoders() const;
/**
* Returns the value for the given param name for the given video encoder
* returned from getVideoEncoderByIndex or -1 if error.
*
* Supported param name are:
* enc.vid.width.min - min video frame width
* enc.vid.width.max - max video frame width
* enc.vid.height.min - min video frame height
* enc.vid.height.max - max video frame height
* enc.vid.bps.min - min bit rate in bits per second
* enc.vid.bps.max - max bit rate in bits per second
* enc.vid.fps.min - min frame rate in frames per second
* enc.vid.fps.max - max frame rate in frames per second
*/
int getVideoEncoderParamByName(const char *name, video_encoder codec) const;
/**
* Returns the audio encoders supported.
*/
Vector<audio_encoder> getAudioEncoders() const;
/**
* Returns the value for the given param name for the given audio encoder
* returned from getAudioEncoderByIndex or -1 if error.
*
* Supported param name are:
* enc.aud.ch.min - min number of channels
* enc.aud.ch.max - max number of channels
* enc.aud.bps.min - min bit rate in bits per second
* enc.aud.bps.max - max bit rate in bits per second
* enc.aud.hz.min - min sample rate in samples per second
* enc.aud.hz.max - max sample rate in samples per second
*/
int getAudioEncoderParamByName(const char *name, audio_encoder codec) const;
/**
* Returns the video decoders supported.
*/
Vector<video_decoder> getVideoDecoders() const;
/**
* Returns the audio decoders supported.
*/
Vector<audio_decoder> getAudioDecoders() const;
/**
* Returns the number of image encoding quality levels supported.
*/
Vector<int> getImageEncodingQualityLevels(int cameraId) const;
private:
MediaProfiles& operator=(const MediaProfiles&); // Don't call me
MediaProfiles(const MediaProfiles&); // Don't call me
MediaProfiles() {} // Dummy default constructor
~MediaProfiles(); // Don't delete me
struct VideoCodec {
VideoCodec(video_encoder codec, int bitRate, int frameWidth, int frameHeight, int frameRate)
: mCodec(codec),
mBitRate(bitRate),
mFrameWidth(frameWidth),
mFrameHeight(frameHeight),
mFrameRate(frameRate) {}
~VideoCodec() {}
video_encoder mCodec;
int mBitRate;
int mFrameWidth;
int mFrameHeight;
int mFrameRate;
};
struct AudioCodec {
AudioCodec(audio_encoder codec, int bitRate, int sampleRate, int channels)
: mCodec(codec),
mBitRate(bitRate),
mSampleRate(sampleRate),
mChannels(channels) {}
~AudioCodec() {}
audio_encoder mCodec;
int mBitRate;
int mSampleRate;
int mChannels;
};
struct CamcorderProfile {
CamcorderProfile()
: mCameraId(0),
mFileFormat(OUTPUT_FORMAT_THREE_GPP),
mQuality(CAMCORDER_QUALITY_HIGH),
mDuration(0),
mVideoCodec(0),
mAudioCodec(0) {}
~CamcorderProfile() {
delete mVideoCodec;
delete mAudioCodec;
}
int mCameraId;
output_format mFileFormat;
camcorder_quality mQuality;
int mDuration;
VideoCodec *mVideoCodec;
AudioCodec *mAudioCodec;
};
struct VideoEncoderCap {
// Ugly constructor
VideoEncoderCap(video_encoder codec,
int minBitRate, int maxBitRate,
int minFrameWidth, int maxFrameWidth,
int minFrameHeight, int maxFrameHeight,
int minFrameRate, int maxFrameRate)
: mCodec(codec),
mMinBitRate(minBitRate), mMaxBitRate(maxBitRate),
mMinFrameWidth(minFrameWidth), mMaxFrameWidth(maxFrameWidth),
mMinFrameHeight(minFrameHeight), mMaxFrameHeight(maxFrameHeight),
mMinFrameRate(minFrameRate), mMaxFrameRate(maxFrameRate) {}
~VideoEncoderCap() {}
video_encoder mCodec;
int mMinBitRate, mMaxBitRate;
int mMinFrameWidth, mMaxFrameWidth;
int mMinFrameHeight, mMaxFrameHeight;
int mMinFrameRate, mMaxFrameRate;
};
struct AudioEncoderCap {
// Ugly constructor
AudioEncoderCap(audio_encoder codec,
int minBitRate, int maxBitRate,
int minSampleRate, int maxSampleRate,
int minChannels, int maxChannels)
: mCodec(codec),
mMinBitRate(minBitRate), mMaxBitRate(maxBitRate),
mMinSampleRate(minSampleRate), mMaxSampleRate(maxSampleRate),
mMinChannels(minChannels), mMaxChannels(maxChannels) {}
~AudioEncoderCap() {}
audio_encoder mCodec;
int mMinBitRate, mMaxBitRate;
int mMinSampleRate, mMaxSampleRate;
int mMinChannels, mMaxChannels;
};
struct VideoDecoderCap {
VideoDecoderCap(video_decoder codec): mCodec(codec) {}
~VideoDecoderCap() {}
video_decoder mCodec;
};
struct AudioDecoderCap {
AudioDecoderCap(audio_decoder codec): mCodec(codec) {}
~AudioDecoderCap() {}
audio_decoder mCodec;
};
struct NameToTagMap {
const char* name;
int tag;
};
struct ImageEncodingQualityLevels {
int mCameraId;
Vector<int> mLevels;
};
// Debug
static void logVideoCodec(const VideoCodec& codec);
static void logAudioCodec(const AudioCodec& codec);
static void logVideoEncoderCap(const VideoEncoderCap& cap);
static void logAudioEncoderCap(const AudioEncoderCap& cap);
static void logVideoDecoderCap(const VideoDecoderCap& cap);
static void logAudioDecoderCap(const AudioDecoderCap& cap);
// If the xml configuration file does exist, use the settings
// from the xml
static MediaProfiles* createInstanceFromXmlFile(const char *xml);
static output_format createEncoderOutputFileFormat(const char **atts);
static VideoCodec* createVideoCodec(const char **atts, MediaProfiles *profiles);
static AudioCodec* createAudioCodec(const char **atts, MediaProfiles *profiles);
static AudioDecoderCap* createAudioDecoderCap(const char **atts);
static VideoDecoderCap* createVideoDecoderCap(const char **atts);
static VideoEncoderCap* createVideoEncoderCap(const char **atts);
static AudioEncoderCap* createAudioEncoderCap(const char **atts);
static CamcorderProfile* createCamcorderProfile(int cameraId, const char **atts);
static int getCameraId(const char **atts);
ImageEncodingQualityLevels* findImageEncodingQualityLevels(int cameraId) const;
void addImageEncodingQualityLevel(int cameraId, const char** atts);
// Customized element tag handler for parsing the xml configuration file.
static void startElementHandler(void *userData, const char *name, const char **atts);
// If the xml configuration file does not exist, use hard-coded values
static MediaProfiles* createDefaultInstance();
static CamcorderProfile *createDefaultCamcorderLowProfile();
static CamcorderProfile *createDefaultCamcorderHighProfile();
static void createDefaultCamcorderProfiles(MediaProfiles *profiles);
static void createDefaultVideoEncoders(MediaProfiles *profiles);
static void createDefaultAudioEncoders(MediaProfiles *profiles);
static void createDefaultVideoDecoders(MediaProfiles *profiles);
static void createDefaultAudioDecoders(MediaProfiles *profiles);
static void createDefaultEncoderOutputFileFormats(MediaProfiles *profiles);
static void createDefaultImageEncodingQualityLevels(MediaProfiles *profiles);
static void createDefaultImageDecodingMaxMemory(MediaProfiles *profiles);
static VideoEncoderCap* createDefaultH263VideoEncoderCap();
static VideoEncoderCap* createDefaultH264VideoEncoderCap();
static VideoEncoderCap* createDefaultM4vVideoEncoderCap();
static AudioEncoderCap* createDefaultAmrNBEncoderCap();
static AudioEncoderCap* createDefaultAacEncoderCap();
static int findTagForName(const NameToTagMap *map, size_t nMappings, const char *name);
// Mappings from name (for instance, codec name) to enum value
static const NameToTagMap sVideoEncoderNameMap[];
static const NameToTagMap sAudioEncoderNameMap[];
static const NameToTagMap sFileFormatMap[];
static const NameToTagMap sVideoDecoderNameMap[];
static const NameToTagMap sAudioDecoderNameMap[];
static const NameToTagMap sCamcorderQualityNameMap[];
static bool sIsInitialized;
static MediaProfiles *sInstance;
static Mutex sLock;
int mCurrentCameraId;
Vector<CamcorderProfile*> mCamcorderProfiles;
Vector<AudioEncoderCap*> mAudioEncoders;
Vector<VideoEncoderCap*> mVideoEncoders;
Vector<AudioDecoderCap*> mAudioDecoders;
Vector<VideoDecoderCap*> mVideoDecoders;
Vector<output_format> mEncoderOutputFileFormats;
Vector<ImageEncodingQualityLevels *> mImageEncodingQualityLevels;
};
}; // namespace android
#endif // ANDROID_MEDIAPROFILES_H
+62
View File
@@ -0,0 +1,62 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIA_RECORDER_BASE_H_
#define MEDIA_RECORDER_BASE_H_
#include <media/mediarecorder.h>
namespace android {
class ISurface;
struct MediaRecorderBase {
MediaRecorderBase() {}
virtual ~MediaRecorderBase() {}
virtual status_t init() = 0;
virtual status_t setAudioSource(audio_source as) = 0;
virtual status_t setVideoSource(video_source vs) = 0;
virtual status_t setOutputFormat(output_format of) = 0;
virtual status_t setAudioEncoder(audio_encoder ae) = 0;
virtual status_t setVideoEncoder(video_encoder ve) = 0;
virtual status_t setVideoSize(int width, int height) = 0;
virtual status_t setVideoFrameRate(int frames_per_second) = 0;
virtual status_t setCamera(const sp<ICamera>& camera) = 0;
virtual status_t setPreviewSurface(const sp<ISurface>& surface) = 0;
virtual status_t setOutputFile(const char *path) = 0;
virtual status_t setOutputFile(int fd, int64_t offset, int64_t length) = 0;
virtual status_t setParameters(const String8& params) = 0;
virtual status_t setListener(const sp<IMediaRecorderClient>& listener) = 0;
virtual status_t setCameraParameters(const String8& params) = 0;
virtual status_t prepare() = 0;
virtual status_t start() = 0;
virtual status_t stop() = 0;
virtual status_t close() = 0;
virtual status_t reset() = 0;
virtual status_t getMaxAmplitude(int *max) = 0;
virtual status_t dump(int fd, const Vector<String16>& args) const = 0;
virtual status_t takeLiveSnapshot() {return NO_ERROR;}
private:
MediaRecorderBase(const MediaRecorderBase &);
MediaRecorderBase &operator=(const MediaRecorderBase &);
};
} // namespace android
#endif // MEDIA_RECORDER_BASE_H_
+134
View File
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEDIA_METADATA_H__
#define ANDROID_MEDIA_METADATA_H__
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/SortedVector.h>
namespace android {
class Parcel;
namespace media {
// Metadata is a class to build/serialize a set of metadata in a Parcel.
//
// This class should be kept in sync with android/media/Metadata.java.
// It provides all the metadata ids available and methods to build the
// header, add records and adjust the set size header field.
//
// Typical Usage:
// ==============
// Parcel p;
// media::Metadata data(&p);
//
// data.appendHeader();
// data.appendBool(Metadata::kPauseAvailable, true);
// ... more append ...
// data.updateLength();
//
class Metadata {
public:
typedef int32_t Type;
typedef SortedVector<Type> Filter;
static const Type kAny = 0;
// Keep in sync with android/media/Metadata.java
static const Type kTitle = 1; // String
static const Type kComment = 2; // String
static const Type kCopyright = 3; // String
static const Type kAlbum = 4; // String
static const Type kArtist = 5; // String
static const Type kAuthor = 6; // String
static const Type kComposer = 7; // String
static const Type kGenre = 8; // String
static const Type kDate = 9; // Date
static const Type kDuration = 10; // Integer(millisec)
static const Type kCdTrackNum = 11; // Integer 1-based
static const Type kCdTrackMax = 12; // Integer
static const Type kRating = 13; // String
static const Type kAlbumArt = 14; // byte[]
static const Type kVideoFrame = 15; // Bitmap
static const Type kCaption = 16; // TimedText
static const Type kBitRate = 17; // Integer, Aggregate rate of
// all the streams in bps.
static const Type kAudioBitRate = 18; // Integer, bps
static const Type kVideoBitRate = 19; // Integer, bps
static const Type kAudioSampleRate = 20; // Integer, Hz
static const Type kVideoframeRate = 21; // Integer, Hz
// See RFC2046 and RFC4281.
static const Type kMimeType = 22; // String
static const Type kAudioCodec = 23; // String
static const Type kVideoCodec = 24; // String
static const Type kVideoHeight = 25; // Integer
static const Type kVideoWidth = 26; // Integer
static const Type kNumTracks = 27; // Integer
static const Type kDrmCrippled = 28; // Boolean
// Playback capabilities.
static const Type kPauseAvailable = 29; // Boolean
static const Type kSeekBackwardAvailable = 30; // Boolean
static const Type kSeekForwardAvailable = 31; // Boolean
static const Type kSeekAvailable = 32; // Boolean
// @param p[inout] The parcel to append the metadata records
// to. The global metadata header should have been set already.
explicit Metadata(Parcel *p);
~Metadata();
// Rewind the underlying parcel, undoing all the changes.
void resetParcel();
// Append the size and 'META' marker.
bool appendHeader();
// Once all the records have been added, call this to update the
// lenght field in the header.
void updateLength();
// append* are methods to append metadata.
// @param key Is the metadata Id.
// @param val Is the value of the metadata.
// @return true if successful, false otherwise.
// TODO: add more as needed to handle other types.
bool appendBool(Type key, bool val);
bool appendInt32(Type key, int32_t val);
private:
Metadata(const Metadata&);
Metadata& operator=(const Metadata&);
// Checks the key is valid and not already present.
bool checkKey(Type key);
Parcel *mData;
size_t mBegin;
};
} // namespace android::media
} // namespace android
#endif // ANDROID_MEDIA_METADATA_H__
+70
View File
@@ -0,0 +1,70 @@
/*
**
** Copyright 2008, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef ANDROID_PVMEDIARECORDER_H
#define ANDROID_PVMEDIARECORDER_H
#include <media/IMediaRecorderClient.h>
#include <media/MediaRecorderBase.h>
namespace android {
class ISurface;
class ICamera;
class AuthorDriverWrapper;
class PVMediaRecorder : public MediaRecorderBase {
public:
PVMediaRecorder();
virtual ~PVMediaRecorder();
virtual status_t init();
virtual status_t setAudioSource(audio_source as);
virtual status_t setVideoSource(video_source vs);
virtual status_t setOutputFormat(output_format of);
virtual status_t setAudioEncoder(audio_encoder ae);
virtual status_t setVideoEncoder(video_encoder ve);
virtual status_t setVideoSize(int width, int height);
virtual status_t setVideoFrameRate(int frames_per_second);
virtual status_t setCamera(const sp<ICamera>& camera);
virtual status_t setPreviewSurface(const sp<ISurface>& surface);
virtual status_t setOutputFile(const char *path);
virtual status_t setOutputFile(int fd, int64_t offset, int64_t length);
virtual status_t setParameters(const String8& params);
virtual status_t setListener(const sp<IMediaRecorderClient>& listener);
virtual status_t setCameraParameters(const String8& params);
virtual status_t prepare();
virtual status_t start();
virtual status_t stop();
virtual status_t close();
virtual status_t reset();
virtual status_t getMaxAmplitude(int *max);
virtual status_t dump(int fd, const Vector<String16>& args) const;
private:
status_t doStop();
AuthorDriverWrapper* mAuthorDriverWrapper;
PVMediaRecorder(const PVMediaRecorder &);
PVMediaRecorder &operator=(const PVMediaRecorder &);
};
}; // namespace android
#endif // ANDROID_PVMEDIARECORDER_H
+51
View File
@@ -0,0 +1,51 @@
/*
**
** Copyright (C) 2008 The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef ANDROID_PVMETADATARETRIEVER_H
#define ANDROID_PVMETADATARETRIEVER_H
#include <utils/Errors.h>
#include <media/MediaMetadataRetrieverInterface.h>
#include <private/media/VideoFrame.h>
namespace android {
class MetadataDriver;
class PVMetadataRetriever : public MediaMetadataRetrieverInterface
{
public:
PVMetadataRetriever();
virtual ~PVMetadataRetriever();
virtual status_t setDataSource(const char *url);
virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
virtual status_t setMode(int mode);
virtual status_t getMode(int* mode) const;
virtual VideoFrame* captureFrame();
virtual MediaAlbumArt* extractAlbumArt();
virtual const char* extractMetadata(int keyCode);
private:
mutable Mutex mLock;
MetadataDriver* mMetadataDriver;
char* mDataSourcePath;
};
}; // namespace android
#endif // ANDROID_PVMETADATARETRIEVER_H
+107
View File
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_PVPLAYER_H
#define ANDROID_PVPLAYER_H
#include <utils/Errors.h>
#include <media/MediaPlayerInterface.h>
#include <media/Metadata.h>
#define MAX_OPENCORE_INSTANCES 25
#ifdef MAX_OPENCORE_INSTANCES
#include <cutils/atomic.h>
#endif
class PlayerDriver;
namespace android {
class PVPlayer : public MediaPlayerInterface
{
public:
PVPlayer();
virtual ~PVPlayer();
virtual status_t initCheck();
virtual status_t setDataSource(
const char *url, const KeyedVector<String8, String8> *headers);
virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
virtual status_t setVideoSurface(const sp<ISurface>& surface);
virtual status_t prepare();
virtual status_t prepareAsync();
virtual status_t start();
virtual status_t stop();
virtual status_t pause();
virtual bool isPlaying();
virtual status_t seekTo(int msec);
virtual status_t getCurrentPosition(int *msec);
virtual status_t getDuration(int *msec);
virtual status_t reset();
virtual status_t setLooping(int loop);
virtual player_type playerType() { return PV_PLAYER; }
virtual status_t invoke(const Parcel& request, Parcel *reply);
virtual status_t getMetadata(
const SortedVector<media::Metadata::Type>& ids,
Parcel *records);
virtual status_t suspend();
virtual status_t resume();
virtual status_t setParameters(const String8& params);
// make available to PlayerDriver
void sendEvent(int msg, int ext1=0, int ext2=0) { MediaPlayerBase::sendEvent(msg, ext1, ext2); }
static status_t usePVPlayer(const char *filename);
static status_t usePVPlayer(int fd, int64_t offset, int64_t length);
void setIsResume(bool set) { mIsResume = set; }
bool getIsResume() { return mIsResume; }
void setIsPlaying(bool set) { mIsPlaying = set; }
bool getIsPlaying() { return mIsPlaying; }
bool isNotPaused();
int getCurrentPlayerState();
private:
static void do_nothing(status_t s, void *cookie, bool cancelled) { }
static void run_init(status_t s, void *cookie, bool cancelled);
static void run_set_video_surface(status_t s, void *cookie, bool cancelled);
static void run_set_audio_output(status_t s, void *cookie, bool cancelled);
static void run_prepare(status_t s, void *cookie, bool cancelled);
static void check_for_live_streaming(status_t s, void *cookie, bool cancelled);
PlayerDriver* mPlayerDriver;
char * mDataSourcePath;
bool mIsDataSourceSet;
sp<ISurface> mSurface;
int mSharedFd;
status_t mInit;
int mDuration;
int mPositionWhenSuspend;
bool mIsPlaying;
bool mIsResume;
#ifdef MAX_OPENCORE_INSTANCES
static volatile int32_t sNumInstances;
#endif
};
}; // namespace android
#endif // ANDROID_PVPLAYER_H
+314
View File
@@ -0,0 +1,314 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_TONEGENERATOR_H_
#define ANDROID_TONEGENERATOR_H_
#include <utils/RefBase.h>
#include <utils/KeyedVector.h>
#include <utils/threads.h>
#include <media/AudioSystem.h>
#include <media/AudioTrack.h>
namespace android {
class ToneGenerator {
public:
// List of all available tones
// This enum must be kept consistant with constants in ToneGenerator JAVA class
enum tone_type {
// DTMF tones ITU-T Recommendation Q.23
TONE_DTMF_0 = 0, // 0 key: 1336Hz, 941Hz
TONE_DTMF_1, // 1 key: 1209Hz, 697Hz
TONE_DTMF_2, // 2 key: 1336Hz, 697Hz
TONE_DTMF_3, // 3 key: 1477Hz, 697Hz
TONE_DTMF_4, // 4 key: 1209Hz, 770Hz
TONE_DTMF_5, // 5 key: 1336Hz, 770Hz
TONE_DTMF_6, // 6 key: 1477Hz, 770Hz
TONE_DTMF_7, // 7 key: 1209Hz, 852Hz
TONE_DTMF_8, // 8 key: 1336Hz, 852Hz
TONE_DTMF_9, // 9 key: 1477Hz, 852Hz
TONE_DTMF_S, // * key: 1209Hz, 941Hz
TONE_DTMF_P, // # key: 1477Hz, 941Hz
TONE_DTMF_A, // A key: 1633Hz, 697Hz
TONE_DTMF_B, // B key: 1633Hz, 770Hz
TONE_DTMF_C, // C key: 1633Hz, 852Hz
TONE_DTMF_D, // D key: 1633Hz, 941Hz
// Call supervisory tones: 3GPP TS 22.001 (CEPT)
TONE_SUP_DIAL, // Dial tone: CEPT: 425Hz, continuous
FIRST_SUP_TONE = TONE_SUP_DIAL,
TONE_SUP_BUSY, // Busy tone, CEPT: 425Hz, 500ms ON, 500ms OFF...
TONE_SUP_CONGESTION, // Congestion tone CEPT, JAPAN: 425Hz, 200ms ON, 200ms OFF...
TONE_SUP_RADIO_ACK, // Radio path acknowlegment, CEPT, ANSI: 425Hz, 200ms ON
TONE_SUP_RADIO_NOTAVAIL, // Radio path not available: 425Hz, 200ms ON, 200 OFF 3 bursts
TONE_SUP_ERROR, // Error/Special info: 950Hz+1400Hz+1800Hz, 330ms ON, 1s OFF...
TONE_SUP_CALL_WAITING, // Call Waiting CEPT,JAPAN: 425Hz, 200ms ON, 600ms OFF, 200ms ON, 3s OFF...
TONE_SUP_RINGTONE, // Ring Tone CEPT, JAPAN: 425Hz, 1s ON, 4s OFF...
LAST_SUP_TONE = TONE_SUP_RINGTONE,
// Proprietary tones: 3GPP TS 31.111
TONE_PROP_BEEP, // General beep: 400Hz+1200Hz, 35ms ON
TONE_PROP_ACK, // Positive Acknowlgement: 1200Hz, 100ms ON, 100ms OFF 2 bursts
TONE_PROP_NACK, // Negative Acknowlgement: 300Hz+400Hz+500Hz, 400ms ON
TONE_PROP_PROMPT, // Prompt tone: 400Hz+1200Hz, 200ms ON
TONE_PROP_BEEP2, // General double beep: 400Hz+1200Hz, 35ms ON, 200ms OFF, 35ms on
// Additional call supervisory tones: specified by IS-95 only
TONE_SUP_INTERCEPT, // Intercept tone: alternating 440 Hz and 620 Hz tones, each on for 250 ms.
TONE_SUP_INTERCEPT_ABBREV, // Abbreviated intercept: intercept tone limited to 4 seconds
TONE_SUP_CONGESTION_ABBREV, // Abbreviated congestion: congestion tone limited to 4 seconds
TONE_SUP_CONFIRM, // Confirm tone: a 350 Hz tone added to a 440 Hz tone repeated 3 times in a 100 ms on, 100 ms off cycle.
TONE_SUP_PIP, // Pip tone: four bursts of 480 Hz tone (0.1 s on, 0.1 s off).
// CDMA Tones
TONE_CDMA_DIAL_TONE_LITE,
TONE_CDMA_NETWORK_USA_RINGBACK,
TONE_CDMA_INTERCEPT,
TONE_CDMA_ABBR_INTERCEPT,
TONE_CDMA_REORDER,
TONE_CDMA_ABBR_REORDER,
TONE_CDMA_NETWORK_BUSY,
TONE_CDMA_CONFIRM,
TONE_CDMA_ANSWER,
TONE_CDMA_NETWORK_CALLWAITING,
TONE_CDMA_PIP,
// ISDN
TONE_CDMA_CALL_SIGNAL_ISDN_NORMAL, // ISDN Alert Normal
TONE_CDMA_CALL_SIGNAL_ISDN_INTERGROUP, // ISDN Intergroup
TONE_CDMA_CALL_SIGNAL_ISDN_SP_PRI, // ISDN SP PRI
TONE_CDMA_CALL_SIGNAL_ISDN_PAT3, // ISDN Alert PAT3
TONE_CDMA_CALL_SIGNAL_ISDN_PING_RING, // ISDN Alert PING RING
TONE_CDMA_CALL_SIGNAL_ISDN_PAT5, // ISDN Alert PAT5
TONE_CDMA_CALL_SIGNAL_ISDN_PAT6, // ISDN Alert PAT6
TONE_CDMA_CALL_SIGNAL_ISDN_PAT7, // ISDN Alert PAT7
// ISDN end
// IS54
TONE_CDMA_HIGH_L, // IS54 High Pitch Long
TONE_CDMA_MED_L, // IS54 Med Pitch Long
TONE_CDMA_LOW_L, // IS54 Low Pitch Long
TONE_CDMA_HIGH_SS, // IS54 High Pitch Short Short
TONE_CDMA_MED_SS, // IS54 Medium Pitch Short Short
TONE_CDMA_LOW_SS, // IS54 Low Pitch Short Short
TONE_CDMA_HIGH_SSL, // IS54 High Pitch Short Short Long
TONE_CDMA_MED_SSL, // IS54 Medium Pitch Short Short Long
TONE_CDMA_LOW_SSL, // IS54 Low Pitch Short Short Long
TONE_CDMA_HIGH_SS_2, // IS54 High Pitch Short Short 2
TONE_CDMA_MED_SS_2, // IS54 Med Pitch Short Short 2
TONE_CDMA_LOW_SS_2, // IS54 Low Pitch Short Short 2
TONE_CDMA_HIGH_SLS, // IS54 High Pitch Short Long Short
TONE_CDMA_MED_SLS, // IS54 Med Pitch Short Long Short
TONE_CDMA_LOW_SLS, // IS54 Low Pitch Short Long Short
TONE_CDMA_HIGH_S_X4, // IS54 High Pitch Short Short Short Short
TONE_CDMA_MED_S_X4, // IS54 Med Pitch Short Short Short Short
TONE_CDMA_LOW_S_X4, // IS54 Low Pitch Short Short Short Short
TONE_CDMA_HIGH_PBX_L, // PBX High Pitch Long
TONE_CDMA_MED_PBX_L, // PBX Med Pitch Long
TONE_CDMA_LOW_PBX_L, // PBX Low Pitch Long
TONE_CDMA_HIGH_PBX_SS, // PBX High Short Short
TONE_CDMA_MED_PBX_SS, // PBX Med Short Short
TONE_CDMA_LOW_PBX_SS, // PBX Low Short Short
TONE_CDMA_HIGH_PBX_SSL, // PBX High Short Short Long
TONE_CDMA_MED_PBX_SSL, // PBX Med Short Short Long
TONE_CDMA_LOW_PBX_SSL, // PBX Low Short Short Long
TONE_CDMA_HIGH_PBX_SLS, // PBX High SLS
TONE_CDMA_MED_PBX_SLS, // PBX Med SLS
TONE_CDMA_LOW_PBX_SLS, // PBX Low SLS
TONE_CDMA_HIGH_PBX_S_X4, // PBX High SSSS
TONE_CDMA_MED_PBX_S_X4, // PBX Med SSSS
TONE_CDMA_LOW_PBX_S_X4, // PBX LOW SSSS
//IS54 end
// proprietary
TONE_CDMA_ALERT_NETWORK_LITE,
TONE_CDMA_ALERT_AUTOREDIAL_LITE,
TONE_CDMA_ONE_MIN_BEEP,
TONE_CDMA_KEYPAD_VOLUME_KEY_LITE,
TONE_CDMA_PRESSHOLDKEY_LITE,
TONE_CDMA_ALERT_INCALL_LITE,
TONE_CDMA_EMERGENCY_RINGBACK,
TONE_CDMA_ALERT_CALL_GUARD,
TONE_CDMA_SOFT_ERROR_LITE,
TONE_CDMA_CALLDROP_LITE,
// proprietary end
TONE_CDMA_NETWORK_BUSY_ONE_SHOT,
TONE_CDMA_ABBR_ALERT,
TONE_CDMA_SIGNAL_OFF,
//CDMA end
TONE_CMAS,
NUM_TONES,
NUM_SUP_TONES = LAST_SUP_TONE-FIRST_SUP_TONE+1
};
ToneGenerator(int streamType, float volume, bool threadCanCallJava = false);
~ToneGenerator();
bool startTone(int toneType, int durationMs = -1);
void stopTone();
bool isInited() { return (mState == TONE_IDLE)?false:true;}
private:
enum tone_state {
TONE_IDLE, // ToneGenerator is being initialized or initialization failed
TONE_INIT, // ToneGenerator has been successfully initialized and is not playing
TONE_STARTING, // ToneGenerator is starting playing
TONE_PLAYING, // ToneGenerator is playing
TONE_STOPPING, // ToneGenerator is stoping
TONE_STOPPED, // ToneGenerator is stopped: the AudioTrack will be stopped
TONE_RESTARTING // A start request was received in active state (playing or stopping)
};
// Region specific tones.
// These supervisory tones are different depending on the region (USA/CANADA, JAPAN, rest of the world).
// When a tone in the range [FIRST_SUP_TONE, LAST_SUP_TONE] is requested, the region is determined
// from system property gsm.operator.iso-country and the proper tone descriptor is selected with the
// help of sToneMappingTable[]
enum regional_tone_type {
// ANSI supervisory tones
TONE_ANSI_DIAL = NUM_TONES, // Dial tone: a continuous 350 Hz + 440 Hz tone.
TONE_ANSI_BUSY, // Busy tone on: a 480 Hz + 620 Hz tone repeated in a 500 ms on, 500 ms off cycle.
TONE_ANSI_CONGESTION, // Network congestion (reorder) tone on: a 480 Hz + 620 Hz tone repeated in a 250 ms on, 250 ms off cycle.
TONE_ANSI_CALL_WAITING, // Call waiting tone on: 440 Hz, on for 300 ms, 9,7 s off followed by
// (440 Hz, on for 100 ms off for 100 ms, on for 100 ms, 9,7s off and repeated as necessary).
TONE_ANSI_RINGTONE, // Ring Tone: a 440 Hz + 480 Hz tone repeated in a 2 s on, 4 s off pattern.
// JAPAN Supervisory tones
TONE_JAPAN_DIAL, // Dial tone: 400Hz, continuous
TONE_JAPAN_BUSY, // Busy tone: 400Hz, 500ms ON, 500ms OFF...
TONE_JAPAN_RADIO_ACK, // Radio path acknowlegment: 400Hz, 1s ON, 2s OFF...
NUM_ALTERNATE_TONES
};
enum region {
ANSI,
JAPAN,
CEPT,
NUM_REGIONS
};
static const unsigned char sToneMappingTable[NUM_REGIONS-1][NUM_SUP_TONES];
static const unsigned int TONEGEN_MAX_WAVES = 3; // Maximun number of sine waves in a tone segment
static const unsigned int TONEGEN_MAX_SEGMENTS = 12; // Maximun number of segments in a tone descriptor
static const unsigned int TONEGEN_INF = 0xFFFFFFFF; // Represents infinite time duration
static const float TONEGEN_GAIN = 0.9; // Default gain passed to WaveGenerator().
// ToneDescriptor class contains all parameters needed to generate a tone:
// - The array waveFreq[]:
// 1 for static tone descriptors: contains the frequencies of all individual waves making the multi-tone.
// 2 for active tone descritors: contains the indexes of the WaveGenerator objects in mWaveGens
// The number of sine waves varies from 1 to TONEGEN_MAX_WAVES.
// The first null value indicates that no more waves are needed.
// - The array segments[] is used to generate the tone pulses. A segment is a period of time
// during which the tone is ON or OFF. Segments with even index (starting from 0)
// correspond to tone ON state and segments with odd index to OFF state.
// The data stored in segments[] is the duration of the corresponding period in ms.
// The first segment encountered with a 0 duration indicates that no more segment follows.
// - loopCnt - Number of times to repeat a sequence of seqments after playing this
// - loopIndx - The segment index to go back and play is loopcnt > 0
// - repeatCnt indicates the number of times the sequence described by segments[] array must be repeated.
// When the tone generator encounters the first 0 duration segment, it will compare repeatCnt to mCurCount.
// If mCurCount > repeatCnt, the tone is stopped automatically. Otherwise, tone sequence will be
// restarted from segment repeatSegment.
// - repeatSegment number of the first repeated segment when repeatCnt is not null
class ToneSegment {
public:
unsigned int duration;
unsigned short waveFreq[TONEGEN_MAX_WAVES+1];
unsigned short loopCnt;
unsigned short loopIndx;
};
class ToneDescriptor {
public:
ToneSegment segments[TONEGEN_MAX_SEGMENTS+1];
unsigned long repeatCnt;
unsigned long repeatSegment;
};
static const ToneDescriptor sToneDescriptors[];
bool mThreadCanCallJava;
unsigned int mTotalSmp; // Total number of audio samples played (gives current time)
unsigned int mNextSegSmp; // Position of next segment transition expressed in samples
// NOTE: because mTotalSmp, mNextSegSmp are stored on 32 bit, current design will operate properly
// only if tone duration is less than about 27 Hours(@44100Hz sampling rate). If this time is exceeded,
// no crash will occur but tone sequence will show a glitch.
unsigned int mMaxSmp; // Maximum number of audio samples played (maximun tone duration)
int mDurationMs; // Maximum tone duration in ms
unsigned short mCurSegment; // Current segment index in ToneDescriptor segments[]
unsigned short mCurCount; // Current sequence repeat count
volatile unsigned short mState; // ToneGenerator state (tone_state)
unsigned short mRegion;
const ToneDescriptor *mpToneDesc; // pointer to active tone descriptor
const ToneDescriptor *mpNewToneDesc; // pointer to next active tone descriptor
unsigned short mLoopCounter; // Current tone loopback count
int mSamplingRate; // AudioFlinger Sampling rate
AudioTrack *mpAudioTrack; // Pointer to audio track used for playback
Mutex mLock; // Mutex to control concurent access to ToneGenerator object from audio callback and application API
Mutex mCbkCondLock; // Mutex associated to mWaitCbkCond
Condition mWaitCbkCond; // condition enabling interface to wait for audio callback completion after a change is requested
float mVolume; // Volume applied to audio track
int mStreamType; // Audio stream used for output
unsigned int mProcessSize; // Size of audio blocks generated at a time by audioCallback() (in PCM frames).
bool initAudioTrack();
static void audioCallback(int event, void* user, void *info);
bool prepareWave();
unsigned int numWaves(unsigned int segmentIdx);
void clearWaveGens();
int getToneForRegion(int toneType);
// WaveGenerator generates a single sine wave
class WaveGenerator {
public:
enum gen_command {
WAVEGEN_START, // Start/restart wave from phase 0
WAVEGEN_CONT, // Continue wave from current phase
WAVEGEN_STOP // Stop wave on zero crossing
};
WaveGenerator(unsigned short samplingRate, unsigned short frequency,
float volume);
~WaveGenerator();
void getSamples(short *outBuffer, unsigned int count,
unsigned int command);
private:
static const short GEN_AMP = 32000; // amplitude of generator
static const short S_Q14 = 14; // shift for Q14
static const short S_Q15 = 15; // shift for Q15
short mA1_Q14; // Q14 coefficient
// delay line of full amplitude generator
short mS1, mS2; // delay line S2 oldest
short mS2_0; // saved value for reinitialisation
short mAmplitude_Q15; // Q15 amplitude
};
KeyedVector<unsigned short, WaveGenerator *> mWaveGens; // list of active wave generators.
};
}
; // namespace android
#endif /*ANDROID_TONEGENERATOR_H_*/
+159
View File
@@ -0,0 +1,159 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEDIA_VISUALIZER_H
#define ANDROID_MEDIA_VISUALIZER_H
#include <media/AudioEffect.h>
#include <media/EffectVisualizerApi.h>
#include <string.h>
/**
* The Visualizer class enables application to retrieve part of the currently playing audio for
* visualization purpose. It is not an audio recording interface and only returns partial and low
* quality audio content. However, to protect privacy of certain audio data (e.g voice mail) the use
* of the visualizer requires the permission android.permission.RECORD_AUDIO.
* The audio session ID passed to the constructor indicates which audio content should be
* visualized:
* - If the session is 0, the audio output mix is visualized
* - If the session is not 0, the audio from a particular MediaPlayer or AudioTrack
* using this audio session is visualized
* Two types of representation of audio content can be captured:
* - Waveform data: consecutive 8-bit (unsigned) mono samples by using the getWaveForm() method
* - Frequency data: 8-bit magnitude FFT by using the getFft() method
*
* The length of the capture can be retrieved or specified by calling respectively
* getCaptureSize() and setCaptureSize() methods. Note that the size of the FFT
* is half of the specified capture size but both sides of the spectrum are returned yielding in a
* number of bytes equal to the capture size. The capture size must be a power of 2 in the range
* returned by getMinCaptureSize() and getMaxCaptureSize().
* In addition to the polling capture mode, a callback mode is also available by installing a
* callback function by use of the setCaptureCallBack() method. The rate at which the callback
* is called as well as the type of data returned is specified.
* Before capturing data, the Visualizer must be enabled by calling the setEnabled() method.
* When data capture is not needed any more, the Visualizer should be disabled.
*/
namespace android {
// ----------------------------------------------------------------------------
class Visualizer: public AudioEffect {
public:
enum callback_flags {
CAPTURE_WAVEFORM = 0x00000001, // capture callback returns a PCM wave form
CAPTURE_FFT = 0x00000002, // apture callback returns a frequency representation
CAPTURE_CALL_JAVA = 0x00000004 // the callback thread can call java
};
/* Constructor.
* See AudioEffect constructor for details on parameters.
*/
Visualizer(int32_t priority = 0,
effect_callback_t cbf = 0,
void* user = 0,
int sessionId = 0);
~Visualizer();
virtual status_t setEnabled(bool enabled);
// maximum capture size in samples
static uint32_t getMaxCaptureSize() { return VISUALIZER_CAPTURE_SIZE_MAX; }
// minimum capture size in samples
static uint32_t getMinCaptureSize() { return VISUALIZER_CAPTURE_SIZE_MIN; }
// maximum capture rate in millihertz
static uint32_t getMaxCaptureRate() { return CAPTURE_RATE_MAX; }
// callback used to return periodic PCM or FFT captures to the application. Either one or both
// types of data are returned (PCM and FFT) according to flags indicated when installing the
// callback. When a type of data is not present, the corresponding size (waveformSize or
// fftSize) is 0.
typedef void (*capture_cbk_t)(void* user,
uint32_t waveformSize,
uint8_t *waveform,
uint32_t fftSize,
uint8_t *fft,
uint32_t samplingrate);
// install a callback to receive periodic captures. The capture rate is specified in milliHertz
// and the capture format is according to flags (see callback_flags).
status_t setCaptureCallBack(capture_cbk_t cbk, void* user, uint32_t flags, uint32_t rate);
// set the capture size capture size must be a power of two in the range
// [VISUALIZER_CAPTURE_SIZE_MAX. VISUALIZER_CAPTURE_SIZE_MIN]
// must be called when the visualizer is not enabled
status_t setCaptureSize(uint32_t size);
uint32_t getCaptureSize() { return mCaptureSize; }
// returns the capture rate indicated when installing the callback
uint32_t getCaptureRate() { return mCaptureRate; }
// returns the sampling rate of the audio being captured
uint32_t getSamplingRate() { return mSampleRate; }
// return a capture in PCM 8 bit unsigned format. The size of the capture is equal to
// getCaptureSize()
status_t getWaveForm(uint8_t *waveform);
// return a capture in FFT 8 bit signed format. The size of the capture is equal to
// getCaptureSize() but the length of the FFT is half of the size (both parts of the spectrum
// are returned
status_t getFft(uint8_t *fft);
private:
static const uint32_t CAPTURE_RATE_MAX = 20000;
static const uint32_t CAPTURE_RATE_DEF = 10000;
static const uint32_t CAPTURE_SIZE_DEF = VISUALIZER_CAPTURE_SIZE_MAX;
/* internal class to handle the callback */
class CaptureThread : public Thread
{
public:
CaptureThread(Visualizer& receiver, uint32_t captureRate, bool bCanCallJava = false);
private:
friend class Visualizer;
virtual bool threadLoop();
virtual status_t readyToRun();
virtual void onFirstRef();
Visualizer& mReceiver;
Mutex mLock;
uint32_t mSleepTimeUs;
};
status_t doFft(uint8_t *fft, uint8_t *waveform);
void periodicCapture();
uint32_t initCaptureSize();
Mutex mLock;
uint32_t mCaptureRate;
uint32_t mCaptureSize;
uint32_t mSampleRate;
capture_cbk_t mCaptureCallBack;
void *mCaptureCbkUser;
sp<CaptureThread> mCaptureThread;
uint32_t mCaptureFlags;
};
}; // namespace android
#endif // ANDROID_MEDIA_VISUALIZER_H
@@ -0,0 +1,87 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIAMETADATARETRIEVER_H
#define MEDIAMETADATARETRIEVER_H
#include <utils/Errors.h> // for status_t
#include <utils/threads.h>
#include <binder/IMemory.h>
#include <media/IMediaMetadataRetriever.h>
namespace android {
class IMediaPlayerService;
class IMediaMetadataRetriever;
// Keep these in synch with the constants defined in MediaMetadataRetriever.java
// class.
enum {
METADATA_KEY_CD_TRACK_NUMBER = 0,
METADATA_KEY_ALBUM = 1,
METADATA_KEY_ARTIST = 2,
METADATA_KEY_AUTHOR = 3,
METADATA_KEY_COMPOSER = 4,
METADATA_KEY_DATE = 5,
METADATA_KEY_GENRE = 6,
METADATA_KEY_TITLE = 7,
METADATA_KEY_YEAR = 8,
METADATA_KEY_DURATION = 9,
METADATA_KEY_NUM_TRACKS = 10,
METADATA_KEY_WRITER = 11,
METADATA_KEY_MIMETYPE = 12,
METADATA_KEY_ALBUMARTIST = 13,
METADATA_KEY_DISC_NUMBER = 14,
METADATA_KEY_COMPILATION = 15,
// Add more here...
};
class MediaMetadataRetriever: public RefBase
{
public:
MediaMetadataRetriever();
~MediaMetadataRetriever();
void disconnect();
status_t setDataSource(const char* dataSourceUrl);
status_t setDataSource(int fd, int64_t offset, int64_t length);
sp<IMemory> getFrameAtTime(int64_t timeUs, int option);
sp<IMemory> extractAlbumArt();
const char* extractMetadata(int keyCode);
private:
static const sp<IMediaPlayerService>& getService();
class DeathNotifier: public IBinder::DeathRecipient
{
public:
DeathNotifier() {}
virtual ~DeathNotifier();
virtual void binderDied(const wp<IBinder>& who);
};
static sp<DeathNotifier> sDeathNotifier;
static Mutex sServiceLock;
static sp<IMediaPlayerService> sService;
Mutex mLock;
sp<IMediaMetadataRetriever> mRetriever;
};
}; // namespace android
#endif // MEDIAMETADATARETRIEVER_H
+222
View File
@@ -0,0 +1,222 @@
/*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEDIAPLAYER_H
#define ANDROID_MEDIAPLAYER_H
#include <binder/IMemory.h>
#include <media/IMediaPlayerClient.h>
#include <media/IMediaPlayer.h>
#include <media/IMediaDeathNotifier.h>
#include <utils/KeyedVector.h>
#include <utils/String8.h>
namespace android {
class Surface;
enum media_invoke_type {
MEDIA_INVOKE_REGISTER_BUFFERS = 1,
MEDIA_INVOKE_UNREGISTER_BUFFERS = 2,
MEDIA_INVOKE_QUEUE_BUFFER = 3,
MEDIA_INVOKE_QUERY_BUFFER_FORMAT = 4,
};
enum media_event_type {
MEDIA_NOP = 0, // interface test message
MEDIA_PREPARED = 1,
MEDIA_PLAYBACK_COMPLETE = 2,
MEDIA_BUFFERING_UPDATE = 3,
MEDIA_SEEK_COMPLETE = 4,
MEDIA_SET_VIDEO_SIZE = 5,
MEDIA_ERROR = 100,
MEDIA_INFO = 200,
MEDIA_FORMAT_CHANGED = 1001, // video format changed, shared memory buffers need to be freed and reallocated
MEDIA_BUFFER_READY = 1002, // return buffer to mediaplayer client
};
// Generic error codes for the media player framework. Errors are fatal, the
// playback must abort.
//
// Errors are communicated back to the client using the
// MediaPlayerListener::notify method defined below.
// In this situation, 'notify' is invoked with the following:
// 'msg' is set to MEDIA_ERROR.
// 'ext1' should be a value from the enum media_error_type.
// 'ext2' contains an implementation dependant error code to provide
// more details. Should default to 0 when not used.
//
// The codes are distributed as follow:
// 0xx: Reserved
// 1xx: Android Player errors. Something went wrong inside the MediaPlayer.
// 2xx: Media errors (e.g Codec not supported). There is a problem with the
// media itself.
// 3xx: Runtime errors. Some extraordinary condition arose making the playback
// impossible.
//
enum media_error_type {
// 0xx
MEDIA_ERROR_UNKNOWN = 1,
// 1xx
MEDIA_ERROR_SERVER_DIED = 100,
// 2xx
MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200,
// 3xx
};
// Info and warning codes for the media player framework. These are non fatal,
// the playback is going on but there might be some user visible issues.
//
// Info and warning messages are communicated back to the client using the
// MediaPlayerListener::notify method defined below. In this situation,
// 'notify' is invoked with the following:
// 'msg' is set to MEDIA_INFO.
// 'ext1' should be a value from the enum media_info_type.
// 'ext2' contains an implementation dependant info code to provide
// more details. Should default to 0 when not used.
//
// The codes are distributed as follow:
// 0xx: Reserved
// 7xx: Android Player info/warning (e.g player lagging behind.)
// 8xx: Media info/warning (e.g media badly interleaved.)
//
enum media_info_type {
// 0xx
MEDIA_INFO_UNKNOWN = 1,
// 7xx
// The video is too complex for the decoder: it can't decode frames fast
// enough. Possibly only the audio plays fine at this stage.
MEDIA_INFO_VIDEO_TRACK_LAGGING = 700,
// MediaPlayer is temporarily pausing playback internally in order to
// buffer more data.
MEDIA_INFO_BUFFERING_START = 701,
// MediaPlayer is resuming playback after filling buffers.
MEDIA_INFO_BUFFERING_END = 702,
// 8xx
// Bad interleaving means that a media has been improperly interleaved or not
// interleaved at all, e.g has all the video samples first then all the audio
// ones. Video is playing but a lot of disk seek may be happening.
MEDIA_INFO_BAD_INTERLEAVING = 800,
// The media is not seekable (e.g live stream).
MEDIA_INFO_NOT_SEEKABLE = 801,
// New media metadata is available.
MEDIA_INFO_METADATA_UPDATE = 802,
};
enum media_player_states {
MEDIA_PLAYER_STATE_ERROR = 0,
MEDIA_PLAYER_IDLE = 1 << 0,
MEDIA_PLAYER_INITIALIZED = 1 << 1,
MEDIA_PLAYER_PREPARING = 1 << 2,
MEDIA_PLAYER_PREPARED = 1 << 3,
MEDIA_PLAYER_STARTED = 1 << 4,
MEDIA_PLAYER_PAUSED = 1 << 5,
MEDIA_PLAYER_STOPPED = 1 << 6,
MEDIA_PLAYER_PLAYBACK_COMPLETE = 1 << 7
};
// ----------------------------------------------------------------------------
// ref-counted object for callbacks
class MediaPlayerListener: virtual public RefBase
{
public:
virtual void notify(int msg, int ext1, int ext2) = 0;
};
class MediaPlayer : public BnMediaPlayerClient,
public virtual IMediaDeathNotifier
{
public:
MediaPlayer();
~MediaPlayer();
void died();
void disconnect();
status_t setDataSource(
const char *url,
const KeyedVector<String8, String8> *headers);
status_t setDataSource(int fd, int64_t offset, int64_t length);
status_t setVideoSurface(const sp<Surface>& surface);
status_t setListener(const sp<MediaPlayerListener>& listener);
status_t prepare();
status_t prepareAsync();
status_t start();
status_t stop();
status_t pause();
bool isPlaying();
status_t getVideoWidth(int *w);
status_t getVideoHeight(int *h);
status_t seekTo(int msec);
status_t getCurrentPosition(int *msec);
status_t getDuration(int *msec);
status_t reset();
status_t setAudioStreamType(int type);
status_t setLooping(int loop);
bool isLooping();
status_t setVolume(float leftVolume, float rightVolume);
void notify(int msg, int ext1, int ext2);
static sp<IMemory> decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
static sp<IMemory> decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
status_t invoke(const Parcel& request, Parcel *reply);
status_t setMetadataFilter(const Parcel& filter);
status_t getMetadata(bool update_only, bool apply_filter, Parcel *metadata);
status_t suspend();
status_t resume();
status_t setAudioSessionId(int sessionId);
int getAudioSessionId();
status_t setAuxEffectSendLevel(float level);
status_t attachAuxEffect(int effectId);
status_t setVideoSurface(const sp<ISurface>& surface);
status_t setParameters(const String8& params);
private:
void clear_l();
status_t seekTo_l(int msec);
status_t prepareAsync_l();
status_t getDuration_l(int *msec);
status_t setDataSource(const sp<IMediaPlayer>& player);
sp<IMediaPlayer> mPlayer;
thread_id_t mLockThreadId;
Mutex mLock;
Mutex mNotifyLock;
Condition mSignal;
sp<MediaPlayerListener> mListener;
void* mCookie;
media_player_states mCurrentState;
int mDuration;
int mCurrentPosition;
int mSeekPosition;
bool mPrepareSync;
status_t mPrepareStatus;
int mStreamType;
bool mLoop;
float mLeftVolume;
float mRightVolume;
int mVideoWidth;
int mVideoHeight;
int mAudioSessionId;
float mSendLevel;
};
}; // namespace android
#endif // ANDROID_MEDIAPLAYER_H
+224
View File
@@ -0,0 +1,224 @@
/*
** Copyright (C) 2008 The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
**
** limitations under the License.
*/
#ifndef ANDROID_MEDIARECORDER_H
#define ANDROID_MEDIARECORDER_H
#include <utils/Log.h>
#include <utils/threads.h>
#include <utils/List.h>
#include <utils/Errors.h>
#include <media/IMediaRecorderClient.h>
#include <media/IMediaDeathNotifier.h>
namespace android {
class Surface;
class IMediaRecorder;
class ICamera;
typedef void (*media_completion_f)(status_t status, void *cookie);
/* Do not change these values without updating their counterparts
* in media/java/android/media/MediaRecorder.java!
*/
enum audio_source {
AUDIO_SOURCE_DEFAULT = 0,
AUDIO_SOURCE_MIC = 1,
AUDIO_SOURCE_VOICE_UPLINK = 2,
AUDIO_SOURCE_VOICE_DOWNLINK = 3,
AUDIO_SOURCE_VOICE_CALL = 4,
AUDIO_SOURCE_CAMCORDER = 5,
AUDIO_SOURCE_VOICE_RECOGNITION = 6,
AUDIO_SOURCE_VOICE_COMMUNICATION = 7,
AUDIO_SOURCE_FM_RX = 8,
AUDIO_SOURCE_FM_RX_A2DP = 9,
AUDIO_SOURCE_MAX = AUDIO_SOURCE_FM_RX_A2DP,
AUDIO_SOURCE_LIST_END // must be last - used to validate audio source type
};
enum video_source {
VIDEO_SOURCE_DEFAULT = 0,
VIDEO_SOURCE_CAMERA = 1,
VIDEO_SOURCE_LIST_END // must be last - used to validate audio source type
};
//Please update media/java/android/media/MediaRecorder.java if the following is updated.
enum output_format {
OUTPUT_FORMAT_DEFAULT = 0,
OUTPUT_FORMAT_THREE_GPP = 1,
OUTPUT_FORMAT_MPEG_4 = 2,
OUTPUT_FORMAT_AUDIO_ONLY_START = 3, // Used in validating the output format. Should be the
// at the start of the audio only output formats.
/* These are audio only file formats */
OUTPUT_FORMAT_RAW_AMR = 3, //to be backward compatible
OUTPUT_FORMAT_AMR_NB = 3,
OUTPUT_FORMAT_AMR_WB = 4,
OUTPUT_FORMAT_AAC_ADIF = 5,
OUTPUT_FORMAT_AAC_ADTS = 6,
/* Stream over a socket, limited to a single stream */
OUTPUT_FORMAT_RTP_AVP = 7,
/* H.264/AAC data encapsulated in MPEG2/TS */
OUTPUT_FORMAT_MPEG2TS = 8,
OUTPUT_FORMAT_QCP = 9, // QCP file format
OUTPUT_FORMAT_THREE_GPP2 = 10, /*3GPP2*/
OUTPUT_FORMAT_LIST_END // must be last - used to validate format type
};
enum audio_encoder {
AUDIO_ENCODER_DEFAULT = 0,
AUDIO_ENCODER_AMR_NB = 1,
AUDIO_ENCODER_AMR_WB = 2,
AUDIO_ENCODER_AAC = 3,
AUDIO_ENCODER_AAC_PLUS = 4,
AUDIO_ENCODER_EAAC_PLUS = 5,
AUDIO_ENCODER_EVRC = 6,
AUDIO_ENCODER_QCELP = 7,
AUDIO_ENCODER_LIST_END // must be the last - used to validate the audio encoder type
};
enum video_encoder {
VIDEO_ENCODER_DEFAULT = 0,
VIDEO_ENCODER_H263 = 1,
VIDEO_ENCODER_H264 = 2,
VIDEO_ENCODER_MPEG_4_SP = 3,
VIDEO_ENCODER_LIST_END // must be the last - used to validate the video encoder type
};
/*
* The state machine of the media_recorder uses a set of different state names.
* The mapping between the media_recorder and the pvauthorengine is shown below:
*
* mediarecorder pvauthorengine
* ----------------------------------------------------------------
* MEDIA_RECORDER_ERROR ERROR
* MEDIA_RECORDER_IDLE IDLE
* MEDIA_RECORDER_INITIALIZED OPENED
* MEDIA_RECORDER_DATASOURCE_CONFIGURED
* MEDIA_RECORDER_PREPARED INITIALIZED
* MEDIA_RECORDER_RECORDING RECORDING
*/
enum media_recorder_states {
MEDIA_RECORDER_ERROR = 0,
MEDIA_RECORDER_IDLE = 1 << 0,
MEDIA_RECORDER_INITIALIZED = 1 << 1,
MEDIA_RECORDER_DATASOURCE_CONFIGURED = 1 << 2,
MEDIA_RECORDER_PREPARED = 1 << 3,
MEDIA_RECORDER_RECORDING = 1 << 4,
};
// The "msg" code passed to the listener in notify.
enum media_recorder_event_type {
MEDIA_RECORDER_EVENT_ERROR = 1,
MEDIA_RECORDER_EVENT_INFO = 2,
MEDIA_RECORDER_MSG_COMPRESSED_IMAGE = 8
};
enum media_recorder_error_type {
MEDIA_RECORDER_ERROR_UNKNOWN = 1,
MEDIA_RECORDER_ERROR_RESOURCE = 2
};
// The codes are distributed as follow:
// 0xx: Reserved
// 8xx: General info/warning
//
enum media_recorder_info_type {
MEDIA_RECORDER_INFO_UNKNOWN = 1,
MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800,
MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801,
MEDIA_RECORDER_INFO_COMPLETION_STATUS = 802,
MEDIA_RECORDER_INFO_PROGRESS_FRAME_STATUS = 803,
MEDIA_RECORDER_INFO_PROGRESS_TIME_STATUS = 804,
MEDIA_RECORDER_UNSUPPORTED_RESOLUTION = 805,
};
// ----------------------------------------------------------------------------
// ref-counted object for callbacks
class MediaRecorderListener: virtual public RefBase
{
public:
virtual void notify(int msg, int ext1, int ext2) = 0;
virtual void postData(int32_t msgType, const sp<IMemory>& dataPtr) = 0;
};
class MediaRecorder : public BnMediaRecorderClient,
public virtual IMediaDeathNotifier
{
public:
MediaRecorder();
~MediaRecorder();
void died();
status_t initCheck();
status_t setCamera(const sp<ICamera>& camera);
status_t setPreviewSurface(const sp<Surface>& surface);
status_t setVideoSource(int vs);
status_t setAudioSource(int as);
status_t setOutputFormat(int of);
status_t setVideoEncoder(int ve);
status_t setAudioEncoder(int ae);
status_t setOutputFile(const char* path);
status_t setOutputFile(int fd, int64_t offset, int64_t length);
status_t setVideoSize(int width, int height);
status_t setVideoFrameRate(int frames_per_second);
status_t setParameters(const String8& params);
status_t setCameraParameters(const String8& params);
status_t setListener(const sp<MediaRecorderListener>& listener);
status_t prepare();
status_t getMaxAmplitude(int* max);
status_t start();
status_t takeLiveSnapshot();
status_t stop();
status_t reset();
status_t init();
status_t close();
status_t release();
void notify(int msg, int ext1, int ext2);
void dataCallback(int32_t msgType, const sp<IMemory>& dataPtr);
private:
void doCleanUp();
status_t doReset();
sp<IMediaRecorder> mMediaRecorder;
sp<MediaRecorderListener> mListener;
media_recorder_states mCurrentState;
bool mIsAudioSourceSet;
bool mIsVideoSourceSet;
bool mIsAudioEncoderSet;
bool mIsVideoEncoderSet;
bool mIsOutputFileSet;
Mutex mLock;
Mutex mNotifyLock;
Mutex mdataCallbackLock;
};
}; // namespace android
#endif // ANDROID_MEDIARECORDER_H
+96
View File
@@ -0,0 +1,96 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIASCANNER_H
#define MEDIASCANNER_H
#include <utils/Log.h>
#include <utils/threads.h>
#include <utils/List.h>
#include <utils/Errors.h>
#include <pthread.h>
namespace android {
class MediaScannerClient;
class StringArray;
struct MediaScanner {
MediaScanner();
virtual ~MediaScanner();
virtual status_t processFile(
const char *path, const char *mimeType,
MediaScannerClient &client) = 0;
typedef bool (*ExceptionCheck)(void* env);
virtual status_t processDirectory(
const char *path, const char *extensions,
MediaScannerClient &client,
ExceptionCheck exceptionCheck, void *exceptionEnv);
void setLocale(const char *locale);
// extracts album art as a block of data
virtual char *extractAlbumArt(int fd) = 0;
protected:
const char *locale() const;
private:
// current locale (like "ja_JP"), created/destroyed with strdup()/free()
char *mLocale;
status_t doProcessDirectory(
char *path, int pathRemaining, const char *extensions,
MediaScannerClient &client, ExceptionCheck exceptionCheck,
void *exceptionEnv);
MediaScanner(const MediaScanner &);
MediaScanner &operator=(const MediaScanner &);
};
class MediaScannerClient
{
public:
MediaScannerClient();
virtual ~MediaScannerClient();
void setLocale(const char* locale);
void beginFile();
bool addStringTag(const char* name, const char* value);
void endFile();
virtual bool scanFile(const char* path, long long lastModified, long long fileSize) = 0;
virtual bool handleStringTag(const char* name, const char* value) = 0;
virtual bool setMimeType(const char* mimeType) = 0;
virtual bool addNoMediaFolder(const char* path) = 0;
protected:
void convertValues(uint32_t encoding);
protected:
// cached name and value strings, for native encoding support.
StringArray* mNames;
StringArray* mValues;
// default encoding based on MediaScanner::mLocale string
uint32_t mLocaleEncoding;
};
}; // namespace android
#endif // MEDIASCANNER_H
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AMR_WRITER_H_
#define AMR_WRITER_H_
#include <stdio.h>
#include <media/stagefright/MediaWriter.h>
#include <utils/threads.h>
namespace android {
struct MediaSource;
struct MetaData;
struct AMRWriter : public MediaWriter {
AMRWriter(const char *filename);
AMRWriter(int fd);
status_t initCheck() const;
virtual status_t addSource(const sp<MediaSource> &source);
virtual bool reachedEOS();
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual status_t pause();
protected:
virtual ~AMRWriter();
private:
FILE *mFile;
status_t mInitCheck;
sp<MediaSource> mSource;
bool mStarted;
volatile bool mPaused;
volatile bool mResumed;
volatile bool mDone;
volatile bool mReachedEOS;
pthread_t mThread;
int64_t mEstimatedSizeBytes;
int64_t mEstimatedDurationUs;
static void *ThreadWrapper(void *);
status_t threadFunc();
bool exceedsFileSizeLimit();
bool exceedsFileDurationLimit();
AMRWriter(const AMRWriter &);
AMRWriter &operator=(const AMRWriter &);
};
} // namespace android
#endif // AMR_WRITER_H_
@@ -0,0 +1,118 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AUDIO_PLAYER_H_
#define AUDIO_PLAYER_H_
#include <media/MediaPlayerInterface.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/TimeSource.h>
#include <utils/threads.h>
namespace android {
class MediaSource;
class AudioTrack;
class AwesomePlayer;
class AudioPlayer : public TimeSource {
public:
enum {
REACHED_EOS,
SEEK_COMPLETE
};
AudioPlayer(const sp<MediaPlayerBase::AudioSink> &audioSink,
AwesomePlayer *audioObserver = NULL);
virtual ~AudioPlayer();
// Caller retains ownership of "source".
virtual void setSource(const sp<MediaSource> &source);
// Return time in us.
virtual int64_t getRealTimeUs();
virtual status_t start(bool sourceAlreadyStarted = false);
virtual void pause(bool playPendingSamples = false);
virtual void resume();
// Returns the timestamp of the last buffer played (in us).
virtual int64_t getMediaTimeUs();
// Returns true iff a mapping is established, i.e. the AudioPlayer
// has played at least one frame of audio.
virtual bool getMediaTimeMapping(int64_t *realtime_us, int64_t *mediatime_us);
virtual status_t seekTo(int64_t time_us);
virtual bool isSeeking();
virtual bool reachedEOS(status_t *finalStatus);
private:
sp<MediaSource> mSource;
AudioTrack *mAudioTrack;
MediaBuffer *mInputBuffer;
int mSampleRate;
int64_t mLatencyUs;
size_t mFrameSize;
Mutex mLock;
int64_t mNumFramesPlayed;
int64_t mPositionTimeMediaUs;
int64_t mPositionTimeRealUs;
bool mSeeking;
bool mReachedEOS;
status_t mFinalStatus;
int64_t mSeekTimeUs;
bool mStarted;
bool mSourceStopped;
bool mIsFirstBuffer;
status_t mFirstBufferResult;
MediaBuffer *mFirstBuffer;
sp<MediaPlayerBase::AudioSink> mAudioSink;
AwesomePlayer *mObserver;
bool mPaused;
static void AudioCallback(int event, void *user, void *info);
void AudioCallback(int event, void *info);
static size_t AudioSinkCallback(
MediaPlayerBase::AudioSink *audioSink,
void *data, size_t size, void *me);
size_t fillBuffer(void *data, size_t size);
int64_t getRealTimeUsLocked() const;
void reset();
AudioPlayer(const AudioPlayer &);
AudioPlayer &operator=(const AudioPlayer &);
};
} // namespace android
#endif // AUDIO_PLAYER_H_
@@ -0,0 +1,106 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AUDIO_SOURCE_H_
#define AUDIO_SOURCE_H_
#include <media/AudioSystem.h>
#include <media/stagefright/MediaSource.h>
namespace android {
class AudioRecord;
struct MediaBufferGroup;
struct AudioSource : public MediaSource {
// Note that the "channels" parameter is _not_ the number of channels,
// but a bitmask of AudioSystem::audio_channels constants.
AudioSource(
int inputSource, uint32_t sampleRate,
uint32_t channels = AudioSystem::CHANNEL_IN_MONO);
status_t initCheck() const;
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual sp<MetaData> getFormat();
// Returns the maximum amplitude since last call.
int16_t getMaxAmplitude();
virtual status_t read(
MediaBuffer **buffer, const ReadOptions *options = NULL);
protected:
virtual ~AudioSource();
private:
enum {
kMaxBufferSize = 4096,
// After the initial mute, we raise the volume linearly
// over kAutoRampDurationUs.
kAutoRampDurationUs = 700000,
// This is the initial mute duration to suppress
// the video recording signal tone
kAutoRampStartUs = 1000000,
};
AudioRecord *mRecord;
status_t mInitCheck;
bool mStarted;
bool mFirstFrame;
bool mCollectStats;
bool mTrackMaxAmplitude;
int64_t mStartTimeUs;
int16_t mMaxAmplitude;
int64_t mPrevSampleTimeUs;
int64_t mTotalLostFrames;
int64_t mPrevLostBytes;
int64_t mInitialReadTimeUs;
MediaBufferGroup *mGroup;
void trackMaxAmplitude(int16_t *data, int nSamples);
// This is used to raise the volume from mute to the
// actual level linearly.
void rampVolume(
int32_t startFrame, int32_t rampDurationFrames,
uint8_t *data, size_t bytes);
AudioSource(const AudioSource &);
AudioSource &operator=(const AudioSource &);
//additions for tunnel source
public:
AudioSource(
int inputSource, const sp<MetaData>& meta );
private:
int32_t mFormat;
String8 mMime;
int32_t mMaxBufferSize;
int32_t mNumChannels;
int64_t bufferDurationUs( ssize_t n );
};
} // namespace android
#endif // AUDIO_SOURCE_H_
@@ -0,0 +1,104 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CAMERA_SOURCE_H_
#define CAMERA_SOURCE_H_
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MediaSource.h>
#include <utils/List.h>
#include <utils/RefBase.h>
#include <utils/threads.h>
#include <media/IMediaRecorderClient.h>
namespace android {
class ICamera;
class IMemory;
class Camera;
class CameraSource : public MediaSource, public MediaBufferObserver {
public:
static CameraSource *Create();
static CameraSource *CreateFromCamera(const sp<Camera> &camera);
virtual ~CameraSource();
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual sp<MetaData> getFormat();
virtual status_t read(
MediaBuffer **buffer, const ReadOptions *options = NULL);
virtual void signalBufferReturned(MediaBuffer* buffer);
virtual status_t getBufferInfo(sp<IMemory>& Frame, size_t *alignedSize);
//this function is not virtual.
void setListener(const sp<IMediaRecorderClient>& listener) {
mListener = listener;
}
private:
friend class CameraSourceListener;
sp<Camera> mCamera;
sp<MetaData> mMeta;
Mutex mLock;
Condition mFrameAvailableCondition;
Condition mFrameCompleteCondition;
List<sp<IMemory> > mFramesReceived;
List<sp<IMemory> > mFramesBeingEncoded;
List<int64_t> mFrameTimes;
int64_t mStartTimeUs;
int64_t mFirstFrameTimeUs;
int64_t mLastFrameTimestampUs;
int32_t mNumFramesReceived;
int32_t mNumFramesEncoded;
int32_t mNumFramesDropped;
int32_t mNumGlitches;
bool mFatalErrorBailout;
int64_t mGlitchDurationThresholdUs;
bool mCollectStats;
bool mStarted;
sp<IMediaRecorderClient> mListener;
CameraSource(const sp<Camera> &camera);
void dataCallbackTimestamp(
int64_t timestampUs, int32_t msgType, const sp<IMemory> &data);
void dataCallback(
int32_t msgType, const sp<IMemory> &data);
void errorCallback( );
void releaseQueuedFrames();
void releaseOneRecordingFrame(const sp<IMemory>& frame);
CameraSource(const CameraSource &);
CameraSource &operator=(const CameraSource &);
};
} // namespace android
#endif // CAMERA_SOURCE_H_
@@ -0,0 +1,122 @@
/*
* Copyright (C) 2009 The Android Open Source Project
* Copyright (c) 2010-2011, The Linux Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COLOR_CONVERTER_H_
#define COLOR_CONVERTER_H_
#include <sys/types.h>
#include <stdint.h>
#include <OMX_Video.h>
namespace android {
struct ColorConverter {
ColorConverter(OMX_COLOR_FORMATTYPE from, OMX_COLOR_FORMATTYPE to);
~ColorConverter();
bool isValid() const;
void convert(
size_t width, size_t height,
const void *srcBits, size_t srcSkip,
void *dstBits, size_t dstSkip);
private:
OMX_COLOR_FORMATTYPE mSrcFormat, mDstFormat;
uint8_t *mClip;
uint8_t *initClip();
void convertCbYCrY(
size_t width, size_t height,
const void *srcBits, size_t srcSkip,
void *dstBits, size_t dstSkip);
void convertYUV420Planar(
size_t width, size_t height,
const void *srcBits, size_t srcSkip,
void *dstBits, size_t dstSkip);
void convertQCOMYUV420SemiPlanar(
size_t width, size_t height,
const void *srcBits, size_t srcSkip,
void *dstBits, size_t dstSkip);
void convertYUV420SemiPlanar(
size_t width, size_t height,
const void *srcBits, size_t srcSkip,
void *dstBits, size_t dstSkip);
void convertYUV420SemiPlanar32Aligned(
size_t width, size_t height,
const void *srcBits, size_t srcSkip,
void *dstBits, size_t dstSkip,
size_t alignedWidth);
ColorConverter(const ColorConverter &);
ColorConverter &operator=(const ColorConverter &);
};
enum ColorConvertFormat {
RGB565 = 1,
YCbCr420Tile,
YCbCr420SP,
YCbCr420P,
YCrCb420P,
};
enum ColorConvertFlags {
COLOR_CONVERT_ALIGN_NONE = 1,
COLOR_CONVERT_CENTER_OUTPUT = 1<<1,
COLOR_CONVERT_ALIGN_16 = 1<<4,
COLOR_CONVERT_ALIGN_2048 = 1<<11,
COLOR_CONVERT_ALIGN_8192 = 1<<13,
};
struct ColorConvertParams {
size_t width;
size_t height;
size_t cropWidth;
size_t cropHeight;
size_t cropLeft;
size_t cropRight;
size_t cropTop;
size_t cropBottom;
ColorConvertFormat colorFormat;
const void * data;
int fd;
uint64_t flags;
};
typedef int (* ConvertFn)(ColorConvertParams src,
ColorConvertParams dst, uint8_t *adjustedClip);
int convert(ColorConvertParams src, ColorConvertParams dst,
uint8_t *adjustedClip);
} // namespace android
#endif // COLOR_CONVERTER_H_
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATA_SOURCE_H_
#define DATA_SOURCE_H_
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/KeyedVector.h>
#include <utils/List.h>
#include <utils/RefBase.h>
#include <utils/threads.h>
namespace android {
struct AMessage;
class String8;
class DataSource : public RefBase {
public:
enum Flags {
kWantsPrefetching = 1,
kStreamedFromLocalHost = 2,
kIsCachingDataSource = 4,
};
static sp<DataSource> CreateFromURI(
const char *uri,
const KeyedVector<String8, String8> *headers = NULL);
DataSource() {}
virtual status_t initCheck() const = 0;
virtual ssize_t readAt(off64_t offset, void *data, size_t size) = 0;
// Convenience methods:
bool getUInt16(off64_t offset, uint16_t *x);
// May return ERROR_UNSUPPORTED.
virtual status_t getSize(off64_t *size);
virtual uint32_t flags() {
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool sniff(String8 *mimeType, float *confidence, sp<AMessage> *meta);
// The sniffer can optionally fill in "meta" with an AMessage containing
// a dictionary of values that helps the corresponding extractor initialize
// its state without duplicating effort already exerted by the sniffer.
typedef bool (*SnifferFunc)(
const sp<DataSource> &source, String8 *mimeType,
float *confidence, sp<AMessage> *meta);
static void RegisterSniffer(SnifferFunc func);
static void RegisterDefaultSniffers();
protected:
virtual ~DataSource() {}
private:
static Mutex gSnifferMutex;
static List<SnifferFunc> gSniffers;
DataSource(const DataSource &);
DataSource &operator=(const DataSource &);
};
} // namespace android
#endif // DATA_SOURCE_H_
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2010, The Linux Foundation. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef EXTENDED_EXTRACTOR_FUNCS_
#define EXTENDED_EXTRACTOR_FUNCS_
#include <media/stagefright/DataSource.h>
namespace android {
class MediaExtractor;
//Prototype for factory function - extended media extractor must export a function with this prototype to
//instantiate MediaExtractor objects.
typedef MediaExtractor* (*MediaExtractorFactory)(const sp<DataSource> &source, const char* mime);
//Function name for extractor factory function. Extended extractor must export a function with this name.
static const char* MEDIA_CREATE_EXTRACTOR = "createExtractor";
//Prototype for function to return sniffers - extended media extractor must export a function with this prototype to
//set a pointer to an array of sniffers and set the count value.
typedef void (*SnifferArrayFunc)(const DataSource::SnifferFunc* snifferArray[], int *count);
//Function name for function to return sniffer array. Extended extractor must export a function with this name.
static const char* MEDIA_SNIFFER_ARRAY = "snifferArray";
} //namespace android
#endif //EXTENDED_EXTRACTOR_FUNCS_
@@ -0,0 +1,126 @@
/*
* Copyright (C) 2011 The Linux Foundation. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef EXTENDED_WRITER_H_
#define EXTENDED_WRITER_H_
#include <stdio.h>
#include <media/stagefright/MediaWriter.h>
#include <utils/threads.h>
namespace android {
struct MediaSource;
struct MetaData;
struct ExtendedWriter : public MediaWriter {
ExtendedWriter(const char *filename);
ExtendedWriter(int fd);
status_t initCheck() const;
virtual status_t addSource(const sp<MediaSource> &source);
virtual bool reachedEOS();
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual status_t pause();
protected:
virtual ~ExtendedWriter();
private:
FILE *mFile;
status_t mInitCheck;
sp<MediaSource> mSource;
bool mStarted;
volatile bool mPaused;
volatile bool mResumed;
volatile bool mDone;
volatile bool mReachedEOS;
pthread_t mThread;
int64_t mEstimatedSizeBytes;
int64_t mEstimatedDurationUs;
int32_t mFormat;
//QCP/EVRC header
struct QCPEVRCHeader
{
/* RIFF Section */
char riff[4];
unsigned int s_riff;
char qlcm[4];
/* Format chunk */
char fmt[4];
unsigned int s_fmt;
char mjr;
char mnr;
unsigned int data1;
/* UNIQUE ID of the codec */
unsigned short data2;
unsigned short data3;
char data4[8];
unsigned short ver;
/* Codec Info */
char name[80];
unsigned short abps;
/* average bits per sec of the codec */
unsigned short bytes_per_pkt;
unsigned short samp_per_block;
unsigned short samp_per_sec;
unsigned short bits_per_samp;
unsigned char vr_num_of_rates;
/* Rate Header fmt info */
unsigned char rvd1[3];
unsigned short vr_bytes_per_pkt[8];
unsigned int rvd2[5];
/* Vrat chunk */
unsigned char vrat[4];
unsigned int s_vrat;
unsigned int v_rate;
unsigned int size_in_pkts;
/* Data chunk */
unsigned char data[4];
unsigned int s_data;
} __attribute__ ((packed));
struct QCPEVRCHeader mHeader;
off_t mOffset; //note off_t
static void *ThreadWrapper(void *);
status_t threadFunc();
bool exceedsFileSizeLimit();
bool exceedsFileDurationLimit();
ExtendedWriter(const ExtendedWriter &);
ExtendedWriter &operator=(const ExtendedWriter &);
status_t writeQCPHeader( );
status_t writeEVRCHeader( );
};
} // namespace android
#endif // AMR_WRITER_H_
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FM_A2DP_WRITER_H_
#define FM_A2DP_WRITER_H_
#include <stdio.h>
#include <media/stagefright/MediaWriter.h>
#include <utils/threads.h>
#include <media/AudioRecord.h>
#include <utils/List.h>
#include <semaphore.h>
#include <media/mediarecorder.h>
namespace android {
struct MediaSource;
struct MetaData;
struct audioBufferstruct {
public:
audioBufferstruct (void *buff, size_t bufflen)
:audioBuffer(buff), bufferlen(bufflen){}
void *audioBuffer;
size_t bufferlen;
};
struct FMA2DPWriter : public MediaWriter {
FMA2DPWriter();
status_t initCheck() const;
virtual status_t addSource(const sp<MediaSource> &source);
virtual bool reachedEOS();
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual status_t pause();
virtual status_t allocateBufferPool();
protected:
virtual ~FMA2DPWriter();
private:
List<audioBufferstruct > mFreeQ,mDataQ;
Mutex mFreeQLock,mDataQLock;
sem_t mReaderThreadWakeupsem,mWriterThreadWakeupsem;
pthread_t mReaderThread,mWriterThread;
bool mStarted;
volatile bool mDone;
int32_t mAudioChannels;
int32_t mSampleRate;
int32_t mAudioFormat;
audio_source mAudioSource;
size_t mBufferSize;
static void *ReaderThreadWrapper(void *);
static void *WriterThreadWrapper(void *);
status_t readerthread();
status_t writerthread();
FMA2DPWriter(const FMA2DPWriter &);
FMA2DPWriter &operator=(const FMA2DPWriter &);
};
} // namespace android
#endif // FM_A2DP_WRITER_H_
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FILE_SOURCE_H_
#define FILE_SOURCE_H_
#include <stdio.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/MediaErrors.h>
#include <utils/threads.h>
namespace android {
class FileSource : public DataSource {
public:
FileSource(const char *filename);
FileSource(int fd, int64_t offset, int64_t length);
virtual status_t initCheck() const;
virtual ssize_t readAt(off64_t offset, void *data, size_t size);
virtual status_t getSize(off64_t *size);
protected:
virtual ~FileSource();
private:
FILE *mFile;
int64_t mOffset;
int64_t mLength;
Mutex mLock;
FileSource(const FileSource &);
FileSource &operator=(const FileSource &);
};
} // namespace android
#endif // FILE_SOURCE_H_
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HARDWARE_API_H_
#define HARDWARE_API_H_
#include <media/stagefright/OMXPluginBase.h>
#include <media/stagefright/VideoRenderer.h>
#include <surfaceflinger/ISurface.h>
#include <utils/RefBase.h>
#include <OMX_Component.h>
extern android::VideoRenderer *createRenderer(
const android::sp<android::ISurface> &surface,
const char *componentName,
OMX_COLOR_FORMATTYPE colorFormat,
size_t displayWidth, size_t displayHeight,
size_t decodedWidth, size_t decodedHeight,
size_t rotation = 0, size_t flags = 0);
extern android::VideoRenderer *createRendererWithRotation(
const android::sp<android::ISurface> &surface,
const char *componentName,
OMX_COLOR_FORMATTYPE colorFormat,
size_t displayWidth, size_t displayHeight,
size_t decodedWidth, size_t decodedHeight,
int32_t rotationDegrees);
extern android::OMXPluginBase *createOMXPlugin();
#endif // HARDWARE_API_H_
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JPEG_SOURCE_H_
#define JPEG_SOURCE_H_
#include <media/stagefright/MediaSource.h>
namespace android {
class DataSource;
class MediaBufferGroup;
struct JPEGSource : public MediaSource {
JPEGSource(const sp<DataSource> &source);
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual sp<MetaData> getFormat();
virtual status_t read(
MediaBuffer **buffer, const ReadOptions *options = NULL);
protected:
virtual ~JPEGSource();
private:
sp<DataSource> mSource;
MediaBufferGroup *mGroup;
bool mStarted;
off64_t mSize;
int32_t mWidth, mHeight;
off64_t mOffset;
status_t parseJPEG();
JPEGSource(const JPEGSource &);
JPEGSource &operator=(const JPEGSource &);
};
} // namespace android
#endif // JPEG_SOURCE_H_
+289
View File
@@ -0,0 +1,289 @@
/*
* Copyright (C) 2009 The Android Open Source Project
* Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LPA_PLAYER_H_
#define LPA_PLAYER_H_
#include "AudioPlayer.h"
#include <media/IAudioFlinger.h>
#include <utils/threads.h>
#include <utils/List.h>
#include <utils/Vector.h>
#include <pthread.h>
#include <binder/IServiceManager.h>
#include <linux/unistd.h>
#include <linux/msm_audio.h>
#include <include/TimedEventQueue.h>
// Pause timeout = 3sec
#define LPA_PAUSE_TIMEOUT_USEC 3000000
namespace android {
class LPAPlayer : public AudioPlayer {
public:
enum {
REACHED_EOS,
SEEK_COMPLETE
};
LPAPlayer(const sp<MediaPlayerBase::AudioSink> &audioSink, bool &initCheck,
AwesomePlayer *audioObserver = NULL);
virtual ~LPAPlayer();
// Caller retains ownership of "source".
virtual void setSource(const sp<MediaSource> &source);
// Return time in us.
virtual int64_t getRealTimeUs();
virtual status_t start(bool sourceAlreadyStarted = false);
virtual void pause(bool playPendingSamples = false);
virtual void resume();
// Returns the timestamp of the last buffer played (in us).
virtual int64_t getMediaTimeUs();
// Returns true iff a mapping is established, i.e. the LPAPlayer
// has played at least one frame of audio.
virtual bool getMediaTimeMapping(int64_t *realtime_us, int64_t *mediatime_us);
virtual status_t seekTo(int64_t time_us);
virtual bool isSeeking();
virtual bool reachedEOS(status_t *finalStatus);
void* handle;
static int objectsAlive;
private:
int afd;
int efd;
int sessionId;
uint32_t bytesToWrite;
bool isPaused;
bool mSeeked;
bool a2dpDisconnectPause;
bool a2dpThreadStarted;
volatile bool asyncReset;
bool eventThreadCreated;
//Structure to hold pmem buffer information
class BuffersAllocated {
public:
BuffersAllocated(void *buf1, void *buf2, int32_t nSize, int32_t fd) :
localBuf(buf1), pmemBuf(buf2), pmemBufsize(nSize), pmemFd(fd)
{}
void* localBuf;
void* pmemBuf;
int32_t pmemBufsize;
int32_t pmemFd;
uint32_t bytesToWrite;
};
List<BuffersAllocated> pmemBuffersRequestQueue;
List<BuffersAllocated> pmemBuffersResponseQueue;
List<BuffersAllocated> bufPool;
List<BuffersAllocated> effectsQueue;
void *pmemBufferAlloc(int32_t nSize, int32_t *pmem_fd);
void pmemBufferDeAlloc();
//Declare all the threads
pthread_t eventThread;
pthread_t decoderThread;
pthread_t A2DPThread;
pthread_t EffectsThread;
pthread_t A2DPNotificationThread;
//Kill Thread boolean
bool killDecoderThread;
bool killEventThread;
bool killA2DPThread;
bool killEffectsThread;
bool killA2DPNotificationThread;
//Thread alive boolean
bool decoderThreadAlive;
bool eventThreadAlive;
bool a2dpThreadAlive;
bool effectsThreadAlive;
bool a2dpNotificationThreadAlive;
//Declare the condition Variables and Mutex
pthread_mutex_t pmem_request_mutex;
pthread_mutex_t pmem_response_mutex;
pthread_mutex_t decoder_mutex;
pthread_mutex_t event_mutex;
pthread_mutex_t a2dp_mutex;
pthread_mutex_t effect_mutex;
pthread_mutex_t apply_effect_mutex;
pthread_mutex_t a2dp_notification_mutex;
pthread_cond_t event_cv;
pthread_cond_t decoder_cv;
pthread_cond_t a2dp_cv;
pthread_cond_t effect_cv;
pthread_cond_t event_thread_cv;
pthread_cond_t a2dp_notification_cv;
// make sure Decoder thread has exited
void requestAndWaitForDecoderThreadExit();
// make sure the event thread also exited
void requestAndWaitForEventThreadExit();
// make sure the A2dp thread also exited
void requestAndWaitForA2DPThreadExit();
// make sure the Effects thread also exited
void requestAndWaitForEffectsThreadExit();
// make sure the Effects thread also exited
void requestAndWaitForA2DPNotificationThreadExit();
static void *eventThreadWrapper(void *me);
void eventThreadEntry();
static void *decoderThreadWrapper(void *me);
void decoderThreadEntry();
static void *A2DPThreadWrapper(void *me);
void A2DPThreadEntry();
static void *EffectsThreadWrapper(void *me);
void EffectsThreadEntry();
static void *A2DPNotificationThreadWrapper(void *me);
void A2DPNotificationThreadEntry();
void createThreads();
volatile bool bIsA2DPEnabled, bIsAudioRouted, bEffectConfigChanged;
//Structure to recieve the BT notification from the flinger.
class AudioFlingerLPAdecodeClient: public IBinder::DeathRecipient, public BnAudioFlingerClient {
public:
AudioFlingerLPAdecodeClient(void *obj);
LPAPlayer *pBaseClass;
// DeathRecipient
virtual void binderDied(const wp<IBinder>& who);
// IAudioFlingerClient
// indicate a change in the configuration of an output or input: keeps the cached
// values for output/input parameters upto date in client process
virtual void ioConfigChanged(int event, int ioHandle, void *param2);
friend class LPAPlayer;
};
sp<IAudioFlinger> mAudioFlinger;
// helper function to obtain AudioFlinger service handle
void getAudioFlinger();
void handleA2DPSwitch();
sp<AudioFlingerLPAdecodeClient> AudioFlingerClient;
friend class AudioFlingerLPAdecodeClient;
Mutex AudioFlingerLock;
bool mSourceEmpty;
bool mAudioSinkOpen;
sp<MediaSource> mSource;
MediaBuffer *mInputBuffer;
int32_t numChannels;
int mSampleRate;
int64_t mLatencyUs;
size_t mFrameSize;
Mutex mLock;
Mutex mSeekLock;
Mutex a2dpSwitchLock;
Mutex resumeLock;
int64_t mNumFramesPlayed;
int64_t mPositionTimeMediaUs;
int64_t mPositionTimeRealUs;
bool mSeeking;
bool mInternalSeeking;
bool mReachedEOS;
status_t mFinalStatus;
int64_t mSeekTimeUs;
int64_t timePlayed;
int64_t timeStarted;
bool mStarted;
bool mIsFirstBuffer;
status_t mFirstBufferResult;
MediaBuffer *mFirstBuffer;
TimedEventQueue mQueue;
bool mQueueStarted;
sp<TimedEventQueue::Event> mPauseEvent;
bool mPauseEventPending;
bool mPlaybackSuspended;
bool mIsDriverStarted;
bool mIsAudioRouted;
sp<MediaPlayerBase::AudioSink> mAudioSink;
AwesomePlayer *mObserver;
size_t fillBuffer(void *data, size_t size);
int64_t getRealTimeUsLocked();
void reset();
void onPauseTimeOut();
LPAPlayer(const LPAPlayer &);
LPAPlayer &operator=(const LPAPlayer &);
};
struct TimedEvent : public TimedEventQueue::Event {
TimedEvent(LPAPlayer *player,
void (LPAPlayer::*method)())
: mPlayer(player),
mMethod(method) {
}
protected:
virtual ~TimedEvent() {}
virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
(mPlayer->*mMethod)();
}
private:
LPAPlayer *mPlayer;
void (LPAPlayer::*mMethod)();
TimedEvent(const TimedEvent &);
TimedEvent &operator=(const TimedEvent &);
};
} // namespace android
#endif // LPA_PLAYER_H_
@@ -0,0 +1,77 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MPEG2TS_WRITER_H_
#define MPEG2TS_WRITER_H_
#include <media/stagefright/foundation/ABase.h>
#include <media/stagefright/foundation/AHandlerReflector.h>
#include <media/stagefright/foundation/ALooper.h>
#include <media/stagefright/MediaWriter.h>
namespace android {
struct ABuffer;
struct MPEG2TSWriter : public MediaWriter {
MPEG2TSWriter(int fd);
MPEG2TSWriter(const char *filename);
virtual status_t addSource(const sp<MediaSource> &source);
virtual status_t start(MetaData *param = NULL);
virtual status_t stop();
virtual status_t pause();
virtual bool reachedEOS();
virtual status_t dump(int fd, const Vector<String16>& args);
void onMessageReceived(const sp<AMessage> &msg);
protected:
virtual ~MPEG2TSWriter();
private:
enum {
kWhatSourceNotify = 'noti'
};
struct SourceInfo;
FILE *mFile;
sp<ALooper> mLooper;
sp<AHandlerReflector<MPEG2TSWriter> > mReflector;
bool mStarted;
Vector<sp<SourceInfo> > mSources;
size_t mNumSourcesDone;
int64_t mNumTSPacketsWritten;
int64_t mNumTSPacketsBeforeMeta;
void init();
void writeTS();
void writeProgramAssociationTable();
void writeProgramMap();
void writeAccessUnit(int32_t sourceIndex, const sp<ABuffer> &buffer);
DISALLOW_EVIL_CONSTRUCTORS(MPEG2TSWriter);
};
} // namespace android
#endif // MPEG2TS_WRITER_H_
@@ -0,0 +1,164 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MPEG4_WRITER_H_
#define MPEG4_WRITER_H_
#include <stdio.h>
#include <media/stagefright/MediaWriter.h>
#include <utils/List.h>
#include <utils/threads.h>
namespace android {
class MediaBuffer;
class MediaSource;
class MetaData;
class MPEG4Writer : public MediaWriter {
public:
MPEG4Writer(const char *filename);
MPEG4Writer(int fd);
virtual status_t addSource(const sp<MediaSource> &source);
virtual status_t start(MetaData *param = NULL);
virtual status_t stop();
virtual status_t pause();
virtual bool reachedEOS();
virtual status_t dump(int fd, const Vector<String16>& args);
void beginBox(const char *fourcc);
void writeInt8(int8_t x);
void writeInt16(int16_t x);
void writeInt32(int32_t x);
void writeInt64(int64_t x);
void writeCString(const char *s);
void writeFourcc(const char *fourcc);
void write(const void *data, size_t size);
void endBox();
uint32_t interleaveDuration() const { return mInterleaveDurationUs; }
status_t setInterleaveDuration(uint32_t duration);
int32_t getTimeScale() const { return mTimeScale; }
protected:
virtual ~MPEG4Writer();
private:
class Track;
bool mUse4ByteNalLength;
bool mUse32BitOffset;
bool mIsFileSizeLimitExplicitlyRequested;
bool mPaused;
bool mStarted;
off64_t mOffset;
off64_t mMdatOffset;
uint8_t *mMoovBoxBuffer;
off64_t mMoovBoxBufferOffset;
bool mWriteMoovBoxToMemory;
off64_t mFreeBoxOffset;
bool mStreamableFile;
off64_t mEstimatedMoovBoxSize;
uint32_t mInterleaveDurationUs;
int32_t mTimeScale;
int64_t mStartTimestampUs;
int mFd;
Mutex mLock;
List<Track *> mTracks;
List<off64_t> mBoxes;
void setStartTimestampUs(int64_t timeUs);
int64_t getStartTimestampUs(); // Not const
status_t startTracks(MetaData *params);
size_t numTracks();
int64_t estimateMoovBoxSize(int32_t bitRate);
struct Chunk {
Track *mTrack; // Owner
int64_t mTimeStampUs; // Timestamp of the 1st sample
List<MediaBuffer *> mSamples; // Sample data
// Convenient constructor
Chunk(Track *track, int64_t timeUs, List<MediaBuffer *> samples)
: mTrack(track), mTimeStampUs(timeUs), mSamples(samples) {
}
};
struct ChunkInfo {
Track *mTrack; // Owner
List<Chunk> mChunks; // Remaining chunks to be written
};
bool mIsFirstChunk;
volatile bool mDone; // Writer thread is done?
pthread_t mThread; // Thread id for the writer
List<ChunkInfo> mChunkInfos; // Chunk infos
Condition mChunkReadyCondition; // Signal that chunks are available
// Writer thread handling
status_t startWriterThread();
void stopWriterThread();
static void *ThreadWrapper(void *me);
void threadFunc();
// Buffer a single chunk to be written out later.
void bufferChunk(const Chunk& chunk);
// Write all buffered chunks from all tracks
void writeChunks();
// Write a chunk if there is one
status_t writeOneChunk();
// Write the first chunk from the given ChunkInfo.
void writeFirstChunk(ChunkInfo* info);
// Adjust other track media clock (presumably wall clock)
// based on audio track media clock with the drift time.
int64_t mDriftTimeUs;
void setDriftTimeUs(int64_t driftTimeUs);
int64_t getDriftTimeUs();
// Return whether the nal length is 4 bytes or 2 bytes
// Only makes sense for H.264/AVC
bool useNalLengthFour();
void lock();
void unlock();
// Acquire lock before calling these methods
off64_t addSample_l(MediaBuffer *buffer);
off64_t addLengthPrefixedSample_l(MediaBuffer *buffer);
inline size_t write(const void *ptr, size_t size, size_t nmemb, int fd);
bool exceedsFileSizeLimit();
bool use32BitFileOffset() const;
bool exceedsFileDurationLimit();
bool isFileStreamable() const;
void trackProgressStatus(const Track* track, int64_t timeUs, status_t err = OK);
void writeCompositionMatrix(int32_t degrees);
MPEG4Writer(const MPEG4Writer &);
MPEG4Writer &operator=(const MPEG4Writer &);
};
} // namespace android
#endif // MPEG4_WRITER_H_
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*--------------------------------------------------------------------------
Copyright (c) 2010, The Linux Foundation. All rights reserved.
--------------------------------------------------------------------------*/
#ifndef MEDIA_BUFFER_H_
#define MEDIA_BUFFER_H_
#include <pthread.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
namespace android {
class MediaBuffer;
class MediaBufferObserver;
class MetaData;
class MediaBufferObserver {
public:
MediaBufferObserver() {}
virtual ~MediaBufferObserver() {}
virtual void signalBufferReturned(MediaBuffer *buffer) = 0;
private:
MediaBufferObserver(const MediaBufferObserver &);
MediaBufferObserver &operator=(const MediaBufferObserver &);
};
class MediaBuffer {
public:
// The underlying data remains the responsibility of the caller!
MediaBuffer(void *data, size_t size);
MediaBuffer(size_t size);
// Decrements the reference count and returns the buffer to its
// associated MediaBufferGroup if the reference count drops to 0.
void release();
// Increments the reference count.
void add_ref();
void setData(void *);
void *data() const;
size_t size() const;
size_t range_offset() const;
size_t range_length() const;
void set_range(size_t offset, size_t length);
sp<MetaData> meta_data();
// Clears meta data and resets the range to the full extent.
void reset();
void setObserver(MediaBufferObserver *group);
// Returns a clone of this MediaBuffer increasing its reference count.
// The clone references the same data but has its own range and
// MetaData.
MediaBuffer *clone();
int refcount() const;
protected:
virtual ~MediaBuffer();
private:
friend class MediaBufferGroup;
friend class OMXDecoder;
// For use by OMXDecoder, reference count must be 1, drop reference
// count to 0 without signalling the observer.
void claim();
MediaBufferObserver *mObserver;
MediaBuffer *mNextBuffer;
int mRefCount;
void *mData;
size_t mSize, mRangeOffset, mRangeLength;
bool mOwnsData;
sp<MetaData> mMetaData;
MediaBuffer *mOriginal;
void setNextBuffer(MediaBuffer *buffer);
MediaBuffer *nextBuffer();
MediaBuffer(const MediaBuffer &);
MediaBuffer &operator=(const MediaBuffer &);
};
} // namespace android
#endif // MEDIA_BUFFER_H_
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIA_BUFFER_GROUP_H_
#define MEDIA_BUFFER_GROUP_H_
#include <media/stagefright/MediaBuffer.h>
#include <utils/Errors.h>
#include <utils/threads.h>
namespace android {
class MediaBuffer;
class MetaData;
class MediaBufferGroup : public MediaBufferObserver {
public:
MediaBufferGroup();
~MediaBufferGroup();
void add_buffer(MediaBuffer *buffer);
// Blocks until a buffer is available and returns it to the caller,
// the returned buffer will have a reference count of 1.
status_t acquire_buffer(MediaBuffer **buffer);
protected:
virtual void signalBufferReturned(MediaBuffer *buffer);
private:
friend class MediaBuffer;
Mutex mLock;
Condition mCondition;
MediaBuffer *mFirstBuffer, *mLastBuffer;
MediaBufferGroup(const MediaBufferGroup &);
MediaBufferGroup &operator=(const MediaBufferGroup &);
};
} // namespace android
#endif // MEDIA_BUFFER_GROUP_H_
@@ -0,0 +1,20 @@
#ifndef MEDIA_DEBUG_H_
#define MEDIA_DEBUG_H_
#include <cutils/log.h>
#define LITERAL_TO_STRING_INTERNAL(x) #x
#define LITERAL_TO_STRING(x) LITERAL_TO_STRING_INTERNAL(x)
#define CHECK_EQ(x,y) \
LOG_ALWAYS_FATAL_IF( \
(x) != (y), \
__FILE__ ":" LITERAL_TO_STRING(__LINE__) " " #x " != " #y)
#define CHECK(x) \
LOG_ALWAYS_FATAL_IF( \
!(x), \
__FILE__ ":" LITERAL_TO_STRING(__LINE__) " " #x)
#endif // MEDIA_DEBUG_H_
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*/
#ifndef MEDIA_DEFS_H_
#define MEDIA_DEFS_H_
namespace android {
extern const char *MEDIA_MIMETYPE_IMAGE_JPEG;
extern const char *MEDIA_MIMETYPE_VIDEO_VPX;
extern const char *MEDIA_MIMETYPE_VIDEO_AVC;
extern const char *MEDIA_MIMETYPE_VIDEO_MPEG4;
extern const char *MEDIA_MIMETYPE_VIDEO_H263;
extern const char *MEDIA_MIMETYPE_VIDEO_RAW;
extern const char *MEDIA_MIMETYPE_VIDEO_WMV;
extern const char *MEDIA_MIMETYPE_AUDIO_AMR_NB;
extern const char *MEDIA_MIMETYPE_AUDIO_AMR_WB;
extern const char *MEDIA_MIMETYPE_AUDIO_MPEG;
extern const char *MEDIA_MIMETYPE_AUDIO_AAC;
extern const char *MEDIA_MIMETYPE_AUDIO_QCELP;
extern const char *MEDIA_MIMETYPE_AUDIO_VORBIS;
extern const char *MEDIA_MIMETYPE_AUDIO_G711_ALAW;
extern const char *MEDIA_MIMETYPE_AUDIO_G711_MLAW;
extern const char *MEDIA_MIMETYPE_AUDIO_RAW;
extern const char *MEDIA_MIMETYPE_AUDIO_WMA;
extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG4;
extern const char *MEDIA_MIMETYPE_CONTAINER_WAV;
extern const char *MEDIA_MIMETYPE_CONTAINER_OGG;
extern const char *MEDIA_MIMETYPE_CONTAINER_MATROSKA;
extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG2TS;
extern const char *MEDIA_MIMETYPE_CONTAINER_AVI;
extern const char *MEDIA_MIMETYPE_CONTAINER_QCP;
extern const char *MEDIA_MIMETYPE_CONTAINER_ASF;
extern const char *MEDIA_MIMETYPE_CONTAINER_AAC;
extern const char *MEDIA_MIMETYPE_VIDEO_DIVX; // DIVX 5 & 6
extern const char *MEDIA_MIMETYPE_VIDEO_DIVX311; // DIVX 311
extern const char *MEDIA_MIMETYPE_VIDEO_DIVX4; // DIVX 4
extern const char *MEDIA_MIMETYPE_AUDIO_AC3;
extern const char *MEDIA_MIMETYPE_VIDEO_SPARK;
extern const char *MEDIA_MIMETYPE_VIDEO_VP6;
extern const char *MEDIA_MIMETYPE_AUDIO_EVRC;
extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG2;
extern const char *MEDIA_MIMETYPE_VIDEO_MPEG2;
} // namespace android
#endif // MEDIA_DEFS_H_
@@ -0,0 +1,50 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIA_ERRORS_H_
#define MEDIA_ERRORS_H_
#include <utils/Errors.h>
namespace android {
enum {
MEDIA_ERROR_BASE = -1000,
ERROR_ALREADY_CONNECTED = MEDIA_ERROR_BASE,
ERROR_NOT_CONNECTED = MEDIA_ERROR_BASE - 1,
ERROR_UNKNOWN_HOST = MEDIA_ERROR_BASE - 2,
ERROR_CANNOT_CONNECT = MEDIA_ERROR_BASE - 3,
ERROR_IO = MEDIA_ERROR_BASE - 4,
ERROR_CONNECTION_LOST = MEDIA_ERROR_BASE - 5,
ERROR_MALFORMED = MEDIA_ERROR_BASE - 7,
ERROR_OUT_OF_RANGE = MEDIA_ERROR_BASE - 8,
ERROR_BUFFER_TOO_SMALL = MEDIA_ERROR_BASE - 9,
ERROR_UNSUPPORTED = MEDIA_ERROR_BASE - 10,
ERROR_END_OF_STREAM = MEDIA_ERROR_BASE - 11,
// Not technically an error.
INFO_FORMAT_CHANGED = MEDIA_ERROR_BASE - 12,
INFO_DISCONTINUITY = MEDIA_ERROR_BASE - 13,
//Custom Error for corrupt NAL
ERROR_CORRUPT_NAL = MEDIA_ERROR_BASE - 99,
};
} // namespace android
#endif // MEDIA_ERRORS_H_
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIA_EXTRACTOR_H_
#define MEDIA_EXTRACTOR_H_
#include <utils/RefBase.h>
namespace android {
class DataSource;
class MediaSource;
class MetaData;
class MediaExtractor : public RefBase {
public:
static sp<MediaExtractor> Create(
const sp<DataSource> &source, const char *mime = NULL);
virtual size_t countTracks() = 0;
virtual sp<MediaSource> getTrack(size_t index) = 0;
enum GetTrackMetaDataFlags {
kIncludeExtensiveMetaData = 1
};
virtual sp<MetaData> getTrackMetaData(
size_t index, uint32_t flags = 0) = 0;
// Return container specific meta-data. The default implementation
// returns an empty metadata object.
virtual sp<MetaData> getMetaData();
enum Flags {
CAN_SEEK_BACKWARD = 1, // the "seek 10secs back button"
CAN_SEEK_FORWARD = 2, // the "seek 10secs forward button"
CAN_PAUSE = 4,
CAN_SEEK = 8, // the "seek bar"
};
// If subclasses do _not_ override this, the default is
// CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK | CAN_PAUSE
virtual uint32_t flags() const;
protected:
MediaExtractor() {}
virtual ~MediaExtractor() {}
private:
MediaExtractor(const MediaExtractor &);
MediaExtractor &operator=(const MediaExtractor &);
};
} // namespace android
#endif // MEDIA_EXTRACTOR_H_
@@ -0,0 +1,136 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIA_SOURCE_H_
#define MEDIA_SOURCE_H_
#include <sys/types.h>
#include <media/stagefright/MediaErrors.h>
#include <utils/RefBase.h>
#include <binder/IMemory.h>
namespace android {
class MediaBuffer;
class MetaData;
struct MediaSource : public RefBase {
MediaSource();
// To be called before any other methods on this object, except
// getFormat().
virtual status_t start(MetaData *params = NULL) = 0;
// Any blocking read call returns immediately with a result of NO_INIT.
// It is an error to call any methods other than start after this call
// returns. Any buffers the object may be holding onto at the time of
// the stop() call are released.
// Also, it is imperative that any buffers output by this object and
// held onto by callers be released before a call to stop() !!!
virtual status_t stop() = 0;
// Returns the format of the data output by this media source.
virtual sp<MetaData> getFormat() = 0;
struct ReadOptions;
// Returns a new buffer of data. Call blocks until a
// buffer is available, an error is encountered of the end of the stream
// is reached.
// End of stream is signalled by a result of ERROR_END_OF_STREAM.
// A result of INFO_FORMAT_CHANGED indicates that the format of this
// MediaSource has changed mid-stream, the client can continue reading
// but should be prepared for buffers of the new configuration.
virtual status_t read(
MediaBuffer **buffer, const ReadOptions *options = NULL) = 0;
virtual status_t getBufferInfo(sp<IMemory>& Frame, size_t *alignedSize);
// Options that modify read() behaviour. The default is to
// a) not request a seek
// b) not be late, i.e. lateness_us = 0
struct ReadOptions {
enum SeekMode {
SEEK_PREVIOUS_SYNC,
SEEK_NEXT_SYNC,
SEEK_CLOSEST_SYNC,
SEEK_CLOSEST,
};
ReadOptions();
// Reset everything back to defaults.
void reset();
void setSeekTo(int64_t time_us, SeekMode mode = SEEK_CLOSEST_SYNC);
void clearSeekTo();
bool getSeekTo(int64_t *time_us, SeekMode *mode) const;
// Option allows encoder to skip some frames until the specified
// time stamp.
// To prevent from being abused, when the skipFrame timestamp is
// found to be more than 1 second later than the current timestamp,
// an error will be returned from read().
void clearSkipFrame();
bool getSkipFrame(int64_t *timeUs) const;
void setSkipFrame(int64_t timeUs);
void setLateBy(int64_t lateness_us);
int64_t getLateBy() const;
private:
enum Options {
// Bit map
kSeekTo_Option = 1,
kSkipFrame_Option = 2,
};
uint32_t mOptions;
int64_t mSeekTimeUs;
SeekMode mSeekMode;
int64_t mLatenessUs;
int64_t mSkipFrameUntilTimeUs;
};
// Causes this source to suspend pulling data from its upstream source
// until a subsequent read-with-seek. Currently only supported by
// OMXCodec.
virtual status_t pause() {
return ERROR_UNSUPPORTED;
}
protected:
virtual ~MediaSource();
private:
MediaSource(const MediaSource &);
MediaSource &operator=(const MediaSource &);
public:
virtual status_t isPaused(){return mIsPaused;}
protected:
bool mIsPaused;
};
} // namespace android
#endif // MEDIA_SOURCE_H_
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MEDIA_WRITER_H_
#define MEDIA_WRITER_H_
#include <utils/RefBase.h>
#include <media/IMediaRecorderClient.h>
namespace android {
struct MediaSource;
struct MetaData;
struct MediaWriter : public RefBase {
MediaWriter()
: mMaxFileSizeLimitBytes(0),
mMaxFileDurationLimitUs(0) {
}
virtual status_t addSource(const sp<MediaSource> &source) = 0;
virtual bool reachedEOS() = 0;
virtual status_t start(MetaData *params = NULL) = 0;
virtual status_t stop() = 0;
virtual status_t pause() = 0;
virtual void setMaxFileSize(int64_t bytes) { mMaxFileSizeLimitBytes = bytes; }
virtual void setMaxFileDuration(int64_t durationUs) { mMaxFileDurationLimitUs = durationUs; }
virtual void setListener(const sp<IMediaRecorderClient>& listener) {
mListener = listener;
}
virtual status_t dump(int fd, const Vector<String16>& args) {
return OK;
}
protected:
virtual ~MediaWriter() {}
int64_t mMaxFileSizeLimitBytes;
int64_t mMaxFileDurationLimitUs;
sp<IMediaRecorderClient> mListener;
void notify(int msg, int ext1, int ext2) {
if (mListener != NULL) {
mListener->notify(msg, ext1, ext2);
}
}
private:
MediaWriter(const MediaWriter &);
MediaWriter &operator=(const MediaWriter &);
};
} // namespace android
#endif // MEDIA_WRITER_H_

Some files were not shown because too many files have changed in this diff Show More