openpilot v0.6 release

This commit is contained in:
Vehicle Researcher
2019-06-28 21:11:30 +00:00
parent bbc7de2cbd
commit 7b469bc8be
974 changed files with 90130 additions and 100834 deletions
@@ -0,0 +1,215 @@
/*
* 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.
*/
/**
* @addtogroup Asset
* @{
*/
/**
* @file asset_manager.h
*/
#ifndef ANDROID_ASSET_MANAGER_H
#define ANDROID_ASSET_MANAGER_H
#ifdef __cplusplus
extern "C" {
#endif
struct AAssetManager;
/**
* {@link AAssetManager} provides access to an application's raw assets by
* creating {@link AAsset} objects.
*
* AAssetManager is a wrapper to the low-level native implementation
* of the java {@link AAssetManager}, a pointer can be obtained using
* AAssetManager_fromJava().
*
* The asset hierarchy may be examined like a filesystem, using
* {@link AAssetDir} objects to peruse a single directory.
*
* A native {@link AAssetManager} pointer may be shared across multiple threads.
*/
typedef struct AAssetManager AAssetManager;
struct AAssetDir;
/**
* {@link AAssetDir} provides access to a chunk of the asset hierarchy as if
* it were a single directory. The contents are populated by the
* {@link AAssetManager}.
*
* The list of files will be sorted in ascending order by ASCII value.
*/
typedef struct AAssetDir AAssetDir;
struct AAsset;
/**
* {@link AAsset} provides access to a read-only asset.
*
* {@link AAsset} objects are NOT thread-safe, and should not be shared across
* threads.
*/
typedef struct AAsset AAsset;
/** Available access modes for opening assets with {@link AAssetManager_open} */
enum {
/** No specific information about how data will be accessed. **/
AASSET_MODE_UNKNOWN = 0,
/** Read chunks, and seek forward and backward. */
AASSET_MODE_RANDOM = 1,
/** Read sequentially, with an occasional forward seek. */
AASSET_MODE_STREAMING = 2,
/** Caller plans to ask for a read-only buffer with all data. */
AASSET_MODE_BUFFER = 3
};
/**
* Open the named directory within the asset hierarchy. The directory can then
* be inspected with the AAssetDir functions. To open the top-level directory,
* pass in "" as the dirName.
*
* The object returned here should be freed by calling AAssetDir_close().
*/
AAssetDir* AAssetManager_openDir(AAssetManager* mgr, const char* dirName);
/**
* Open an asset.
*
* The object returned here should be freed by calling AAsset_close().
*/
AAsset* AAssetManager_open(AAssetManager* mgr, const char* filename, int mode);
/**
* Iterate over the files in an asset directory. A NULL string is returned
* when all the file names have been returned.
*
* The returned file name is suitable for passing to AAssetManager_open().
*
* The string returned here is owned by the AssetDir implementation and is not
* guaranteed to remain valid if any other calls are made on this AAssetDir
* instance.
*/
const char* AAssetDir_getNextFileName(AAssetDir* assetDir);
/**
* Reset the iteration state of AAssetDir_getNextFileName() to the beginning.
*/
void AAssetDir_rewind(AAssetDir* assetDir);
/**
* Close an opened AAssetDir, freeing any related resources.
*/
void AAssetDir_close(AAssetDir* assetDir);
/**
* Attempt to read 'count' bytes of data from the current offset.
*
* Returns the number of bytes read, zero on EOF, or < 0 on error.
*/
int AAsset_read(AAsset* asset, void* buf, size_t count);
/**
* Seek to the specified offset within the asset data. 'whence' uses the
* same constants as lseek()/fseek().
*
* Returns the new position on success, or (off_t) -1 on error.
*/
off_t AAsset_seek(AAsset* asset, off_t offset, int whence);
/**
* Seek to the specified offset within the asset data. 'whence' uses the
* same constants as lseek()/fseek().
*
* Uses 64-bit data type for large files as opposed to the 32-bit type used
* by AAsset_seek.
*
* Returns the new position on success, or (off64_t) -1 on error.
*/
off64_t AAsset_seek64(AAsset* asset, off64_t offset, int whence);
/**
* Close the asset, freeing all associated resources.
*/
void AAsset_close(AAsset* asset);
/**
* Get a pointer to a buffer holding the entire contents of the assset.
*
* Returns NULL on failure.
*/
const void* AAsset_getBuffer(AAsset* asset);
/**
* Report the total size of the asset data.
*/
off_t AAsset_getLength(AAsset* asset);
/**
* Report the total size of the asset data. Reports the size using a 64-bit
* number insted of 32-bit as AAsset_getLength.
*/
off64_t AAsset_getLength64(AAsset* asset);
/**
* Report the total amount of asset data that can be read from the current position.
*/
off_t AAsset_getRemainingLength(AAsset* asset);
/**
* Report the total amount of asset data that can be read from the current position.
*
* Uses a 64-bit number instead of a 32-bit number as AAsset_getRemainingLength does.
*/
off64_t AAsset_getRemainingLength64(AAsset* asset);
/**
* Open a new file descriptor that can be used to read the asset data. If the
* start or length cannot be represented by a 32-bit number, it will be
* truncated. If the file is large, use AAsset_openFileDescriptor64 instead.
*
* Returns < 0 if direct fd access is not possible (for example, if the asset is
* compressed).
*/
int AAsset_openFileDescriptor(AAsset* asset, off_t* outStart, off_t* outLength);
/**
* Open a new file descriptor that can be used to read the asset data.
*
* Uses a 64-bit number for the offset and length instead of 32-bit instead of
* as AAsset_openFileDescriptor does.
*
* Returns < 0 if direct fd access is not possible (for example, if the asset is
* compressed).
*/
int AAsset_openFileDescriptor64(AAsset* asset, off64_t* outStart, off64_t* outLength);
/**
* Returns whether this asset's internal buffer is allocated in ordinary RAM (i.e. not
* mmapped).
*/
int AAsset_isAllocated(AAsset* asset);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_ASSET_MANAGER_H
/** @} */
@@ -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.
*/
/**
* @addtogroup Asset
* @{
*/
/**
* @file asset_manager_jni.h
*/
#ifndef ANDROID_ASSET_MANAGER_JNI_H
#define ANDROID_ASSET_MANAGER_JNI_H
#include <android/asset_manager.h>
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Given a Dalvik AssetManager object, obtain the corresponding native AAssetManager
* object. Note that the caller is responsible for obtaining and holding a VM reference
* to the jobject to prevent its being garbage collected while the native object is
* in use.
*/
AAssetManager* AAssetManager_fromJava(JNIEnv* env, jobject assetManager);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_ASSET_MANAGER_JNI_H
/** @} */
@@ -0,0 +1,112 @@
/*
* 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.
*/
/**
* @addtogroup Bitmap
* @{
*/
/**
* @file bitmap.h
*/
#ifndef ANDROID_BITMAP_H
#define ANDROID_BITMAP_H
#include <stdint.h>
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
/** AndroidBitmap functions result code. */
enum {
/** Operation was successful. */
ANDROID_BITMAP_RESULT_SUCCESS = 0,
/** Bad parameter. */
ANDROID_BITMAP_RESULT_BAD_PARAMETER = -1,
/** JNI exception occured. */
ANDROID_BITMAP_RESULT_JNI_EXCEPTION = -2,
/** Allocation failed. */
ANDROID_BITMAP_RESULT_ALLOCATION_FAILED = -3,
};
/** Backward compatibility: this macro used to be misspelled. */
#define ANDROID_BITMAP_RESUT_SUCCESS ANDROID_BITMAP_RESULT_SUCCESS
/** Bitmap pixel format. */
enum AndroidBitmapFormat {
/** No format. */
ANDROID_BITMAP_FORMAT_NONE = 0,
/** Red: 8 bits, Green: 8 bits, Blue: 8 bits, Alpha: 8 bits. **/
ANDROID_BITMAP_FORMAT_RGBA_8888 = 1,
/** Red: 5 bits, Green: 6 bits, Blue: 5 bits. **/
ANDROID_BITMAP_FORMAT_RGB_565 = 4,
/** Red: 4 bits, Green: 4 bits, Blue: 4 bits, Alpha: 4 bits. **/
ANDROID_BITMAP_FORMAT_RGBA_4444 = 7,
/** Deprecated. */
ANDROID_BITMAP_FORMAT_A_8 = 8,
};
/** Bitmap info, see AndroidBitmap_getInfo(). */
typedef struct {
/** The bitmap width in pixels. */
uint32_t width;
/** The bitmap height in pixels. */
uint32_t height;
/** The number of byte per row. */
uint32_t stride;
/** The bitmap pixel format. See {@link AndroidBitmapFormat} */
int32_t format;
/** Unused. */
uint32_t flags; // 0 for now
} AndroidBitmapInfo;
/**
* Given a java bitmap object, fill out the AndroidBitmapInfo struct for it.
* If the call fails, the info parameter will be ignored.
*/
int AndroidBitmap_getInfo(JNIEnv* env, jobject jbitmap,
AndroidBitmapInfo* info);
/**
* Given a java bitmap object, attempt to lock the pixel address.
* Locking will ensure that the memory for the pixels will not move
* until the unlockPixels call, and ensure that, if the pixels had been
* previously purged, they will have been restored.
*
* If this call succeeds, it must be balanced by a call to
* AndroidBitmap_unlockPixels, after which time the address of the pixels should
* no longer be used.
*
* If this succeeds, *addrPtr will be set to the pixel address. If the call
* fails, addrPtr will be ignored.
*/
int AndroidBitmap_lockPixels(JNIEnv* env, jobject jbitmap, void** addrPtr);
/**
* Call this to balance a successful call to AndroidBitmap_lockPixels.
*/
int AndroidBitmap_unlockPixels(JNIEnv* env, jobject jbitmap);
#ifdef __cplusplus
}
#endif
#endif
/** @} */
@@ -0,0 +1,708 @@
/*
* 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.
*/
/**
* @addtogroup Configuration
* @{
*/
/**
* @file configuration.h
*/
#ifndef ANDROID_CONFIGURATION_H
#define ANDROID_CONFIGURATION_H
#include <android/asset_manager.h>
#ifdef __cplusplus
extern "C" {
#endif
struct AConfiguration;
/**
* {@link AConfiguration} is an opaque type used to get and set
* various subsystem configurations.
*
* A {@link AConfiguration} pointer can be obtained using:
* - AConfiguration_new()
* - AConfiguration_fromAssetManager()
*/
typedef struct AConfiguration AConfiguration;
/**
* Define flags and constants for various subsystem configurations.
*/
enum {
/** Orientation: not specified. */
ACONFIGURATION_ORIENTATION_ANY = 0x0000,
/**
* Orientation: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#OrientationQualifier">port</a>
* resource qualifier.
*/
ACONFIGURATION_ORIENTATION_PORT = 0x0001,
/**
* Orientation: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#OrientationQualifier">land</a>
* resource qualifier.
*/
ACONFIGURATION_ORIENTATION_LAND = 0x0002,
/** @deprecated Not currently supported or used. */
ACONFIGURATION_ORIENTATION_SQUARE = 0x0003,
/** Touchscreen: not specified. */
ACONFIGURATION_TOUCHSCREEN_ANY = 0x0000,
/**
* Touchscreen: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#TouchscreenQualifier">notouch</a>
* resource qualifier.
*/
ACONFIGURATION_TOUCHSCREEN_NOTOUCH = 0x0001,
/** @deprecated Not currently supported or used. */
ACONFIGURATION_TOUCHSCREEN_STYLUS = 0x0002,
/**
* Touchscreen: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#TouchscreenQualifier">finger</a>
* resource qualifier.
*/
ACONFIGURATION_TOUCHSCREEN_FINGER = 0x0003,
/** Density: default density. */
ACONFIGURATION_DENSITY_DEFAULT = 0,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">ldpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_LOW = 120,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">mdpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_MEDIUM = 160,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">tvdpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_TV = 213,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">hdpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_HIGH = 240,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">xhdpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_XHIGH = 320,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">xxhdpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_XXHIGH = 480,
/**
* Density: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">xxxhdpi</a>
* resource qualifier.
*/
ACONFIGURATION_DENSITY_XXXHIGH = 640,
/** Density: any density. */
ACONFIGURATION_DENSITY_ANY = 0xfffe,
/** Density: no density specified. */
ACONFIGURATION_DENSITY_NONE = 0xffff,
/** Keyboard: not specified. */
ACONFIGURATION_KEYBOARD_ANY = 0x0000,
/**
* Keyboard: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ImeQualifier">nokeys</a>
* resource qualifier.
*/
ACONFIGURATION_KEYBOARD_NOKEYS = 0x0001,
/**
* Keyboard: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ImeQualifier">qwerty</a>
* resource qualifier.
*/
ACONFIGURATION_KEYBOARD_QWERTY = 0x0002,
/**
* Keyboard: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ImeQualifier">12key</a>
* resource qualifier.
*/
ACONFIGURATION_KEYBOARD_12KEY = 0x0003,
/** Navigation: not specified. */
ACONFIGURATION_NAVIGATION_ANY = 0x0000,
/**
* Navigation: value corresponding to the
* <a href="@@dacRoot/guide/topics/resources/providing-resources.html#NavigationQualifier">nonav</a>
* resource qualifier.
*/
ACONFIGURATION_NAVIGATION_NONAV = 0x0001,
/**
* Navigation: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NavigationQualifier">dpad</a>
* resource qualifier.
*/
ACONFIGURATION_NAVIGATION_DPAD = 0x0002,
/**
* Navigation: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NavigationQualifier">trackball</a>
* resource qualifier.
*/
ACONFIGURATION_NAVIGATION_TRACKBALL = 0x0003,
/**
* Navigation: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NavigationQualifier">wheel</a>
* resource qualifier.
*/
ACONFIGURATION_NAVIGATION_WHEEL = 0x0004,
/** Keyboard availability: not specified. */
ACONFIGURATION_KEYSHIDDEN_ANY = 0x0000,
/**
* Keyboard availability: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#KeyboardAvailQualifier">keysexposed</a>
* resource qualifier.
*/
ACONFIGURATION_KEYSHIDDEN_NO = 0x0001,
/**
* Keyboard availability: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#KeyboardAvailQualifier">keyshidden</a>
* resource qualifier.
*/
ACONFIGURATION_KEYSHIDDEN_YES = 0x0002,
/**
* Keyboard availability: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#KeyboardAvailQualifier">keyssoft</a>
* resource qualifier.
*/
ACONFIGURATION_KEYSHIDDEN_SOFT = 0x0003,
/** Navigation availability: not specified. */
ACONFIGURATION_NAVHIDDEN_ANY = 0x0000,
/**
* Navigation availability: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NavAvailQualifier">navexposed</a>
* resource qualifier.
*/
ACONFIGURATION_NAVHIDDEN_NO = 0x0001,
/**
* Navigation availability: value corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NavAvailQualifier">navhidden</a>
* resource qualifier.
*/
ACONFIGURATION_NAVHIDDEN_YES = 0x0002,
/** Screen size: not specified. */
ACONFIGURATION_SCREENSIZE_ANY = 0x00,
/**
* Screen size: value indicating the screen is at least
* approximately 320x426 dp units, corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenSizeQualifier">small</a>
* resource qualifier.
*/
ACONFIGURATION_SCREENSIZE_SMALL = 0x01,
/**
* Screen size: value indicating the screen is at least
* approximately 320x470 dp units, corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenSizeQualifier">normal</a>
* resource qualifier.
*/
ACONFIGURATION_SCREENSIZE_NORMAL = 0x02,
/**
* Screen size: value indicating the screen is at least
* approximately 480x640 dp units, corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenSizeQualifier">large</a>
* resource qualifier.
*/
ACONFIGURATION_SCREENSIZE_LARGE = 0x03,
/**
* Screen size: value indicating the screen is at least
* approximately 720x960 dp units, corresponding to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenSizeQualifier">xlarge</a>
* resource qualifier.
*/
ACONFIGURATION_SCREENSIZE_XLARGE = 0x04,
/** Screen layout: not specified. */
ACONFIGURATION_SCREENLONG_ANY = 0x00,
/**
* Screen layout: value that corresponds to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenAspectQualifier">notlong</a>
* resource qualifier.
*/
ACONFIGURATION_SCREENLONG_NO = 0x1,
/**
* Screen layout: value that corresponds to the
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenAspectQualifier">long</a>
* resource qualifier.
*/
ACONFIGURATION_SCREENLONG_YES = 0x2,
ACONFIGURATION_SCREENROUND_ANY = 0x00,
ACONFIGURATION_SCREENROUND_NO = 0x1,
ACONFIGURATION_SCREENROUND_YES = 0x2,
/** UI mode: not specified. */
ACONFIGURATION_UI_MODE_TYPE_ANY = 0x00,
/**
* UI mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">no
* UI mode type</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_TYPE_NORMAL = 0x01,
/**
* UI mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">desk</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_TYPE_DESK = 0x02,
/**
* UI mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">car</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_TYPE_CAR = 0x03,
/**
* UI mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">television</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_TYPE_TELEVISION = 0x04,
/**
* UI mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">appliance</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_TYPE_APPLIANCE = 0x05,
/**
* UI mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">watch</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_TYPE_WATCH = 0x06,
/** UI night mode: not specified.*/
ACONFIGURATION_UI_MODE_NIGHT_ANY = 0x00,
/**
* UI night mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NightQualifier">notnight</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_NIGHT_NO = 0x1,
/**
* UI night mode: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NightQualifier">night</a> resource qualifier specified.
*/
ACONFIGURATION_UI_MODE_NIGHT_YES = 0x2,
/** Screen width DPI: not specified. */
ACONFIGURATION_SCREEN_WIDTH_DP_ANY = 0x0000,
/** Screen height DPI: not specified. */
ACONFIGURATION_SCREEN_HEIGHT_DP_ANY = 0x0000,
/** Smallest screen width DPI: not specified.*/
ACONFIGURATION_SMALLEST_SCREEN_WIDTH_DP_ANY = 0x0000,
/** Layout direction: not specified. */
ACONFIGURATION_LAYOUTDIR_ANY = 0x00,
/**
* Layout direction: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#LayoutDirectionQualifier">ldltr</a> resource qualifier specified.
*/
ACONFIGURATION_LAYOUTDIR_LTR = 0x01,
/**
* Layout direction: value that corresponds to
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#LayoutDirectionQualifier">ldrtl</a> resource qualifier specified.
*/
ACONFIGURATION_LAYOUTDIR_RTL = 0x02,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#MccQualifier">mcc</a>
* configuration.
*/
ACONFIGURATION_MCC = 0x0001,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#MccQualifier">mnc</a>
* configuration.
*/
ACONFIGURATION_MNC = 0x0002,
/**
* Bit mask for
* <a href="{@docRoot}guide/topics/resources/providing-resources.html#LocaleQualifier">locale</a>
* configuration.
*/
ACONFIGURATION_LOCALE = 0x0004,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#TouchscreenQualifier">touchscreen</a>
* configuration.
*/
ACONFIGURATION_TOUCHSCREEN = 0x0008,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ImeQualifier">keyboard</a>
* configuration.
*/
ACONFIGURATION_KEYBOARD = 0x0010,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#KeyboardAvailQualifier">keyboardHidden</a>
* configuration.
*/
ACONFIGURATION_KEYBOARD_HIDDEN = 0x0020,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#NavigationQualifier">navigation</a>
* configuration.
*/
ACONFIGURATION_NAVIGATION = 0x0040,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#OrientationQualifier">orientation</a>
* configuration.
*/
ACONFIGURATION_ORIENTATION = 0x0080,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#DensityQualifier">density</a>
* configuration.
*/
ACONFIGURATION_DENSITY = 0x0100,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#ScreenSizeQualifier">screen size</a>
* configuration.
*/
ACONFIGURATION_SCREEN_SIZE = 0x0200,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#VersionQualifier">platform version</a>
* configuration.
*/
ACONFIGURATION_VERSION = 0x0400,
/**
* Bit mask for screen layout configuration.
*/
ACONFIGURATION_SCREEN_LAYOUT = 0x0800,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#UiModeQualifier">ui mode</a>
* configuration.
*/
ACONFIGURATION_UI_MODE = 0x1000,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#SmallestScreenWidthQualifier">smallest screen width</a>
* configuration.
*/
ACONFIGURATION_SMALLEST_SCREEN_SIZE = 0x2000,
/**
* Bit mask for
* <a href="@dacRoot/guide/topics/resources/providing-resources.html#LayoutDirectionQualifier">layout direction</a>
* configuration.
*/
ACONFIGURATION_LAYOUTDIR = 0x4000,
ACONFIGURATION_SCREEN_ROUND = 0x8000,
/**
* Constant used to to represent MNC (Mobile Network Code) zero.
* 0 cannot be used, since it is used to represent an undefined MNC.
*/
ACONFIGURATION_MNC_ZERO = 0xffff,
};
/**
* Create a new AConfiguration, initialized with no values set.
*/
AConfiguration* AConfiguration_new();
/**
* Free an AConfiguration that was previously created with
* AConfiguration_new().
*/
void AConfiguration_delete(AConfiguration* config);
/**
* Create and return a new AConfiguration based on the current configuration in
* use in the given {@link AAssetManager}.
*/
void AConfiguration_fromAssetManager(AConfiguration* out, AAssetManager* am);
/**
* Copy the contents of 'src' to 'dest'.
*/
void AConfiguration_copy(AConfiguration* dest, AConfiguration* src);
/**
* Return the current MCC set in the configuration. 0 if not set.
*/
int32_t AConfiguration_getMcc(AConfiguration* config);
/**
* Set the current MCC in the configuration. 0 to clear.
*/
void AConfiguration_setMcc(AConfiguration* config, int32_t mcc);
/**
* Return the current MNC set in the configuration. 0 if not set.
*/
int32_t AConfiguration_getMnc(AConfiguration* config);
/**
* Set the current MNC in the configuration. 0 to clear.
*/
void AConfiguration_setMnc(AConfiguration* config, int32_t mnc);
/**
* Return the current language code set in the configuration. The output will
* be filled with an array of two characters. They are not 0-terminated. If
* a language is not set, they will be 0.
*/
void AConfiguration_getLanguage(AConfiguration* config, char* outLanguage);
/**
* Set the current language code in the configuration, from the first two
* characters in the string.
*/
void AConfiguration_setLanguage(AConfiguration* config, const char* language);
/**
* Return the current country code set in the configuration. The output will
* be filled with an array of two characters. They are not 0-terminated. If
* a country is not set, they will be 0.
*/
void AConfiguration_getCountry(AConfiguration* config, char* outCountry);
/**
* Set the current country code in the configuration, from the first two
* characters in the string.
*/
void AConfiguration_setCountry(AConfiguration* config, const char* country);
/**
* Return the current ACONFIGURATION_ORIENTATION_* set in the configuration.
*/
int32_t AConfiguration_getOrientation(AConfiguration* config);
/**
* Set the current orientation in the configuration.
*/
void AConfiguration_setOrientation(AConfiguration* config, int32_t orientation);
/**
* Return the current ACONFIGURATION_TOUCHSCREEN_* set in the configuration.
*/
int32_t AConfiguration_getTouchscreen(AConfiguration* config);
/**
* Set the current touchscreen in the configuration.
*/
void AConfiguration_setTouchscreen(AConfiguration* config, int32_t touchscreen);
/**
* Return the current ACONFIGURATION_DENSITY_* set in the configuration.
*/
int32_t AConfiguration_getDensity(AConfiguration* config);
/**
* Set the current density in the configuration.
*/
void AConfiguration_setDensity(AConfiguration* config, int32_t density);
/**
* Return the current ACONFIGURATION_KEYBOARD_* set in the configuration.
*/
int32_t AConfiguration_getKeyboard(AConfiguration* config);
/**
* Set the current keyboard in the configuration.
*/
void AConfiguration_setKeyboard(AConfiguration* config, int32_t keyboard);
/**
* Return the current ACONFIGURATION_NAVIGATION_* set in the configuration.
*/
int32_t AConfiguration_getNavigation(AConfiguration* config);
/**
* Set the current navigation in the configuration.
*/
void AConfiguration_setNavigation(AConfiguration* config, int32_t navigation);
/**
* Return the current ACONFIGURATION_KEYSHIDDEN_* set in the configuration.
*/
int32_t AConfiguration_getKeysHidden(AConfiguration* config);
/**
* Set the current keys hidden in the configuration.
*/
void AConfiguration_setKeysHidden(AConfiguration* config, int32_t keysHidden);
/**
* Return the current ACONFIGURATION_NAVHIDDEN_* set in the configuration.
*/
int32_t AConfiguration_getNavHidden(AConfiguration* config);
/**
* Set the current nav hidden in the configuration.
*/
void AConfiguration_setNavHidden(AConfiguration* config, int32_t navHidden);
/**
* Return the current SDK (API) version set in the configuration.
*/
int32_t AConfiguration_getSdkVersion(AConfiguration* config);
/**
* Set the current SDK version in the configuration.
*/
void AConfiguration_setSdkVersion(AConfiguration* config, int32_t sdkVersion);
/**
* Return the current ACONFIGURATION_SCREENSIZE_* set in the configuration.
*/
int32_t AConfiguration_getScreenSize(AConfiguration* config);
/**
* Set the current screen size in the configuration.
*/
void AConfiguration_setScreenSize(AConfiguration* config, int32_t screenSize);
/**
* Return the current ACONFIGURATION_SCREENLONG_* set in the configuration.
*/
int32_t AConfiguration_getScreenLong(AConfiguration* config);
/**
* Set the current screen long in the configuration.
*/
void AConfiguration_setScreenLong(AConfiguration* config, int32_t screenLong);
/**
* Return the current ACONFIGURATION_SCREENROUND_* set in the configuration.
*/
int32_t AConfiguration_getScreenRound(AConfiguration* config);
/**
* Set the current screen round in the configuration.
*/
void AConfiguration_setScreenRound(AConfiguration* config, int32_t screenRound);
/**
* Return the current ACONFIGURATION_UI_MODE_TYPE_* set in the configuration.
*/
int32_t AConfiguration_getUiModeType(AConfiguration* config);
/**
* Set the current UI mode type in the configuration.
*/
void AConfiguration_setUiModeType(AConfiguration* config, int32_t uiModeType);
/**
* Return the current ACONFIGURATION_UI_MODE_NIGHT_* set in the configuration.
*/
int32_t AConfiguration_getUiModeNight(AConfiguration* config);
/**
* Set the current UI mode night in the configuration.
*/
void AConfiguration_setUiModeNight(AConfiguration* config, int32_t uiModeNight);
/**
* Return the current configuration screen width in dp units, or
* ACONFIGURATION_SCREEN_WIDTH_DP_ANY if not set.
*/
int32_t AConfiguration_getScreenWidthDp(AConfiguration* config);
/**
* Set the configuration's current screen width in dp units.
*/
void AConfiguration_setScreenWidthDp(AConfiguration* config, int32_t value);
/**
* Return the current configuration screen height in dp units, or
* ACONFIGURATION_SCREEN_HEIGHT_DP_ANY if not set.
*/
int32_t AConfiguration_getScreenHeightDp(AConfiguration* config);
/**
* Set the configuration's current screen width in dp units.
*/
void AConfiguration_setScreenHeightDp(AConfiguration* config, int32_t value);
/**
* Return the configuration's smallest screen width in dp units, or
* ACONFIGURATION_SMALLEST_SCREEN_WIDTH_DP_ANY if not set.
*/
int32_t AConfiguration_getSmallestScreenWidthDp(AConfiguration* config);
/**
* Set the configuration's smallest screen width in dp units.
*/
void AConfiguration_setSmallestScreenWidthDp(AConfiguration* config, int32_t value);
/**
* Return the configuration's layout direction, or
* ACONFIGURATION_LAYOUTDIR_ANY if not set.
*/
int32_t AConfiguration_getLayoutDirection(AConfiguration* config);
/**
* Set the configuration's layout direction.
*/
void AConfiguration_setLayoutDirection(AConfiguration* config, int32_t value);
/**
* Perform a diff between two configurations. Returns a bit mask of
* ACONFIGURATION_* constants, each bit set meaning that configuration element
* is different between them.
*/
int32_t AConfiguration_diff(AConfiguration* config1, AConfiguration* config2);
/**
* Determine whether 'base' is a valid configuration for use within the
* environment 'requested'. Returns 0 if there are any values in 'base'
* that conflict with 'requested'. Returns 1 if it does not conflict.
*/
int32_t AConfiguration_match(AConfiguration* base, AConfiguration* requested);
/**
* Determine whether the configuration in 'test' is better than the existing
* configuration in 'base'. If 'requested' is non-NULL, this decision is based
* on the overall configuration given there. If it is NULL, this decision is
* simply based on which configuration is more specific. Returns non-0 if
* 'test' is better than 'base'.
*
* This assumes you have already filtered the configurations with
* AConfiguration_match().
*/
int32_t AConfiguration_isBetterThan(AConfiguration* base, AConfiguration* test,
AConfiguration* requested);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_CONFIGURATION_H
/** @} */
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,752 @@
/*
* 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.
*/
/**
* @addtogroup Input
* @{
*/
/**
* @file keycodes.h
*/
#ifndef _ANDROID_KEYCODES_H
#define _ANDROID_KEYCODES_H
/******************************************************************
*
* IMPORTANT NOTICE:
*
* This file is part of Android's set of stable system headers
* exposed by the Android NDK (Native Development Kit).
*
* Third-party source AND binary code relies on the definitions
* here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
*
* - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
* - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
* - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
* - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
*/
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Key codes.
*/
enum {
/** Unknown key code. */
AKEYCODE_UNKNOWN = 0,
/** Soft Left key.
* Usually situated below the display on phones and used as a multi-function
* feature key for selecting a software defined function shown on the bottom left
* of the display. */
AKEYCODE_SOFT_LEFT = 1,
/** Soft Right key.
* Usually situated below the display on phones and used as a multi-function
* feature key for selecting a software defined function shown on the bottom right
* of the display. */
AKEYCODE_SOFT_RIGHT = 2,
/** Home key.
* This key is handled by the framework and is never delivered to applications. */
AKEYCODE_HOME = 3,
/** Back key. */
AKEYCODE_BACK = 4,
/** Call key. */
AKEYCODE_CALL = 5,
/** End Call key. */
AKEYCODE_ENDCALL = 6,
/** '0' key. */
AKEYCODE_0 = 7,
/** '1' key. */
AKEYCODE_1 = 8,
/** '2' key. */
AKEYCODE_2 = 9,
/** '3' key. */
AKEYCODE_3 = 10,
/** '4' key. */
AKEYCODE_4 = 11,
/** '5' key. */
AKEYCODE_5 = 12,
/** '6' key. */
AKEYCODE_6 = 13,
/** '7' key. */
AKEYCODE_7 = 14,
/** '8' key. */
AKEYCODE_8 = 15,
/** '9' key. */
AKEYCODE_9 = 16,
/** '*' key. */
AKEYCODE_STAR = 17,
/** '#' key. */
AKEYCODE_POUND = 18,
/** Directional Pad Up key.
* May also be synthesized from trackball motions. */
AKEYCODE_DPAD_UP = 19,
/** Directional Pad Down key.
* May also be synthesized from trackball motions. */
AKEYCODE_DPAD_DOWN = 20,
/** Directional Pad Left key.
* May also be synthesized from trackball motions. */
AKEYCODE_DPAD_LEFT = 21,
/** Directional Pad Right key.
* May also be synthesized from trackball motions. */
AKEYCODE_DPAD_RIGHT = 22,
/** Directional Pad Center key.
* May also be synthesized from trackball motions. */
AKEYCODE_DPAD_CENTER = 23,
/** Volume Up key.
* Adjusts the speaker volume up. */
AKEYCODE_VOLUME_UP = 24,
/** Volume Down key.
* Adjusts the speaker volume down. */
AKEYCODE_VOLUME_DOWN = 25,
/** Power key. */
AKEYCODE_POWER = 26,
/** Camera key.
* Used to launch a camera application or take pictures. */
AKEYCODE_CAMERA = 27,
/** Clear key. */
AKEYCODE_CLEAR = 28,
/** 'A' key. */
AKEYCODE_A = 29,
/** 'B' key. */
AKEYCODE_B = 30,
/** 'C' key. */
AKEYCODE_C = 31,
/** 'D' key. */
AKEYCODE_D = 32,
/** 'E' key. */
AKEYCODE_E = 33,
/** 'F' key. */
AKEYCODE_F = 34,
/** 'G' key. */
AKEYCODE_G = 35,
/** 'H' key. */
AKEYCODE_H = 36,
/** 'I' key. */
AKEYCODE_I = 37,
/** 'J' key. */
AKEYCODE_J = 38,
/** 'K' key. */
AKEYCODE_K = 39,
/** 'L' key. */
AKEYCODE_L = 40,
/** 'M' key. */
AKEYCODE_M = 41,
/** 'N' key. */
AKEYCODE_N = 42,
/** 'O' key. */
AKEYCODE_O = 43,
/** 'P' key. */
AKEYCODE_P = 44,
/** 'Q' key. */
AKEYCODE_Q = 45,
/** 'R' key. */
AKEYCODE_R = 46,
/** 'S' key. */
AKEYCODE_S = 47,
/** 'T' key. */
AKEYCODE_T = 48,
/** 'U' key. */
AKEYCODE_U = 49,
/** 'V' key. */
AKEYCODE_V = 50,
/** 'W' key. */
AKEYCODE_W = 51,
/** 'X' key. */
AKEYCODE_X = 52,
/** 'Y' key. */
AKEYCODE_Y = 53,
/** 'Z' key. */
AKEYCODE_Z = 54,
/** ',' key. */
AKEYCODE_COMMA = 55,
/** '.' key. */
AKEYCODE_PERIOD = 56,
/** Left Alt modifier key. */
AKEYCODE_ALT_LEFT = 57,
/** Right Alt modifier key. */
AKEYCODE_ALT_RIGHT = 58,
/** Left Shift modifier key. */
AKEYCODE_SHIFT_LEFT = 59,
/** Right Shift modifier key. */
AKEYCODE_SHIFT_RIGHT = 60,
/** Tab key. */
AKEYCODE_TAB = 61,
/** Space key. */
AKEYCODE_SPACE = 62,
/** Symbol modifier key.
* Used to enter alternate symbols. */
AKEYCODE_SYM = 63,
/** Explorer special function key.
* Used to launch a browser application. */
AKEYCODE_EXPLORER = 64,
/** Envelope special function key.
* Used to launch a mail application. */
AKEYCODE_ENVELOPE = 65,
/** Enter key. */
AKEYCODE_ENTER = 66,
/** Backspace key.
* Deletes characters before the insertion point, unlike {@link AKEYCODE_FORWARD_DEL}. */
AKEYCODE_DEL = 67,
/** '`' (backtick) key. */
AKEYCODE_GRAVE = 68,
/** '-'. */
AKEYCODE_MINUS = 69,
/** '=' key. */
AKEYCODE_EQUALS = 70,
/** '[' key. */
AKEYCODE_LEFT_BRACKET = 71,
/** ']' key. */
AKEYCODE_RIGHT_BRACKET = 72,
/** '\' key. */
AKEYCODE_BACKSLASH = 73,
/** ';' key. */
AKEYCODE_SEMICOLON = 74,
/** ''' (apostrophe) key. */
AKEYCODE_APOSTROPHE = 75,
/** '/' key. */
AKEYCODE_SLASH = 76,
/** '@' key. */
AKEYCODE_AT = 77,
/** Number modifier key.
* Used to enter numeric symbols.
* This key is not {@link AKEYCODE_NUM_LOCK}; it is more like {@link AKEYCODE_ALT_LEFT}. */
AKEYCODE_NUM = 78,
/** Headset Hook key.
* Used to hang up calls and stop media. */
AKEYCODE_HEADSETHOOK = 79,
/** Camera Focus key.
* Used to focus the camera. */
AKEYCODE_FOCUS = 80,
/** '+' key. */
AKEYCODE_PLUS = 81,
/** Menu key. */
AKEYCODE_MENU = 82,
/** Notification key. */
AKEYCODE_NOTIFICATION = 83,
/** Search key. */
AKEYCODE_SEARCH = 84,
/** Play/Pause media key. */
AKEYCODE_MEDIA_PLAY_PAUSE= 85,
/** Stop media key. */
AKEYCODE_MEDIA_STOP = 86,
/** Play Next media key. */
AKEYCODE_MEDIA_NEXT = 87,
/** Play Previous media key. */
AKEYCODE_MEDIA_PREVIOUS = 88,
/** Rewind media key. */
AKEYCODE_MEDIA_REWIND = 89,
/** Fast Forward media key. */
AKEYCODE_MEDIA_FAST_FORWARD = 90,
/** Mute key.
* Mutes the microphone, unlike {@link AKEYCODE_VOLUME_MUTE}. */
AKEYCODE_MUTE = 91,
/** Page Up key. */
AKEYCODE_PAGE_UP = 92,
/** Page Down key. */
AKEYCODE_PAGE_DOWN = 93,
/** Picture Symbols modifier key.
* Used to switch symbol sets (Emoji, Kao-moji). */
AKEYCODE_PICTSYMBOLS = 94,
/** Switch Charset modifier key.
* Used to switch character sets (Kanji, Katakana). */
AKEYCODE_SWITCH_CHARSET = 95,
/** A Button key.
* On a game controller, the A button should be either the button labeled A
* or the first button on the bottom row of controller buttons. */
AKEYCODE_BUTTON_A = 96,
/** B Button key.
* On a game controller, the B button should be either the button labeled B
* or the second button on the bottom row of controller buttons. */
AKEYCODE_BUTTON_B = 97,
/** C Button key.
* On a game controller, the C button should be either the button labeled C
* or the third button on the bottom row of controller buttons. */
AKEYCODE_BUTTON_C = 98,
/** X Button key.
* On a game controller, the X button should be either the button labeled X
* or the first button on the upper row of controller buttons. */
AKEYCODE_BUTTON_X = 99,
/** Y Button key.
* On a game controller, the Y button should be either the button labeled Y
* or the second button on the upper row of controller buttons. */
AKEYCODE_BUTTON_Y = 100,
/** Z Button key.
* On a game controller, the Z button should be either the button labeled Z
* or the third button on the upper row of controller buttons. */
AKEYCODE_BUTTON_Z = 101,
/** L1 Button key.
* On a game controller, the L1 button should be either the button labeled L1 (or L)
* or the top left trigger button. */
AKEYCODE_BUTTON_L1 = 102,
/** R1 Button key.
* On a game controller, the R1 button should be either the button labeled R1 (or R)
* or the top right trigger button. */
AKEYCODE_BUTTON_R1 = 103,
/** L2 Button key.
* On a game controller, the L2 button should be either the button labeled L2
* or the bottom left trigger button. */
AKEYCODE_BUTTON_L2 = 104,
/** R2 Button key.
* On a game controller, the R2 button should be either the button labeled R2
* or the bottom right trigger button. */
AKEYCODE_BUTTON_R2 = 105,
/** Left Thumb Button key.
* On a game controller, the left thumb button indicates that the left (or only)
* joystick is pressed. */
AKEYCODE_BUTTON_THUMBL = 106,
/** Right Thumb Button key.
* On a game controller, the right thumb button indicates that the right
* joystick is pressed. */
AKEYCODE_BUTTON_THUMBR = 107,
/** Start Button key.
* On a game controller, the button labeled Start. */
AKEYCODE_BUTTON_START = 108,
/** Select Button key.
* On a game controller, the button labeled Select. */
AKEYCODE_BUTTON_SELECT = 109,
/** Mode Button key.
* On a game controller, the button labeled Mode. */
AKEYCODE_BUTTON_MODE = 110,
/** Escape key. */
AKEYCODE_ESCAPE = 111,
/** Forward Delete key.
* Deletes characters ahead of the insertion point, unlike {@link AKEYCODE_DEL}. */
AKEYCODE_FORWARD_DEL = 112,
/** Left Control modifier key. */
AKEYCODE_CTRL_LEFT = 113,
/** Right Control modifier key. */
AKEYCODE_CTRL_RIGHT = 114,
/** Caps Lock key. */
AKEYCODE_CAPS_LOCK = 115,
/** Scroll Lock key. */
AKEYCODE_SCROLL_LOCK = 116,
/** Left Meta modifier key. */
AKEYCODE_META_LEFT = 117,
/** Right Meta modifier key. */
AKEYCODE_META_RIGHT = 118,
/** Function modifier key. */
AKEYCODE_FUNCTION = 119,
/** System Request / Print Screen key. */
AKEYCODE_SYSRQ = 120,
/** Break / Pause key. */
AKEYCODE_BREAK = 121,
/** Home Movement key.
* Used for scrolling or moving the cursor around to the start of a line
* or to the top of a list. */
AKEYCODE_MOVE_HOME = 122,
/** End Movement key.
* Used for scrolling or moving the cursor around to the end of a line
* or to the bottom of a list. */
AKEYCODE_MOVE_END = 123,
/** Insert key.
* Toggles insert / overwrite edit mode. */
AKEYCODE_INSERT = 124,
/** Forward key.
* Navigates forward in the history stack. Complement of {@link AKEYCODE_BACK}. */
AKEYCODE_FORWARD = 125,
/** Play media key. */
AKEYCODE_MEDIA_PLAY = 126,
/** Pause media key. */
AKEYCODE_MEDIA_PAUSE = 127,
/** Close media key.
* May be used to close a CD tray, for example. */
AKEYCODE_MEDIA_CLOSE = 128,
/** Eject media key.
* May be used to eject a CD tray, for example. */
AKEYCODE_MEDIA_EJECT = 129,
/** Record media key. */
AKEYCODE_MEDIA_RECORD = 130,
/** F1 key. */
AKEYCODE_F1 = 131,
/** F2 key. */
AKEYCODE_F2 = 132,
/** F3 key. */
AKEYCODE_F3 = 133,
/** F4 key. */
AKEYCODE_F4 = 134,
/** F5 key. */
AKEYCODE_F5 = 135,
/** F6 key. */
AKEYCODE_F6 = 136,
/** F7 key. */
AKEYCODE_F7 = 137,
/** F8 key. */
AKEYCODE_F8 = 138,
/** F9 key. */
AKEYCODE_F9 = 139,
/** F10 key. */
AKEYCODE_F10 = 140,
/** F11 key. */
AKEYCODE_F11 = 141,
/** F12 key. */
AKEYCODE_F12 = 142,
/** Num Lock key.
* This is the Num Lock key; it is different from {@link AKEYCODE_NUM}.
* This key alters the behavior of other keys on the numeric keypad. */
AKEYCODE_NUM_LOCK = 143,
/** Numeric keypad '0' key. */
AKEYCODE_NUMPAD_0 = 144,
/** Numeric keypad '1' key. */
AKEYCODE_NUMPAD_1 = 145,
/** Numeric keypad '2' key. */
AKEYCODE_NUMPAD_2 = 146,
/** Numeric keypad '3' key. */
AKEYCODE_NUMPAD_3 = 147,
/** Numeric keypad '4' key. */
AKEYCODE_NUMPAD_4 = 148,
/** Numeric keypad '5' key. */
AKEYCODE_NUMPAD_5 = 149,
/** Numeric keypad '6' key. */
AKEYCODE_NUMPAD_6 = 150,
/** Numeric keypad '7' key. */
AKEYCODE_NUMPAD_7 = 151,
/** Numeric keypad '8' key. */
AKEYCODE_NUMPAD_8 = 152,
/** Numeric keypad '9' key. */
AKEYCODE_NUMPAD_9 = 153,
/** Numeric keypad '/' key (for division). */
AKEYCODE_NUMPAD_DIVIDE = 154,
/** Numeric keypad '*' key (for multiplication). */
AKEYCODE_NUMPAD_MULTIPLY = 155,
/** Numeric keypad '-' key (for subtraction). */
AKEYCODE_NUMPAD_SUBTRACT = 156,
/** Numeric keypad '+' key (for addition). */
AKEYCODE_NUMPAD_ADD = 157,
/** Numeric keypad '.' key (for decimals or digit grouping). */
AKEYCODE_NUMPAD_DOT = 158,
/** Numeric keypad ',' key (for decimals or digit grouping). */
AKEYCODE_NUMPAD_COMMA = 159,
/** Numeric keypad Enter key. */
AKEYCODE_NUMPAD_ENTER = 160,
/** Numeric keypad '=' key. */
AKEYCODE_NUMPAD_EQUALS = 161,
/** Numeric keypad '(' key. */
AKEYCODE_NUMPAD_LEFT_PAREN = 162,
/** Numeric keypad ')' key. */
AKEYCODE_NUMPAD_RIGHT_PAREN = 163,
/** Volume Mute key.
* Mutes the speaker, unlike {@link AKEYCODE_MUTE}.
* This key should normally be implemented as a toggle such that the first press
* mutes the speaker and the second press restores the original volume. */
AKEYCODE_VOLUME_MUTE = 164,
/** Info key.
* Common on TV remotes to show additional information related to what is
* currently being viewed. */
AKEYCODE_INFO = 165,
/** Channel up key.
* On TV remotes, increments the television channel. */
AKEYCODE_CHANNEL_UP = 166,
/** Channel down key.
* On TV remotes, decrements the television channel. */
AKEYCODE_CHANNEL_DOWN = 167,
/** Zoom in key. */
AKEYCODE_ZOOM_IN = 168,
/** Zoom out key. */
AKEYCODE_ZOOM_OUT = 169,
/** TV key.
* On TV remotes, switches to viewing live TV. */
AKEYCODE_TV = 170,
/** Window key.
* On TV remotes, toggles picture-in-picture mode or other windowing functions. */
AKEYCODE_WINDOW = 171,
/** Guide key.
* On TV remotes, shows a programming guide. */
AKEYCODE_GUIDE = 172,
/** DVR key.
* On some TV remotes, switches to a DVR mode for recorded shows. */
AKEYCODE_DVR = 173,
/** Bookmark key.
* On some TV remotes, bookmarks content or web pages. */
AKEYCODE_BOOKMARK = 174,
/** Toggle captions key.
* Switches the mode for closed-captioning text, for example during television shows. */
AKEYCODE_CAPTIONS = 175,
/** Settings key.
* Starts the system settings activity. */
AKEYCODE_SETTINGS = 176,
/** TV power key.
* On TV remotes, toggles the power on a television screen. */
AKEYCODE_TV_POWER = 177,
/** TV input key.
* On TV remotes, switches the input on a television screen. */
AKEYCODE_TV_INPUT = 178,
/** Set-top-box power key.
* On TV remotes, toggles the power on an external Set-top-box. */
AKEYCODE_STB_POWER = 179,
/** Set-top-box input key.
* On TV remotes, switches the input mode on an external Set-top-box. */
AKEYCODE_STB_INPUT = 180,
/** A/V Receiver power key.
* On TV remotes, toggles the power on an external A/V Receiver. */
AKEYCODE_AVR_POWER = 181,
/** A/V Receiver input key.
* On TV remotes, switches the input mode on an external A/V Receiver. */
AKEYCODE_AVR_INPUT = 182,
/** Red "programmable" key.
* On TV remotes, acts as a contextual/programmable key. */
AKEYCODE_PROG_RED = 183,
/** Green "programmable" key.
* On TV remotes, actsas a contextual/programmable key. */
AKEYCODE_PROG_GREEN = 184,
/** Yellow "programmable" key.
* On TV remotes, acts as a contextual/programmable key. */
AKEYCODE_PROG_YELLOW = 185,
/** Blue "programmable" key.
* On TV remotes, acts as a contextual/programmable key. */
AKEYCODE_PROG_BLUE = 186,
/** App switch key.
* Should bring up the application switcher dialog. */
AKEYCODE_APP_SWITCH = 187,
/** Generic Game Pad Button #1.*/
AKEYCODE_BUTTON_1 = 188,
/** Generic Game Pad Button #2.*/
AKEYCODE_BUTTON_2 = 189,
/** Generic Game Pad Button #3.*/
AKEYCODE_BUTTON_3 = 190,
/** Generic Game Pad Button #4.*/
AKEYCODE_BUTTON_4 = 191,
/** Generic Game Pad Button #5.*/
AKEYCODE_BUTTON_5 = 192,
/** Generic Game Pad Button #6.*/
AKEYCODE_BUTTON_6 = 193,
/** Generic Game Pad Button #7.*/
AKEYCODE_BUTTON_7 = 194,
/** Generic Game Pad Button #8.*/
AKEYCODE_BUTTON_8 = 195,
/** Generic Game Pad Button #9.*/
AKEYCODE_BUTTON_9 = 196,
/** Generic Game Pad Button #10.*/
AKEYCODE_BUTTON_10 = 197,
/** Generic Game Pad Button #11.*/
AKEYCODE_BUTTON_11 = 198,
/** Generic Game Pad Button #12.*/
AKEYCODE_BUTTON_12 = 199,
/** Generic Game Pad Button #13.*/
AKEYCODE_BUTTON_13 = 200,
/** Generic Game Pad Button #14.*/
AKEYCODE_BUTTON_14 = 201,
/** Generic Game Pad Button #15.*/
AKEYCODE_BUTTON_15 = 202,
/** Generic Game Pad Button #16.*/
AKEYCODE_BUTTON_16 = 203,
/** Language Switch key.
* Toggles the current input language such as switching between English and Japanese on
* a QWERTY keyboard. On some devices, the same function may be performed by
* pressing Shift+Spacebar. */
AKEYCODE_LANGUAGE_SWITCH = 204,
/** Manner Mode key.
* Toggles silent or vibrate mode on and off to make the device behave more politely
* in certain settings such as on a crowded train. On some devices, the key may only
* operate when long-pressed. */
AKEYCODE_MANNER_MODE = 205,
/** 3D Mode key.
* Toggles the display between 2D and 3D mode. */
AKEYCODE_3D_MODE = 206,
/** Contacts special function key.
* Used to launch an address book application. */
AKEYCODE_CONTACTS = 207,
/** Calendar special function key.
* Used to launch a calendar application. */
AKEYCODE_CALENDAR = 208,
/** Music special function key.
* Used to launch a music player application. */
AKEYCODE_MUSIC = 209,
/** Calculator special function key.
* Used to launch a calculator application. */
AKEYCODE_CALCULATOR = 210,
/** Japanese full-width / half-width key. */
AKEYCODE_ZENKAKU_HANKAKU = 211,
/** Japanese alphanumeric key. */
AKEYCODE_EISU = 212,
/** Japanese non-conversion key. */
AKEYCODE_MUHENKAN = 213,
/** Japanese conversion key. */
AKEYCODE_HENKAN = 214,
/** Japanese katakana / hiragana key. */
AKEYCODE_KATAKANA_HIRAGANA = 215,
/** Japanese Yen key. */
AKEYCODE_YEN = 216,
/** Japanese Ro key. */
AKEYCODE_RO = 217,
/** Japanese kana key. */
AKEYCODE_KANA = 218,
/** Assist key.
* Launches the global assist activity. Not delivered to applications. */
AKEYCODE_ASSIST = 219,
/** Brightness Down key.
* Adjusts the screen brightness down. */
AKEYCODE_BRIGHTNESS_DOWN = 220,
/** Brightness Up key.
* Adjusts the screen brightness up. */
AKEYCODE_BRIGHTNESS_UP = 221,
/** Audio Track key.
* Switches the audio tracks. */
AKEYCODE_MEDIA_AUDIO_TRACK = 222,
/** Sleep key.
* Puts the device to sleep. Behaves somewhat like {@link AKEYCODE_POWER} but it
* has no effect if the device is already asleep. */
AKEYCODE_SLEEP = 223,
/** Wakeup key.
* Wakes up the device. Behaves somewhat like {@link AKEYCODE_POWER} but it
* has no effect if the device is already awake. */
AKEYCODE_WAKEUP = 224,
/** Pairing key.
* Initiates peripheral pairing mode. Useful for pairing remote control
* devices or game controllers, especially if no other input mode is
* available. */
AKEYCODE_PAIRING = 225,
/** Media Top Menu key.
* Goes to the top of media menu. */
AKEYCODE_MEDIA_TOP_MENU = 226,
/** '11' key. */
AKEYCODE_11 = 227,
/** '12' key. */
AKEYCODE_12 = 228,
/** Last Channel key.
* Goes to the last viewed channel. */
AKEYCODE_LAST_CHANNEL = 229,
/** TV data service key.
* Displays data services like weather, sports. */
AKEYCODE_TV_DATA_SERVICE = 230,
/** Voice Assist key.
* Launches the global voice assist activity. Not delivered to applications. */
AKEYCODE_VOICE_ASSIST = 231,
/** Radio key.
* Toggles TV service / Radio service. */
AKEYCODE_TV_RADIO_SERVICE = 232,
/** Teletext key.
* Displays Teletext service. */
AKEYCODE_TV_TELETEXT = 233,
/** Number entry key.
* Initiates to enter multi-digit channel nubmber when each digit key is assigned
* for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC
* User Control Code. */
AKEYCODE_TV_NUMBER_ENTRY = 234,
/** Analog Terrestrial key.
* Switches to analog terrestrial broadcast service. */
AKEYCODE_TV_TERRESTRIAL_ANALOG = 235,
/** Digital Terrestrial key.
* Switches to digital terrestrial broadcast service. */
AKEYCODE_TV_TERRESTRIAL_DIGITAL = 236,
/** Satellite key.
* Switches to digital satellite broadcast service. */
AKEYCODE_TV_SATELLITE = 237,
/** BS key.
* Switches to BS digital satellite broadcasting service available in Japan. */
AKEYCODE_TV_SATELLITE_BS = 238,
/** CS key.
* Switches to CS digital satellite broadcasting service available in Japan. */
AKEYCODE_TV_SATELLITE_CS = 239,
/** BS/CS key.
* Toggles between BS and CS digital satellite services. */
AKEYCODE_TV_SATELLITE_SERVICE = 240,
/** Toggle Network key.
* Toggles selecting broacast services. */
AKEYCODE_TV_NETWORK = 241,
/** Antenna/Cable key.
* Toggles broadcast input source between antenna and cable. */
AKEYCODE_TV_ANTENNA_CABLE = 242,
/** HDMI #1 key.
* Switches to HDMI input #1. */
AKEYCODE_TV_INPUT_HDMI_1 = 243,
/** HDMI #2 key.
* Switches to HDMI input #2. */
AKEYCODE_TV_INPUT_HDMI_2 = 244,
/** HDMI #3 key.
* Switches to HDMI input #3. */
AKEYCODE_TV_INPUT_HDMI_3 = 245,
/** HDMI #4 key.
* Switches to HDMI input #4. */
AKEYCODE_TV_INPUT_HDMI_4 = 246,
/** Composite #1 key.
* Switches to composite video input #1. */
AKEYCODE_TV_INPUT_COMPOSITE_1 = 247,
/** Composite #2 key.
* Switches to composite video input #2. */
AKEYCODE_TV_INPUT_COMPOSITE_2 = 248,
/** Component #1 key.
* Switches to component video input #1. */
AKEYCODE_TV_INPUT_COMPONENT_1 = 249,
/** Component #2 key.
* Switches to component video input #2. */
AKEYCODE_TV_INPUT_COMPONENT_2 = 250,
/** VGA #1 key.
* Switches to VGA (analog RGB) input #1. */
AKEYCODE_TV_INPUT_VGA_1 = 251,
/** Audio description key.
* Toggles audio description off / on. */
AKEYCODE_TV_AUDIO_DESCRIPTION = 252,
/** Audio description mixing volume up key.
* Louden audio description volume as compared with normal audio volume. */
AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253,
/** Audio description mixing volume down key.
* Lessen audio description volume as compared with normal audio volume. */
AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254,
/** Zoom mode key.
* Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) */
AKEYCODE_TV_ZOOM_MODE = 255,
/** Contents menu key.
* Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control
* Code */
AKEYCODE_TV_CONTENTS_MENU = 256,
/** Media context menu key.
* Goes to the context menu of media contents. Corresponds to Media Context-sensitive
* Menu (0x11) of CEC User Control Code. */
AKEYCODE_TV_MEDIA_CONTEXT_MENU = 257,
/** Timer programming key.
* Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of
* CEC User Control Code. */
AKEYCODE_TV_TIMER_PROGRAMMING = 258,
/** Help key. */
AKEYCODE_HELP = 259,
AKEYCODE_NAVIGATE_PREVIOUS = 260,
AKEYCODE_NAVIGATE_NEXT = 261,
AKEYCODE_NAVIGATE_IN = 262,
AKEYCODE_NAVIGATE_OUT = 263,
/** Primary stem key for Wear
* Main power/reset button on watch. */
AKEYCODE_STEM_PRIMARY = 264,
/** Generic stem key 1 for Wear */
AKEYCODE_STEM_1 = 265,
/** Generic stem key 2 for Wear */
AKEYCODE_STEM_2 = 266,
/** Generic stem key 3 for Wear */
AKEYCODE_STEM_3 = 267,
AKEYCODE_MEDIA_SKIP_FORWARD = 272,
AKEYCODE_MEDIA_SKIP_BACKWARD = 273,
AKEYCODE_MEDIA_STEP_FORWARD = 274,
AKEYCODE_MEDIA_STEP_BACKWARD = 275,
/** Put device to sleep unless a wakelock is held. */
AKEYCODE_SOFT_SLEEP = 276
// NOTE: If you add a new keycode here you must also add it to several other files.
// Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
};
#ifdef __cplusplus
}
#endif
#endif // _ANDROID_KEYCODES_H
/** @} */
@@ -0,0 +1,269 @@
/*
* 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.
*/
/**
* @addtogroup Looper
* @{
*/
/**
* @file looper.h
*/
#ifndef ANDROID_LOOPER_H
#define ANDROID_LOOPER_H
#ifdef __cplusplus
extern "C" {
#endif
struct ALooper;
/**
* ALooper
*
* A looper is the state tracking an event loop for a thread.
* Loopers do not define event structures or other such things; rather
* they are a lower-level facility to attach one or more discrete objects
* listening for an event. An "event" here is simply data available on
* a file descriptor: each attached object has an associated file descriptor,
* and waiting for "events" means (internally) polling on all of these file
* descriptors until one or more of them have data available.
*
* A thread can have only one ALooper associated with it.
*/
typedef struct ALooper ALooper;
/**
* Returns the looper associated with the calling thread, or NULL if
* there is not one.
*/
ALooper* ALooper_forThread();
/** Option for for ALooper_prepare(). */
enum {
/**
* This looper will accept calls to ALooper_addFd() that do not
* have a callback (that is provide NULL for the callback). In
* this case the caller of ALooper_pollOnce() or ALooper_pollAll()
* MUST check the return from these functions to discover when
* data is available on such fds and process it.
*/
ALOOPER_PREPARE_ALLOW_NON_CALLBACKS = 1<<0
};
/**
* Prepares a looper associated with the calling thread, and returns it.
* If the thread already has a looper, it is returned. Otherwise, a new
* one is created, associated with the thread, and returned.
*
* The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
*/
ALooper* ALooper_prepare(int opts);
/** Result from ALooper_pollOnce() and ALooper_pollAll(). */
enum {
/**
* The poll was awoken using wake() before the timeout expired
* and no callbacks were executed and no other file descriptors were ready.
*/
ALOOPER_POLL_WAKE = -1,
/**
* Result from ALooper_pollOnce() and ALooper_pollAll():
* One or more callbacks were executed.
*/
ALOOPER_POLL_CALLBACK = -2,
/**
* Result from ALooper_pollOnce() and ALooper_pollAll():
* The timeout expired.
*/
ALOOPER_POLL_TIMEOUT = -3,
/**
* Result from ALooper_pollOnce() and ALooper_pollAll():
* An error occurred.
*/
ALOOPER_POLL_ERROR = -4,
};
/**
* Acquire a reference on the given ALooper object. This prevents the object
* from being deleted until the reference is removed. This is only needed
* to safely hand an ALooper from one thread to another.
*/
void ALooper_acquire(ALooper* looper);
/**
* Remove a reference that was previously acquired with ALooper_acquire().
*/
void ALooper_release(ALooper* looper);
/**
* Flags for file descriptor events that a looper can monitor.
*
* These flag bits can be combined to monitor multiple events at once.
*/
enum {
/**
* The file descriptor is available for read operations.
*/
ALOOPER_EVENT_INPUT = 1 << 0,
/**
* The file descriptor is available for write operations.
*/
ALOOPER_EVENT_OUTPUT = 1 << 1,
/**
* The file descriptor has encountered an error condition.
*
* The looper always sends notifications about errors; it is not necessary
* to specify this event flag in the requested event set.
*/
ALOOPER_EVENT_ERROR = 1 << 2,
/**
* The file descriptor was hung up.
* For example, indicates that the remote end of a pipe or socket was closed.
*
* The looper always sends notifications about hangups; it is not necessary
* to specify this event flag in the requested event set.
*/
ALOOPER_EVENT_HANGUP = 1 << 3,
/**
* The file descriptor is invalid.
* For example, the file descriptor was closed prematurely.
*
* The looper always sends notifications about invalid file descriptors; it is not necessary
* to specify this event flag in the requested event set.
*/
ALOOPER_EVENT_INVALID = 1 << 4,
};
/**
* For callback-based event loops, this is the prototype of the function
* that is called when a file descriptor event occurs.
* It is given the file descriptor it is associated with,
* a bitmask of the poll events that were triggered (typically ALOOPER_EVENT_INPUT),
* and the data pointer that was originally supplied.
*
* Implementations should return 1 to continue receiving callbacks, or 0
* to have this file descriptor and callback unregistered from the looper.
*/
typedef int (*ALooper_callbackFunc)(int fd, int events, void* data);
/**
* Waits for events to be available, with optional timeout in milliseconds.
* Invokes callbacks for all file descriptors on which an event occurred.
*
* If the timeout is zero, returns immediately without blocking.
* If the timeout is negative, waits indefinitely until an event appears.
*
* Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
* the timeout expired and no callbacks were invoked and no other file
* descriptors were ready.
*
* Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
*
* Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
* timeout expired.
*
* Returns ALOOPER_POLL_ERROR if an error occurred.
*
* Returns a value >= 0 containing an identifier (the same identifier
* `ident` passed to ALooper_addFd()) if its file descriptor has data
* and it has no callback function (requiring the caller here to
* handle it). In this (and only this) case outFd, outEvents and
* outData will contain the poll events and data associated with the
* fd, otherwise they will be set to NULL.
*
* This method does not return until it has finished invoking the appropriate callbacks
* for all file descriptors that were signalled.
*/
int ALooper_pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
/**
* Like ALooper_pollOnce(), but performs all pending callbacks until all
* data has been consumed or a file descriptor is available with no callback.
* This function will never return ALOOPER_POLL_CALLBACK.
*/
int ALooper_pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
/**
* Wakes the poll asynchronously.
*
* This method can be called on any thread.
* This method returns immediately.
*/
void ALooper_wake(ALooper* looper);
/**
* Adds a new file descriptor to be polled by the looper.
* If the same file descriptor was previously added, it is replaced.
*
* "fd" is the file descriptor to be added.
* "ident" is an identifier for this event, which is returned from ALooper_pollOnce().
* The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
* "events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT.
* "callback" is the function to call when there is an event on the file descriptor.
* "data" is a private data pointer to supply to the callback.
*
* There are two main uses of this function:
*
* (1) If "callback" is non-NULL, then this function will be called when there is
* data on the file descriptor. It should execute any events it has pending,
* appropriately reading from the file descriptor. The 'ident' is ignored in this case.
*
* (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
* when its file descriptor has data available, requiring the caller to take
* care of processing it.
*
* Returns 1 if the file descriptor was added or -1 if an error occurred.
*
* This method can be called on any thread.
* This method may block briefly if it needs to wake the poll.
*/
int ALooper_addFd(ALooper* looper, int fd, int ident, int events,
ALooper_callbackFunc callback, void* data);
/**
* Removes a previously added file descriptor from the looper.
*
* When this method returns, it is safe to close the file descriptor since the looper
* will no longer have a reference to it. However, it is possible for the callback to
* already be running or for it to run one last time if the file descriptor was already
* signalled. Calling code is responsible for ensuring that this case is safely handled.
* For example, if the callback takes care of removing itself during its own execution either
* by returning 0 or by calling this method, then it can be guaranteed to not be invoked
* again at any later time unless registered anew.
*
* Returns 1 if the file descriptor was removed, 0 if none was previously registered
* or -1 if an error occurred.
*
* This method can be called on any thread.
* This method may block briefly if it needs to wake the poll.
*/
int ALooper_removeFd(ALooper* looper, int fd);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_LOOPER_H
/** @} */
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2015 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_MULTINETWORK_H
#define ANDROID_MULTINETWORK_H
#include <netdb.h>
#include <stdlib.h>
#include <sys/cdefs.h>
__BEGIN_DECLS
/**
* The corresponding C type for android.net.Network#getNetworkHandle() return
* values. The Java signed long value can be safely cast to a net_handle_t:
*
* [C] ((net_handle_t) java_long_network_handle)
* [C++] static_cast<net_handle_t>(java_long_network_handle)
*
* as appropriate.
*/
typedef uint64_t net_handle_t;
/**
* The value NETWORK_UNSPECIFIED indicates no specific network.
*
* For some functions (documented below), a previous binding may be cleared
* by an invocation with NETWORK_UNSPECIFIED.
*
* Depending on the context it may indicate an error. It is expressly
* not used to indicate some notion of the "current default network".
*/
#define NETWORK_UNSPECIFIED ((net_handle_t)0)
/**
* All functions below that return an int return 0 on success or -1
* on failure with an appropriate errno value set.
*/
/**
* Set the network to be used by the given socket file descriptor.
*
* To clear a previous socket binding invoke with NETWORK_UNSPECIFIED.
*
* This is the equivalent of:
*
* [ android.net.Network#bindSocket() ]
* https://developer.android.com/reference/android/net/Network.html#bindSocket(java.net.Socket)
*/
int android_setsocknetwork(net_handle_t network, int fd);
/**
* Binds the current process to |network|. All sockets created in the future
* (and not explicitly bound via android_setsocknetwork()) will be bound to
* |network|. All host name resolutions will be limited to |network| as well.
* Note that if the network identified by |network| ever disconnects, all
* sockets created in this way will cease to work and all host name
* resolutions will fail. This is by design so an application doesn't
* accidentally use sockets it thinks are still bound to a particular network.
*
* To clear a previous process binding invoke with NETWORK_UNSPECIFIED.
*
* This is the equivalent of:
*
* [ android.net.ConnectivityManager#setProcessDefaultNetwork() ]
* https://developer.android.com/reference/android/net/ConnectivityManager.html#setProcessDefaultNetwork(android.net.Network)
*/
int android_setprocnetwork(net_handle_t network);
/**
* Perform hostname resolution via the DNS servers associated with |network|.
*
* All arguments (apart from |network|) are used identically as those passed
* to getaddrinfo(3). Return and error values are identical to those of
* getaddrinfo(3), and in particular gai_strerror(3) can be used as expected.
* Similar to getaddrinfo(3):
* - |hints| may be NULL (in which case man page documented defaults apply)
* - either |node| or |service| may be NULL, but not both
* - |res| must not be NULL
*
* This is the equivalent of:
*
* [ android.net.Network#getAllByName() ]
* https://developer.android.com/reference/android/net/Network.html#getAllByName(java.lang.String)
*/
int android_getaddrinfofornetwork(net_handle_t network,
const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res);
__END_DECLS
#endif // ANDROID_MULTINETWORK_H
@@ -0,0 +1,340 @@
/*
* 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.
*/
/**
* @addtogroup NativeActivity Native Activity
* @{
*/
/**
* @file native_activity.h
*/
#ifndef ANDROID_NATIVE_ACTIVITY_H
#define ANDROID_NATIVE_ACTIVITY_H
#include <stdint.h>
#include <sys/types.h>
#include <jni.h>
#include <android/asset_manager.h>
#include <android/input.h>
#include <android/native_window.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* {@link ANativeActivityCallbacks}
*/
struct ANativeActivityCallbacks;
/**
* This structure defines the native side of an android.app.NativeActivity.
* It is created by the framework, and handed to the application's native
* code as it is being launched.
*/
typedef struct ANativeActivity {
/**
* Pointer to the callback function table of the native application.
* You can set the functions here to your own callbacks. The callbacks
* pointer itself here should not be changed; it is allocated and managed
* for you by the framework.
*/
struct ANativeActivityCallbacks* callbacks;
/**
* The global handle on the process's Java VM.
*/
JavaVM* vm;
/**
* JNI context for the main thread of the app. Note that this field
* can ONLY be used from the main thread of the process; that is, the
* thread that calls into the ANativeActivityCallbacks.
*/
JNIEnv* env;
/**
* The NativeActivity object handle.
*
* IMPORTANT NOTE: This member is mis-named. It should really be named
* 'activity' instead of 'clazz', since it's a reference to the
* NativeActivity instance created by the system for you.
*
* We unfortunately cannot change this without breaking NDK
* source-compatibility.
*/
jobject clazz;
/**
* Path to this application's internal data directory.
*/
const char* internalDataPath;
/**
* Path to this application's external (removable/mountable) data directory.
*/
const char* externalDataPath;
/**
* The platform's SDK version code.
*/
int32_t sdkVersion;
/**
* This is the native instance of the application. It is not used by
* the framework, but can be set by the application to its own instance
* state.
*/
void* instance;
/**
* Pointer to the Asset Manager instance for the application. The application
* uses this to access binary assets bundled inside its own .apk file.
*/
AAssetManager* assetManager;
/**
* Available starting with Honeycomb: path to the directory containing
* the application's OBB files (if any). If the app doesn't have any
* OBB files, this directory may not exist.
*/
const char* obbPath;
} ANativeActivity;
/**
* These are the callbacks the framework makes into a native application.
* All of these callbacks happen on the main thread of the application.
* By default, all callbacks are NULL; set to a pointer to your own function
* to have it called.
*/
typedef struct ANativeActivityCallbacks {
/**
* NativeActivity has started. See Java documentation for Activity.onStart()
* for more information.
*/
void (*onStart)(ANativeActivity* activity);
/**
* NativeActivity has resumed. See Java documentation for Activity.onResume()
* for more information.
*/
void (*onResume)(ANativeActivity* activity);
/**
* Framework is asking NativeActivity to save its current instance state.
* See Java documentation for Activity.onSaveInstanceState() for more
* information. The returned pointer needs to be created with malloc();
* the framework will call free() on it for you. You also must fill in
* outSize with the number of bytes in the allocation. Note that the
* saved state will be persisted, so it can not contain any active
* entities (pointers to memory, file descriptors, etc).
*/
void* (*onSaveInstanceState)(ANativeActivity* activity, size_t* outSize);
/**
* NativeActivity has paused. See Java documentation for Activity.onPause()
* for more information.
*/
void (*onPause)(ANativeActivity* activity);
/**
* NativeActivity has stopped. See Java documentation for Activity.onStop()
* for more information.
*/
void (*onStop)(ANativeActivity* activity);
/**
* NativeActivity is being destroyed. See Java documentation for Activity.onDestroy()
* for more information.
*/
void (*onDestroy)(ANativeActivity* activity);
/**
* Focus has changed in this NativeActivity's window. This is often used,
* for example, to pause a game when it loses input focus.
*/
void (*onWindowFocusChanged)(ANativeActivity* activity, int hasFocus);
/**
* The drawing window for this native activity has been created. You
* can use the given native window object to start drawing.
*/
void (*onNativeWindowCreated)(ANativeActivity* activity, ANativeWindow* window);
/**
* The drawing window for this native activity has been resized. You should
* retrieve the new size from the window and ensure that your rendering in
* it now matches.
*/
void (*onNativeWindowResized)(ANativeActivity* activity, ANativeWindow* window);
/**
* The drawing window for this native activity needs to be redrawn. To avoid
* transient artifacts during screen changes (such resizing after rotation),
* applications should not return from this function until they have finished
* drawing their window in its current state.
*/
void (*onNativeWindowRedrawNeeded)(ANativeActivity* activity, ANativeWindow* window);
/**
* The drawing window for this native activity is going to be destroyed.
* You MUST ensure that you do not touch the window object after returning
* from this function: in the common case of drawing to the window from
* another thread, that means the implementation of this callback must
* properly synchronize with the other thread to stop its drawing before
* returning from here.
*/
void (*onNativeWindowDestroyed)(ANativeActivity* activity, ANativeWindow* window);
/**
* The input queue for this native activity's window has been created.
* You can use the given input queue to start retrieving input events.
*/
void (*onInputQueueCreated)(ANativeActivity* activity, AInputQueue* queue);
/**
* The input queue for this native activity's window is being destroyed.
* You should no longer try to reference this object upon returning from this
* function.
*/
void (*onInputQueueDestroyed)(ANativeActivity* activity, AInputQueue* queue);
/**
* The rectangle in the window in which content should be placed has changed.
*/
void (*onContentRectChanged)(ANativeActivity* activity, const ARect* rect);
/**
* The current device AConfiguration has changed. The new configuration can
* be retrieved from assetManager.
*/
void (*onConfigurationChanged)(ANativeActivity* activity);
/**
* The system is running low on memory. Use this callback to release
* resources you do not need, to help the system avoid killing more
* important processes.
*/
void (*onLowMemory)(ANativeActivity* activity);
} ANativeActivityCallbacks;
/**
* This is the function that must be in the native code to instantiate the
* application's native activity. It is called with the activity instance (see
* above); if the code is being instantiated from a previously saved instance,
* the savedState will be non-NULL and point to the saved data. You must make
* any copy of this data you need -- it will be released after you return from
* this function.
*/
typedef void ANativeActivity_createFunc(ANativeActivity* activity,
void* savedState, size_t savedStateSize);
/**
* The name of the function that NativeInstance looks for when launching its
* native code. This is the default function that is used, you can specify
* "android.app.func_name" string meta-data in your manifest to use a different
* function.
*/
extern ANativeActivity_createFunc ANativeActivity_onCreate;
/**
* Finish the given activity. Its finish() method will be called, causing it
* to be stopped and destroyed. Note that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place.
*/
void ANativeActivity_finish(ANativeActivity* activity);
/**
* Change the window format of the given activity. Calls getWindow().setFormat()
* of the given activity. Note that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place.
*/
void ANativeActivity_setWindowFormat(ANativeActivity* activity, int32_t format);
/**
* Change the window flags of the given activity. Calls getWindow().setFlags()
* of the given activity. Note that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place. See window.h for flag constants.
*/
void ANativeActivity_setWindowFlags(ANativeActivity* activity,
uint32_t addFlags, uint32_t removeFlags);
/**
* Flags for ANativeActivity_showSoftInput; see the Java InputMethodManager
* API for documentation.
*/
enum {
/**
* Implicit request to show the input window, not as the result
* of a direct request by the user.
*/
ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT = 0x0001,
/**
* The user has forced the input method open (such as by
* long-pressing menu) so it should not be closed until they
* explicitly do so.
*/
ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED = 0x0002,
};
/**
* Show the IME while in the given activity. Calls InputMethodManager.showSoftInput()
* for the given activity. Note that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place.
*/
void ANativeActivity_showSoftInput(ANativeActivity* activity, uint32_t flags);
/**
* Flags for ANativeActivity_hideSoftInput; see the Java InputMethodManager
* API for documentation.
*/
enum {
/**
* The soft input window should only be hidden if it was not
* explicitly shown by the user.
*/
ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY = 0x0001,
/**
* The soft input window should normally be hidden, unless it was
* originally shown with {@link ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED}.
*/
ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS = 0x0002,
};
/**
* Hide the IME while in the given activity. Calls InputMethodManager.hideSoftInput()
* for the given activity. Note that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place.
*/
void ANativeActivity_hideSoftInput(ANativeActivity* activity, uint32_t flags);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_NATIVE_ACTIVITY_H
/** @} */
@@ -0,0 +1,150 @@
/*
* 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.
*/
/**
* @addtogroup NativeActivity Native Activity
* @{
*/
/**
* @file native_window.h
*/
#ifndef ANDROID_NATIVE_WINDOW_H
#define ANDROID_NATIVE_WINDOW_H
#include <android/rect.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Pixel formats that a window can use.
*/
enum {
/** Red: 8 bits, Green: 8 bits, Blue: 8 bits, Alpha: 8 bits. **/
WINDOW_FORMAT_RGBA_8888 = 1,
/** Red: 8 bits, Green: 8 bits, Blue: 8 bits, Unused: 8 bits. **/
WINDOW_FORMAT_RGBX_8888 = 2,
/** Red: 5 bits, Green: 6 bits, Blue: 5 bits. **/
WINDOW_FORMAT_RGB_565 = 4,
};
struct ANativeWindow;
/**
* {@link ANativeWindow} is opaque type that provides access to a native window.
*
* A pointer can be obtained using ANativeWindow_fromSurface().
*/
typedef struct ANativeWindow ANativeWindow;
/**
* {@link ANativeWindow} is a struct that represents a windows buffer.
*
* A pointer can be obtained using ANativeWindow_lock().
*/
typedef struct ANativeWindow_Buffer {
// The number of pixels that are show horizontally.
int32_t width;
// The number of pixels that are shown vertically.
int32_t height;
// The number of *pixels* that a line in the buffer takes in
// memory. This may be >= width.
int32_t stride;
// The format of the buffer. One of WINDOW_FORMAT_*
int32_t format;
// The actual bits.
void* bits;
// Do not touch.
uint32_t reserved[6];
} ANativeWindow_Buffer;
/**
* Acquire a reference on the given ANativeWindow object. This prevents the object
* from being deleted until the reference is removed.
*/
void ANativeWindow_acquire(ANativeWindow* window);
/**
* Remove a reference that was previously acquired with ANativeWindow_acquire().
*/
void ANativeWindow_release(ANativeWindow* window);
/**
* Return the current width in pixels of the window surface. Returns a
* negative value on error.
*/
int32_t ANativeWindow_getWidth(ANativeWindow* window);
/**
* Return the current height in pixels of the window surface. Returns a
* negative value on error.
*/
int32_t ANativeWindow_getHeight(ANativeWindow* window);
/**
* Return the current pixel format of the window surface. Returns a
* negative value on error.
*/
int32_t ANativeWindow_getFormat(ANativeWindow* window);
/**
* Change the format and size of the window buffers.
*
* The width and height control the number of pixels in the buffers, not the
* dimensions of the window on screen. If these are different than the
* window's physical size, then it buffer will be scaled to match that size
* when compositing it to the screen.
*
* For all of these parameters, if 0 is supplied then the window's base
* value will come back in force.
*
* width and height must be either both zero or both non-zero.
*
*/
int32_t ANativeWindow_setBuffersGeometry(ANativeWindow* window,
int32_t width, int32_t height, int32_t format);
/**
* Lock the window's next drawing surface for writing.
* inOutDirtyBounds is used as an in/out parameter, upon entering the
* function, it contains the dirty region, that is, the region the caller
* intends to redraw. When the function returns, inOutDirtyBounds is updated
* with the actual area the caller needs to redraw -- this region is often
* extended by ANativeWindow_lock.
*/
int32_t ANativeWindow_lock(ANativeWindow* window, ANativeWindow_Buffer* outBuffer,
ARect* inOutDirtyBounds);
/**
* Unlock the window's drawing surface after previously locking it,
* posting the new buffer to the display.
*/
int32_t ANativeWindow_unlockAndPost(ANativeWindow* window);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_NATIVE_WINDOW_H
/** @} */
@@ -0,0 +1,51 @@
/*
* 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.
*/
/**
* @addtogroup NativeActivity Native Activity
* @{
*/
/**
* @file native_window_jni.h
*/
#ifndef ANDROID_NATIVE_WINDOW_JNI_H
#define ANDROID_NATIVE_WINDOW_JNI_H
#include <android/native_window.h>
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Return the ANativeWindow associated with a Java Surface object,
* for interacting with it through native code. This acquires a reference
* on the ANativeWindow that is returned; be sure to use ANativeWindow_release()
* when done with it so that it doesn't leak.
*/
ANativeWindow* ANativeWindow_fromSurface(JNIEnv* env, jobject surface);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_NATIVE_WINDOW_H
/** @} */
@@ -0,0 +1,76 @@
/*
* 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.
*/
/**
* @addtogroup Storage
* @{
*/
/**
* @file obb.h
*/
#ifndef ANDROID_OBB_H
#define ANDROID_OBB_H
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
struct AObbInfo;
/** {@link AObbInfo} is an opaque type representing information for obb storage. */
typedef struct AObbInfo AObbInfo;
/** Flag for an obb file, returned by AObbInfo_getFlags(). */
enum {
/** overlay */
AOBBINFO_OVERLAY = 0x0001,
};
/**
* Scan an OBB and get information about it.
*/
AObbInfo* AObbScanner_getObbInfo(const char* filename);
/**
* Destroy the AObbInfo object. You must call this when finished with the object.
*/
void AObbInfo_delete(AObbInfo* obbInfo);
/**
* Get the package name for the OBB.
*/
const char* AObbInfo_getPackageName(AObbInfo* obbInfo);
/**
* Get the version of an OBB file.
*/
int32_t AObbInfo_getVersion(AObbInfo* obbInfo);
/**
* Get the flags of an OBB file.
*/
int32_t AObbInfo_getFlags(AObbInfo* obbInfo);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_OBB_H
/** @} */
@@ -0,0 +1,62 @@
/*
* 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.
*/
/**
* @addtogroup NativeActivity Native Activity
* @{
*/
/**
* @file rect.h
*/
#ifndef ANDROID_RECT_H
#define ANDROID_RECT_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* {@link ARect} is a struct that represents a rectangular window area.
*
* It is used with {@link
* ANativeActivityCallbacks::onContentRectChanged} event callback and
* ANativeWindow_lock() function.
*/
typedef struct ARect {
#ifdef __cplusplus
typedef int32_t value_type;
#endif
/** left position */
int32_t left;
/** top position */
int32_t top;
/** left position */
int32_t right;
/** bottom position */
int32_t bottom;
} ARect;
#ifdef __cplusplus
};
#endif
#endif // ANDROID_RECT_H
/** @} */
@@ -0,0 +1,475 @@
/*
* 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.
*/
/**
* @addtogroup Sensor
* @{
*/
/**
* @file sensor.h
*/
#ifndef ANDROID_SENSOR_H
#define ANDROID_SENSOR_H
/******************************************************************
*
* IMPORTANT NOTICE:
*
* This file is part of Android's set of stable system headers
* exposed by the Android NDK (Native Development Kit).
*
* Third-party source AND binary code relies on the definitions
* here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
*
* - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
* - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
* - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
* - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
*/
/**
* Structures and functions to receive and process sensor events in
* native code.
*
*/
#include <sys/types.h>
#include <android/looper.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Sensor types.
* (keep in sync with hardware/sensor.h)
*/
enum {
/**
* {@link ASENSOR_TYPE_ACCELEROMETER}
* reporting-mode: continuous
*
* All values are in SI units (m/s^2) and measure the acceleration of the
* device minus the force of gravity.
*/
ASENSOR_TYPE_ACCELEROMETER = 1,
/**
* {@link ASENSOR_TYPE_MAGNETIC_FIELD}
* reporting-mode: continuous
*
* All values are in micro-Tesla (uT) and measure the geomagnetic
* field in the X, Y and Z axis.
*/
ASENSOR_TYPE_MAGNETIC_FIELD = 2,
/**
* {@link ASENSOR_TYPE_GYROSCOPE}
* reporting-mode: continuous
*
* All values are in radians/second and measure the rate of rotation
* around the X, Y and Z axis.
*/
ASENSOR_TYPE_GYROSCOPE = 4,
/**
* {@link ASENSOR_TYPE_LIGHT}
* reporting-mode: on-change
*
* The light sensor value is returned in SI lux units.
*/
ASENSOR_TYPE_LIGHT = 5,
/**
* {@link ASENSOR_TYPE_PROXIMITY}
* reporting-mode: on-change
*
* The proximity sensor which turns the screen off and back on during calls is the
* wake-up proximity sensor. Implement wake-up proximity sensor before implementing
* a non wake-up proximity sensor. For the wake-up proximity sensor set the flag
* SENSOR_FLAG_WAKE_UP.
* The value corresponds to the distance to the nearest object in centimeters.
*/
ASENSOR_TYPE_PROXIMITY = 8
};
/**
* Sensor accuracy measure.
*/
enum {
/** no contact */
ASENSOR_STATUS_NO_CONTACT = -1,
/** unreliable */
ASENSOR_STATUS_UNRELIABLE = 0,
/** low accuracy */
ASENSOR_STATUS_ACCURACY_LOW = 1,
/** medium accuracy */
ASENSOR_STATUS_ACCURACY_MEDIUM = 2,
/** high accuracy */
ASENSOR_STATUS_ACCURACY_HIGH = 3
};
/**
* Sensor Reporting Modes.
*/
enum {
/** continuous reporting */
AREPORTING_MODE_CONTINUOUS = 0,
/** reporting on change */
AREPORTING_MODE_ON_CHANGE = 1,
/** on shot reporting */
AREPORTING_MODE_ONE_SHOT = 2,
/** special trigger reporting */
AREPORTING_MODE_SPECIAL_TRIGGER = 3
};
/*
* A few useful constants
*/
/** Earth's gravity in m/s^2 */
#define ASENSOR_STANDARD_GRAVITY (9.80665f)
/** Maximum magnetic field on Earth's surface in uT */
#define ASENSOR_MAGNETIC_FIELD_EARTH_MAX (60.0f)
/** Minimum magnetic field on Earth's surface in uT*/
#define ASENSOR_MAGNETIC_FIELD_EARTH_MIN (30.0f)
/**
* A sensor event.
*/
/* NOTE: Must match hardware/sensors.h */
typedef struct ASensorVector {
union {
float v[3];
struct {
float x;
float y;
float z;
};
struct {
float azimuth;
float pitch;
float roll;
};
};
int8_t status;
uint8_t reserved[3];
} ASensorVector;
typedef struct AMetaDataEvent {
int32_t what;
int32_t sensor;
} AMetaDataEvent;
typedef struct AUncalibratedEvent {
union {
float uncalib[3];
struct {
float x_uncalib;
float y_uncalib;
float z_uncalib;
};
};
union {
float bias[3];
struct {
float x_bias;
float y_bias;
float z_bias;
};
};
} AUncalibratedEvent;
typedef struct AHeartRateEvent {
float bpm;
int8_t status;
} AHeartRateEvent;
/* NOTE: Must match hardware/sensors.h */
typedef struct ASensorEvent {
int32_t version; /* sizeof(struct ASensorEvent) */
int32_t sensor;
int32_t type;
int32_t reserved0;
int64_t timestamp;
union {
union {
float data[16];
ASensorVector vector;
ASensorVector acceleration;
ASensorVector magnetic;
float temperature;
float distance;
float light;
float pressure;
float relative_humidity;
AUncalibratedEvent uncalibrated_gyro;
AUncalibratedEvent uncalibrated_magnetic;
AMetaDataEvent meta_data;
AHeartRateEvent heart_rate;
};
union {
uint64_t data[8];
uint64_t step_counter;
} u64;
};
uint32_t flags;
int32_t reserved1[3];
} ASensorEvent;
struct ASensorManager;
/**
* {@link ASensorManager} is an opaque type to manage sensors and
* events queues.
*
* {@link ASensorManager} is a singleton that can be obtained using
* ASensorManager_getInstance().
*
* This file provides a set of functions that uses {@link
* ASensorManager} to access and list hardware sensors, and
* create and destroy event queues:
* - ASensorManager_getSensorList()
* - ASensorManager_getDefaultSensor()
* - ASensorManager_getDefaultSensorEx()
* - ASensorManager_createEventQueue()
* - ASensorManager_destroyEventQueue()
*/
typedef struct ASensorManager ASensorManager;
struct ASensorEventQueue;
/**
* {@link ASensorEventQueue} is an opaque type that provides access to
* {@link ASensorEvent} from hardware sensors.
*
* A new {@link ASensorEventQueue} can be obtained using ASensorManager_createEventQueue().
*
* This file provides a set of functions to enable and disable
* sensors, check and get events, and set event rates on a {@link
* ASensorEventQueue}.
* - ASensorEventQueue_enableSensor()
* - ASensorEventQueue_disableSensor()
* - ASensorEventQueue_hasEvents()
* - ASensorEventQueue_getEvents()
* - ASensorEventQueue_setEventRate()
*/
typedef struct ASensorEventQueue ASensorEventQueue;
struct ASensor;
/**
* {@link ASensor} is an opaque type that provides information about
* an hardware sensors.
*
* A {@link ASensor} pointer can be obtained using
* ASensorManager_getDefaultSensor(),
* ASensorManager_getDefaultSensorEx() or from a {@link ASensorList}.
*
* This file provides a set of functions to access properties of a
* {@link ASensor}:
* - ASensor_getName()
* - ASensor_getVendor()
* - ASensor_getType()
* - ASensor_getResolution()
* - ASensor_getMinDelay()
* - ASensor_getFifoMaxEventCount()
* - ASensor_getFifoReservedEventCount()
* - ASensor_getStringType()
* - ASensor_getReportingMode()
* - ASensor_isWakeUpSensor()
*/
typedef struct ASensor ASensor;
/**
* {@link ASensorRef} is a type for constant pointers to {@link ASensor}.
*
* This is used to define entry in {@link ASensorList} arrays.
*/
typedef ASensor const* ASensorRef;
/**
* {@link ASensorList} is an array of reference to {@link ASensor}.
*
* A {@link ASensorList} can be initialized using ASensorManager_getSensorList().
*/
typedef ASensorRef const* ASensorList;
/*****************************************************************************/
/**
* Get a reference to the sensor manager. ASensorManager is a singleton
* per package as different packages may have access to different sensors.
*
* Deprecated: Use ASensorManager_getInstanceForPackage(const char*) instead.
*
* Example:
*
* ASensorManager* sensorManager = ASensorManager_getInstance();
*
*/
__attribute__ ((deprecated)) ASensorManager* ASensorManager_getInstance();
/*
* Get a reference to the sensor manager. ASensorManager is a singleton
* per package as different packages may have access to different sensors.
*
* Example:
*
* ASensorManager* sensorManager = ASensorManager_getInstanceForPackage("foo.bar.baz");
*
*/
ASensorManager* ASensorManager_getInstanceForPackage(const char* packageName);
/**
* Returns the list of available sensors.
*/
int ASensorManager_getSensorList(ASensorManager* manager, ASensorList* list);
/**
* Returns the default sensor for the given type, or NULL if no sensor
* of that type exists.
*/
ASensor const* ASensorManager_getDefaultSensor(ASensorManager* manager, int type);
/**
* Returns the default sensor with the given type and wakeUp properties or NULL if no sensor
* of this type and wakeUp properties exists.
*/
ASensor const* ASensorManager_getDefaultSensorEx(ASensorManager* manager, int type,
bool wakeUp);
/**
* Creates a new sensor event queue and associate it with a looper.
*
* "ident" is a identifier for the events that will be returned when
* calling ALooper_pollOnce(). The identifier must be >= 0, or
* ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
*/
ASensorEventQueue* ASensorManager_createEventQueue(ASensorManager* manager,
ALooper* looper, int ident, ALooper_callbackFunc callback, void* data);
/**
* Destroys the event queue and free all resources associated to it.
*/
int ASensorManager_destroyEventQueue(ASensorManager* manager, ASensorEventQueue* queue);
/*****************************************************************************/
/**
* Enable the selected sensor. Returns a negative error code on failure.
*/
int ASensorEventQueue_enableSensor(ASensorEventQueue* queue, ASensor const* sensor);
/**
* Disable the selected sensor. Returns a negative error code on failure.
*/
int ASensorEventQueue_disableSensor(ASensorEventQueue* queue, ASensor const* sensor);
/**
* Sets the delivery rate of events in microseconds for the given sensor.
* Note that this is a hint only, generally event will arrive at a higher
* rate. It is an error to set a rate inferior to the value returned by
* ASensor_getMinDelay().
* Returns a negative error code on failure.
*/
int ASensorEventQueue_setEventRate(ASensorEventQueue* queue, ASensor const* sensor, int32_t usec);
/**
* Returns true if there are one or more events available in the
* sensor queue. Returns 1 if the queue has events; 0 if
* it does not have events; and a negative value if there is an error.
*/
int ASensorEventQueue_hasEvents(ASensorEventQueue* queue);
/**
* Returns the next available events from the queue. Returns a negative
* value if no events are available or an error has occurred, otherwise
* the number of events returned.
*
* Examples:
* ASensorEvent event;
* ssize_t numEvent = ASensorEventQueue_getEvents(queue, &event, 1);
*
* ASensorEvent eventBuffer[8];
* ssize_t numEvent = ASensorEventQueue_getEvents(queue, eventBuffer, 8);
*
*/
ssize_t ASensorEventQueue_getEvents(ASensorEventQueue* queue,
ASensorEvent* events, size_t count);
/*****************************************************************************/
/**
* Returns this sensor's name (non localized)
*/
const char* ASensor_getName(ASensor const* sensor);
/**
* Returns this sensor's vendor's name (non localized)
*/
const char* ASensor_getVendor(ASensor const* sensor);
/**
* Return this sensor's type
*/
int ASensor_getType(ASensor const* sensor);
/**
* Returns this sensors's resolution
*/
float ASensor_getResolution(ASensor const* sensor);
/**
* Returns the minimum delay allowed between events in microseconds.
* A value of zero means that this sensor doesn't report events at a
* constant rate, but rather only when a new data is available.
*/
int ASensor_getMinDelay(ASensor const* sensor);
/**
* Returns the maximum size of batches for this sensor. Batches will often be
* smaller, as the hardware fifo might be used for other sensors.
*/
int ASensor_getFifoMaxEventCount(ASensor const* sensor);
/**
* Returns the hardware batch fifo size reserved to this sensor.
*/
int ASensor_getFifoReservedEventCount(ASensor const* sensor);
/**
* Returns this sensor's string type.
*/
const char* ASensor_getStringType(ASensor const* sensor);
/**
* Returns the reporting mode for this sensor. One of AREPORTING_MODE_* constants.
*/
int ASensor_getReportingMode(ASensor const* sensor);
/**
* Returns true if this is a wake up sensor, false otherwise.
*/
bool ASensor_isWakeUpSensor(ASensor const* sensor);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_SENSOR_H
/** @} */
@@ -0,0 +1,154 @@
/*
* 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.
*/
/**
* @addtogroup Storage
* @{
*/
/**
* @file storage_manager.h
*/
#ifndef ANDROID_STORAGE_MANAGER_H
#define ANDROID_STORAGE_MANAGER_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct AStorageManager;
/**
* {@link AStorageManager} manages application OBB storage, a pointer
* can be obtained with AStorageManager_new().
*/
typedef struct AStorageManager AStorageManager;
/**
* The different states of a OBB storage passed to AStorageManager_obbCallbackFunc().
*/
enum {
/**
* The OBB container is now mounted and ready for use. Can be returned
* as the status for callbacks made during asynchronous OBB actions.
*/
AOBB_STATE_MOUNTED = 1,
/**
* The OBB container is now unmounted and not usable. Can be returned
* as the status for callbacks made during asynchronous OBB actions.
*/
AOBB_STATE_UNMOUNTED = 2,
/**
* There was an internal system error encountered while trying to
* mount the OBB. Can be returned as the status for callbacks made
* during asynchronous OBB actions.
*/
AOBB_STATE_ERROR_INTERNAL = 20,
/**
* The OBB could not be mounted by the system. Can be returned as the
* status for callbacks made during asynchronous OBB actions.
*/
AOBB_STATE_ERROR_COULD_NOT_MOUNT = 21,
/**
* The OBB could not be unmounted. This most likely indicates that a
* file is in use on the OBB. Can be returned as the status for
* callbacks made during asynchronous OBB actions.
*/
AOBB_STATE_ERROR_COULD_NOT_UNMOUNT = 22,
/**
* A call was made to unmount the OBB when it was not mounted. Can be
* returned as the status for callbacks made during asynchronous OBB
* actions.
*/
AOBB_STATE_ERROR_NOT_MOUNTED = 23,
/**
* The OBB has already been mounted. Can be returned as the status for
* callbacks made during asynchronous OBB actions.
*/
AOBB_STATE_ERROR_ALREADY_MOUNTED = 24,
/**
* The current application does not have permission to use this OBB.
* This could be because the OBB indicates it's owned by a different
* package. Can be returned as the status for callbacks made during
* asynchronous OBB actions.
*/
AOBB_STATE_ERROR_PERMISSION_DENIED = 25,
};
/**
* Obtains a new instance of AStorageManager.
*/
AStorageManager* AStorageManager_new();
/**
* Release AStorageManager instance.
*/
void AStorageManager_delete(AStorageManager* mgr);
/**
* Callback function for asynchronous calls made on OBB files.
*
* "state" is one of the following constants:
* - {@link AOBB_STATE_MOUNTED}
* - {@link AOBB_STATE_UNMOUNTED}
* - {@link AOBB_STATE_ERROR_INTERNAL}
* - {@link AOBB_STATE_ERROR_COULD_NOT_MOUNT}
* - {@link AOBB_STATE_ERROR_COULD_NOT_UNMOUNT}
* - {@link AOBB_STATE_ERROR_NOT_MOUNTED}
* - {@link AOBB_STATE_ERROR_ALREADY_MOUNTED}
* - {@link AOBB_STATE_ERROR_PERMISSION_DENIED}
*/
typedef void (*AStorageManager_obbCallbackFunc)(const char* filename, const int32_t state, void* data);
/**
* Attempts to mount an OBB file. This is an asynchronous operation.
*/
void AStorageManager_mountObb(AStorageManager* mgr, const char* filename, const char* key,
AStorageManager_obbCallbackFunc cb, void* data);
/**
* Attempts to unmount an OBB file. This is an asynchronous operation.
*/
void AStorageManager_unmountObb(AStorageManager* mgr, const char* filename, const int force,
AStorageManager_obbCallbackFunc cb, void* data);
/**
* Check whether an OBB is mounted.
*/
int AStorageManager_isObbMounted(AStorageManager* mgr, const char* filename);
/**
* Get the mounted path for an OBB.
*/
const char* AStorageManager_getMountedObbPath(AStorageManager* mgr, const char* filename);
#ifdef __cplusplus
};
#endif
#endif // ANDROID_STORAGE_MANAGER_H
/** @} */
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2015 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_NATIVE_TRACE_H
#define ANDROID_NATIVE_TRACE_H
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Returns true if tracing is enabled. Use this signal to avoid expensive computation only necessary
* when tracing is enabled.
*/
bool ATrace_isEnabled();
/**
* Writes a tracing message to indicate that the given section of code has begun. This call must be
* followed by a corresponding call to endSection() on the same thread.
*
* Note: At this time the vertical bar character '|' and newline character '\n' are used internally
* by the tracing mechanism. If sectionName contains these characters they will be replaced with a
* space character in the trace.
*/
void ATrace_beginSection(const char* sectionName);
/**
* Writes a tracing message to indicate that a given section of code has ended. This call must be
* preceeded by a corresponding call to beginSection(char*) on the same thread. Calling this method
* will mark the end of the most recently begun section of code, so care must be taken to ensure
* that beginSection / endSection pairs are properly nested and called from the same thread.
*/
void ATrace_endSection();
#ifdef __cplusplus
};
#endif
#endif // ANDROID_NATIVE_TRACE_H
@@ -0,0 +1,224 @@
/*
* 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.
*/
/**
* @addtogroup NativeActivity Native Activity
* @{
*/
/**
* @file window.h
*/
#ifndef ANDROID_WINDOW_H
#define ANDROID_WINDOW_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* Window flags, as per the Java API at android.view.WindowManager.LayoutParams.
*/
enum {
/**
* As long as this window is visible to the user, allow the lock
* screen to activate while the screen is on. This can be used
* independently, or in combination with {@link
* AWINDOW_FLAG_KEEP_SCREEN_ON} and/or {@link
* AWINDOW_FLAG_SHOW_WHEN_LOCKED}
*/
AWINDOW_FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
/** Everything behind this window will be dimmed. */
AWINDOW_FLAG_DIM_BEHIND = 0x00000002,
/**
* Blur everything behind this window.
* @deprecated Blurring is no longer supported.
*/
AWINDOW_FLAG_BLUR_BEHIND = 0x00000004,
/**
* This window won't ever get key input focus, so the
* user can not send key or other button events to it. Those will
* instead go to whatever focusable window is behind it. This flag
* will also enable {@link AWINDOW_FLAG_NOT_TOUCH_MODAL} whether or not that
* is explicitly set.
*
* Setting this flag also implies that the window will not need to
* interact with
* a soft input method, so it will be Z-ordered and positioned
* independently of any active input method (typically this means it
* gets Z-ordered on top of the input method, so it can use the full
* screen for its content and cover the input method if needed. You
* can use {@link AWINDOW_FLAG_ALT_FOCUSABLE_IM} to modify this behavior.
*/
AWINDOW_FLAG_NOT_FOCUSABLE = 0x00000008,
/** this window can never receive touch events. */
AWINDOW_FLAG_NOT_TOUCHABLE = 0x00000010,
/**
* Even when this window is focusable (its
* {@link AWINDOW_FLAG_NOT_FOCUSABLE} is not set), allow any pointer events
* outside of the window to be sent to the windows behind it. Otherwise
* it will consume all pointer events itself, regardless of whether they
* are inside of the window.
*/
AWINDOW_FLAG_NOT_TOUCH_MODAL = 0x00000020,
/**
* When set, if the device is asleep when the touch
* screen is pressed, you will receive this first touch event. Usually
* the first touch event is consumed by the system since the user can
* not see what they are pressing on.
*
* @deprecated This flag has no effect.
*/
AWINDOW_FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
/**
* As long as this window is visible to the user, keep
* the device's screen turned on and bright.
*/
AWINDOW_FLAG_KEEP_SCREEN_ON = 0x00000080,
/**
* Place the window within the entire screen, ignoring
* decorations around the border (such as the status bar). The
* window must correctly position its contents to take the screen
* decoration into account.
*/
AWINDOW_FLAG_LAYOUT_IN_SCREEN = 0x00000100,
/** allow window to extend outside of the screen. */
AWINDOW_FLAG_LAYOUT_NO_LIMITS = 0x00000200,
/**
* Hide all screen decorations (such as the status
* bar) while this window is displayed. This allows the window to
* use the entire display space for itself -- the status bar will
* be hidden when an app window with this flag set is on the top
* layer. A fullscreen window will ignore a value of {@link
* AWINDOW_SOFT_INPUT_ADJUST_RESIZE}; the window will stay
* fullscreen and will not resize.
*/
AWINDOW_FLAG_FULLSCREEN = 0x00000400,
/**
* Override {@link AWINDOW_FLAG_FULLSCREEN} and force the
* screen decorations (such as the status bar) to be shown.
*/
AWINDOW_FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
/**
* Turn on dithering when compositing this window to
* the screen.
* @deprecated This flag is no longer used.
*/
AWINDOW_FLAG_DITHER = 0x00001000,
/**
* Treat the content of the window as secure, preventing
* it from appearing in screenshots or from being viewed on non-secure
* displays.
*/
AWINDOW_FLAG_SECURE = 0x00002000,
/**
* A special mode where the layout parameters are used
* to perform scaling of the surface when it is composited to the
* screen.
*/
AWINDOW_FLAG_SCALED = 0x00004000,
/**
* Intended for windows that will often be used when the user is
* holding the screen against their face, it will aggressively
* filter the event stream to prevent unintended presses in this
* situation that may not be desired for a particular window, when
* such an event stream is detected, the application will receive
* a {@link AMOTION_EVENT_ACTION_CANCEL} to indicate this so
* applications can handle this accordingly by taking no action on
* the event until the finger is released.
*/
AWINDOW_FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
/**
* A special option only for use in combination with
* {@link AWINDOW_FLAG_LAYOUT_IN_SCREEN}. When requesting layout in the
* screen your window may appear on top of or behind screen decorations
* such as the status bar. By also including this flag, the window
* manager will report the inset rectangle needed to ensure your
* content is not covered by screen decorations.
*/
AWINDOW_FLAG_LAYOUT_INSET_DECOR = 0x00010000,
/**
* Invert the state of {@link AWINDOW_FLAG_NOT_FOCUSABLE} with
* respect to how this window interacts with the current method.
* That is, if FLAG_NOT_FOCUSABLE is set and this flag is set,
* then the window will behave as if it needs to interact with the
* input method and thus be placed behind/away from it; if {@link
* AWINDOW_FLAG_NOT_FOCUSABLE} is not set and this flag is set,
* then the window will behave as if it doesn't need to interact
* with the input method and can be placed to use more space and
* cover the input method.
*/
AWINDOW_FLAG_ALT_FOCUSABLE_IM = 0x00020000,
/**
* If you have set {@link AWINDOW_FLAG_NOT_TOUCH_MODAL}, you
* can set this flag to receive a single special MotionEvent with
* the action
* {@link AMOTION_EVENT_ACTION_OUTSIDE} for
* touches that occur outside of your window. Note that you will not
* receive the full down/move/up gesture, only the location of the
* first down as an {@link AMOTION_EVENT_ACTION_OUTSIDE}.
*/
AWINDOW_FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
/**
* Special flag to let windows be shown when the screen
* is locked. This will let application windows take precedence over
* key guard or any other lock screens. Can be used with
* {@link AWINDOW_FLAG_KEEP_SCREEN_ON} to turn screen on and display windows
* directly before showing the key guard window. Can be used with
* {@link AWINDOW_FLAG_DISMISS_KEYGUARD} to automatically fully dismisss
* non-secure keyguards. This flag only applies to the top-most
* full-screen window.
*/
AWINDOW_FLAG_SHOW_WHEN_LOCKED = 0x00080000,
/**
* Ask that the system wallpaper be shown behind
* your window. The window surface must be translucent to be able
* to actually see the wallpaper behind it; this flag just ensures
* that the wallpaper surface will be there if this window actually
* has translucent regions.
*/
AWINDOW_FLAG_SHOW_WALLPAPER = 0x00100000,
/**
* When set as a window is being added or made
* visible, once the window has been shown then the system will
* poke the power manager's user activity (as if the user had woken
* up the device) to turn the screen on.
*/
AWINDOW_FLAG_TURN_SCREEN_ON = 0x00200000,
/**
* When set the window will cause the keyguard to
* be dismissed, only if it is not a secure lock keyguard. Because such
* a keyguard is not needed for security, it will never re-appear if
* the user navigates to another window (in contrast to
* {@link AWINDOW_FLAG_SHOW_WHEN_LOCKED}, which will only temporarily
* hide both secure and non-secure keyguards but ensure they reappear
* when the user moves to another UI that doesn't hide them).
* If the keyguard is currently active and is secure (requires an
* unlock pattern) than the user will still need to confirm it before
* seeing this window, unless {@link AWINDOW_FLAG_SHOW_WHEN_LOCKED} has
* also been set.
*/
AWINDOW_FLAG_DISMISS_KEYGUARD = 0x00400000,
};
#ifdef __cplusplus
};
#endif
#endif // ANDROID_WINDOW_H
/** @} */
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2013 The Android Open Source Project
* Copyright (C) 2015 The CyanogenMod 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_BATTERYSERVICE_H
#define ANDROID_BATTERYSERVICE_H
#include <binder/Parcel.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/String8.h>
namespace android {
// must be kept in sync with definitions in BatteryManager.java
enum {
BATTERY_STATUS_UNKNOWN = 1, // equals BatteryManager.BATTERY_STATUS_UNKNOWN constant
BATTERY_STATUS_CHARGING = 2, // equals BatteryManager.BATTERY_STATUS_CHARGING constant
BATTERY_STATUS_DISCHARGING = 3, // equals BatteryManager.BATTERY_STATUS_DISCHARGING constant
BATTERY_STATUS_NOT_CHARGING = 4, // equals BatteryManager.BATTERY_STATUS_NOT_CHARGING constant
BATTERY_STATUS_FULL = 5, // equals BatteryManager.BATTERY_STATUS_FULL constant
};
// must be kept in sync with definitions in BatteryManager.java
enum {
BATTERY_HEALTH_UNKNOWN = 1, // equals BatteryManager.BATTERY_HEALTH_UNKNOWN constant
BATTERY_HEALTH_GOOD = 2, // equals BatteryManager.BATTERY_HEALTH_GOOD constant
BATTERY_HEALTH_OVERHEAT = 3, // equals BatteryManager.BATTERY_HEALTH_OVERHEAT constant
BATTERY_HEALTH_DEAD = 4, // equals BatteryManager.BATTERY_HEALTH_DEAD constant
BATTERY_HEALTH_OVER_VOLTAGE = 5, // equals BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE constant
BATTERY_HEALTH_UNSPECIFIED_FAILURE = 6, // equals BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE constant
BATTERY_HEALTH_COLD = 7, // equals BatteryManager.BATTERY_HEALTH_COLD constant
};
// must be kept in sync with definitions in BatteryProperty.java
enum {
BATTERY_PROP_CHARGE_COUNTER = 1, // equals BatteryProperty.CHARGE_COUNTER constant
BATTERY_PROP_CURRENT_NOW = 2, // equals BatteryProperty.CURRENT_NOW constant
BATTERY_PROP_CURRENT_AVG = 3, // equals BatteryProperty.CURRENT_AVG constant
BATTERY_PROP_CAPACITY = 4, // equals BatteryProperty.CAPACITY constant
BATTERY_PROP_ENERGY_COUNTER = 5, // equals BatteryProperty.ENERGY_COUNTER constant
};
struct BatteryProperties {
bool chargerAcOnline;
bool chargerUsbOnline;
bool chargerWirelessOnline;
int maxChargingCurrent;
int batteryStatus;
int batteryHealth;
bool batteryPresent;
int batteryLevel;
int batteryVoltage;
int batteryTemperature;
String8 batteryTechnology;
bool dockBatterySupported;
bool chargerDockAcOnline;
int dockBatteryStatus;
int dockBatteryHealth;
bool dockBatteryPresent;
int dockBatteryLevel;
int dockBatteryVoltage;
int dockBatteryTemperature;
String8 dockBatteryTechnology;
status_t writeToParcel(Parcel* parcel) const;
status_t readFromParcel(Parcel* parcel);
};
struct BatteryProperty {
int64_t valueInt64;
status_t writeToParcel(Parcel* parcel) const;
status_t readFromParcel(Parcel* parcel);
};
}; // namespace android
#endif // ANDROID_BATTERYSERVICE_H
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2013 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_IBATTERYPROPERTIESLISTENER_H
#define ANDROID_IBATTERYPROPERTIESLISTENER_H
#include <binder/IBinder.h>
#include <binder/IInterface.h>
#include <batteryservice/BatteryService.h>
namespace android {
// must be kept in sync with interface defined in IBatteryPropertiesListener.aidl
enum {
TRANSACT_BATTERYPROPERTIESCHANGED = IBinder::FIRST_CALL_TRANSACTION,
};
// ----------------------------------------------------------------------------
class IBatteryPropertiesListener : public IInterface {
public:
DECLARE_META_INTERFACE(BatteryPropertiesListener);
virtual void batteryPropertiesChanged(struct BatteryProperties props) = 0;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IBATTERYPROPERTIESLISTENER_H
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2013 The Android Open Source Project
* Copyright (C) 2015 The CyanogenMod 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_IBATTERYPROPERTIESREGISTRAR_H
#define ANDROID_IBATTERYPROPERTIESREGISTRAR_H
#include <binder/IInterface.h>
#include <batteryservice/IBatteryPropertiesListener.h>
namespace android {
// must be kept in sync with interface defined in IBatteryPropertiesRegistrar.aidl
enum {
REGISTER_LISTENER = IBinder::FIRST_CALL_TRANSACTION,
UNREGISTER_LISTENER,
GET_PROPERTY,
GET_DOCK_PROPERTY,
};
class IBatteryPropertiesRegistrar : public IInterface {
public:
DECLARE_META_INTERFACE(BatteryPropertiesRegistrar);
virtual void registerListener(const sp<IBatteryPropertiesListener>& listener) = 0;
virtual void unregisterListener(const sp<IBatteryPropertiesListener>& listener) = 0;
virtual status_t getProperty(int id, struct BatteryProperty *val) = 0;
virtual status_t getDockProperty(int id, struct BatteryProperty *val) = 0;
};
class BnBatteryPropertiesRegistrar : public BnInterface<IBatteryPropertiesRegistrar> {
public:
virtual status_t onTransact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0);
};
}; // namespace android
#endif // ANDROID_IBATTERYPROPERTIESREGISTRAR_H
@@ -0,0 +1,130 @@
/*
* Copyright (C) 2013 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_OPS_MANAGER_H
#define ANDROID_APP_OPS_MANAGER_H
#include <binder/IAppOpsService.h>
#include <utils/threads.h>
// ---------------------------------------------------------------------------
namespace android {
class AppOpsManager
{
public:
enum {
MODE_ALLOWED = IAppOpsService::MODE_ALLOWED,
MODE_IGNORED = IAppOpsService::MODE_IGNORED,
MODE_ERRORED = IAppOpsService::MODE_ERRORED
};
enum {
OP_NONE = -1,
OP_COARSE_LOCATION = 0,
OP_FINE_LOCATION = 1,
OP_GPS = 2,
OP_VIBRATE = 3,
OP_READ_CONTACTS = 4,
OP_WRITE_CONTACTS = 5,
OP_READ_CALL_LOG = 6,
OP_WRITE_CALL_LOG = 7,
OP_READ_CALENDAR = 8,
OP_WRITE_CALENDAR = 9,
OP_WIFI_SCAN = 10,
OP_POST_NOTIFICATION = 11,
OP_NEIGHBORING_CELLS = 12,
OP_CALL_PHONE = 13,
OP_READ_SMS = 14,
OP_WRITE_SMS = 15,
OP_RECEIVE_SMS = 16,
OP_RECEIVE_EMERGECY_SMS = 17,
OP_RECEIVE_MMS = 18,
OP_RECEIVE_WAP_PUSH = 19,
OP_SEND_SMS = 20,
OP_READ_ICC_SMS = 21,
OP_WRITE_ICC_SMS = 22,
OP_WRITE_SETTINGS = 23,
OP_SYSTEM_ALERT_WINDOW = 24,
OP_ACCESS_NOTIFICATIONS = 25,
OP_CAMERA = 26,
OP_RECORD_AUDIO = 27,
OP_PLAY_AUDIO = 28,
OP_READ_CLIPBOARD = 29,
OP_WRITE_CLIPBOARD = 30,
OP_TAKE_MEDIA_BUTTONS = 31,
OP_TAKE_AUDIO_FOCUS = 32,
OP_AUDIO_MASTER_VOLUME = 33,
OP_AUDIO_VOICE_VOLUME = 34,
OP_AUDIO_RING_VOLUME = 35,
OP_AUDIO_MEDIA_VOLUME = 36,
OP_AUDIO_ALARM_VOLUME = 37,
OP_AUDIO_NOTIFICATION_VOLUME = 38,
OP_AUDIO_BLUETOOTH_VOLUME = 39,
OP_WAKE_LOCK = 40,
OP_MONITOR_LOCATION = 41,
OP_MONITOR_HIGH_POWER_LOCATION = 42,
OP_GET_USAGE_STATS = 43,
OP_MUTE_MICROPHONE = 44,
OP_TOAST_WINDOW = 45,
OP_PROJECT_MEDIA = 46,
OP_ACTIVATE_VPN = 47,
OP_WRITE_WALLPAPER = 48,
OP_ASSIST_STRUCTURE = 49,
OP_ASSIST_SCREENSHOT = 50,
OP_READ_PHONE_STATE = 51,
OP_ADD_VOICEMAIL = 52,
OP_USE_SIP = 53,
OP_PROCESS_OUTGOING_CALLS = 54,
OP_USE_FINGERPRINT = 55,
OP_BODY_SENSORS = 56,
OP_READ_CELL_BROADCASTS = 57,
OP_MOCK_LOCATION = 58,
OP_READ_EXTERNAL_STORAGE = 59,
OP_WRITE_EXTERNAL_STORAGE = 60,
OP_TURN_SCREEN_ON = 61,
OP_GET_ACCOUNTS = 62,
OP_WIFI_CHANGE = 63,
OP_BLUETOOTH_CHANGE = 64,
OP_BOOT_COMPLETED = 65,
OP_NFC_CHANGE = 66,
OP_DATA_CONNECT_CHANGE = 67,
OP_SU = 68
};
AppOpsManager();
int32_t checkOp(int32_t op, int32_t uid, const String16& callingPackage);
int32_t noteOp(int32_t op, int32_t uid, const String16& callingPackage);
int32_t startOp(int32_t op, int32_t uid, const String16& callingPackage);
void finishOp(int32_t op, int32_t uid, const String16& callingPackage);
void startWatchingMode(int32_t op, const String16& packageName,
const sp<IAppOpsCallback>& callback);
void stopWatchingMode(const sp<IAppOpsCallback>& callback);
int32_t permissionToOpCode(const String16& permission);
private:
Mutex mLock;
sp<IAppOpsService> mService;
sp<IAppOpsService> getService();
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_APP_OPS_MANAGER_H
@@ -0,0 +1,105 @@
/*
* 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 <stdatomic.h>
#include <stdint.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;
atomic_uintptr_t mExtras; // should be atomic<Extras *>
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
@@ -0,0 +1,65 @@
/*
* 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(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}
static void publishAndJoinThreadPool(bool allowIsolated = false) {
publish(allowIsolated);
joinThreadPool();
}
static void instantiate() { publish(); }
static status_t shutdown() { return NO_ERROR; }
private:
static void joinThreadPool() {
sp<ProcessState> ps(ProcessState::self());
ps->startThreadPool();
ps->giveThreadPoolName();
IPCThreadState::self()->joinThreadPool();
}
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_BINDER_SERVICE_H
@@ -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
@@ -0,0 +1,67 @@
/*
* Copyright (C) 2006 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_BUFFEREDTEXTOUTPUT_H
#define ANDROID_BUFFEREDTEXTOUTPUT_H
#include <binder/TextOutput.h>
#include <utils/threads.h>
#include <sys/uio.h>
// ---------------------------------------------------------------------------
namespace android {
class BufferedTextOutput : public TextOutput
{
public:
//** Flags for constructor */
enum {
MULTITHREADED = 0x0001
};
BufferedTextOutput(uint32_t flags = 0);
virtual ~BufferedTextOutput();
virtual status_t print(const char* txt, size_t len);
virtual void moveIndent(int delta);
virtual void pushBundle();
virtual void popBundle();
protected:
virtual status_t writeLines(const struct iovec& vec, size_t N) = 0;
private:
struct BufferState;
struct ThreadState;
static ThreadState*getThreadState();
static void threadDestructor(void *st);
BufferState*getBuffer() const;
uint32_t mFlags;
const int32_t mSeq;
const int32_t mIndex;
Mutex mLock;
BufferState* mGlobalState;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_BUFFEREDTEXTOUTPUT_H
@@ -0,0 +1,49 @@
/*
* 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_BINDER_DEBUG_H
#define ANDROID_BINDER_DEBUG_H
#include <stdint.h>
#include <sys/types.h>
namespace android {
// ---------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
const char* stringForIndent(int32_t indentLevel);
typedef void (*debugPrintFunc)(void* cookie, const char* txt);
void printTypeCode(uint32_t typeCode,
debugPrintFunc func = 0, void* cookie = 0);
void printHexData(int32_t indent, const void *buf, size_t length,
size_t bytesPerLine=16, int32_t singleLineBytesCutoff=16,
size_t alignment=0, bool cArrayStyle=false,
debugPrintFunc func = 0, void* cookie = 0);
#ifdef __cplusplus
}
#endif
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_BINDER_DEBUG_H
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2013 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_IAPP_OPS_CALLBACK_H
#define ANDROID_IAPP_OPS_CALLBACK_H
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------
class IAppOpsCallback : public IInterface
{
public:
DECLARE_META_INTERFACE(AppOpsCallback);
virtual void opChanged(int32_t op, const String16& packageName) = 0;
enum {
OP_CHANGED_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION
};
};
// ----------------------------------------------------------------------
class BnAppOpsCallback : public BnInterface<IAppOpsCallback>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IAPP_OPS_CALLBACK_H
@@ -0,0 +1,78 @@
/*
* Copyright (C) 2013 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_IAPP_OPS_SERVICE_H
#define ANDROID_IAPP_OPS_SERVICE_H
#include <binder/IAppOpsCallback.h>
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------
class IAppOpsService : public IInterface
{
public:
DECLARE_META_INTERFACE(AppOpsService);
virtual int32_t checkOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
virtual int32_t noteOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
virtual int32_t startOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
const String16& packageName) = 0;
virtual void finishOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
const String16& packageName) = 0;
virtual void startWatchingMode(int32_t op, const String16& packageName,
const sp<IAppOpsCallback>& callback) = 0;
virtual void stopWatchingMode(const sp<IAppOpsCallback>& callback) = 0;
virtual sp<IBinder> getToken(const sp<IBinder>& clientToken) = 0;
virtual int32_t permissionToOpCode(const String16& permission) = 0;
enum {
CHECK_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
NOTE_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+1,
START_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+2,
FINISH_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+3,
START_WATCHING_MODE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+4,
STOP_WATCHING_MODE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+5,
GET_TOKEN_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+6,
PERMISSION_TO_OP_CODE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+7,
};
enum {
MODE_ALLOWED = 0,
MODE_IGNORED = 1,
MODE_ERRORED = 2
};
};
// ----------------------------------------------------------------------
class BnAppOpsService : public BnInterface<IAppOpsService>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IAPP_OPS_SERVICE_H
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2013 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_IBATTERYSTATS_H
#define ANDROID_IBATTERYSTATS_H
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------
class IBatteryStats : public IInterface
{
public:
DECLARE_META_INTERFACE(BatteryStats);
virtual void noteStartSensor(int uid, int sensor) = 0;
virtual void noteStopSensor(int uid, int sensor) = 0;
virtual void noteStartVideo(int uid) = 0;
virtual void noteStopVideo(int uid) = 0;
virtual void noteStartAudio(int uid) = 0;
virtual void noteStopAudio(int uid) = 0;
virtual void noteResetVideo() = 0;
virtual void noteResetAudio() = 0;
virtual void noteFlashlightOn(int uid) = 0;
virtual void noteFlashlightOff(int uid) = 0;
virtual void noteStartCamera(int uid) = 0;
virtual void noteStopCamera(int uid) = 0;
virtual void noteResetCamera() = 0;
virtual void noteResetFlashlight() = 0;
enum {
NOTE_START_SENSOR_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
NOTE_STOP_SENSOR_TRANSACTION,
NOTE_START_VIDEO_TRANSACTION,
NOTE_STOP_VIDEO_TRANSACTION,
NOTE_START_AUDIO_TRANSACTION,
NOTE_STOP_AUDIO_TRANSACTION,
NOTE_RESET_VIDEO_TRANSACTION,
NOTE_RESET_AUDIO_TRANSACTION,
NOTE_FLASHLIGHT_ON_TRANSACTION,
NOTE_FLASHLIGHT_OFF_TRANSACTION,
NOTE_START_CAMERA_TRANSACTION,
NOTE_STOP_CAMERA_TRANSACTION,
NOTE_RESET_CAMERA_TRANSACTION,
NOTE_RESET_FLASHLIGHT_TRANSACTION
};
};
// ----------------------------------------------------------------------
class BnBatteryStats : public BnInterface<IBatteryStats>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IBATTERYSTATS_H
@@ -0,0 +1,152 @@
/*
* 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'),
SYSPROPS_TRANSACTION = B_PACK_CHARS('_', 'S', 'P', 'R'),
// 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;
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 reference
* 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
@@ -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();
static sp<IBinder> asBinder(const IInterface*);
static sp<IBinder> asBinder(const sp<IInterface>&);
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
@@ -0,0 +1,107 @@
/*
* 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,
#ifdef USE_MEMORY_HEAP_ION
USE_ION_FD = 0x00008000
#else
USE_ION_FD = 0x00000008
#endif
};
virtual int getHeapID() const = 0;
virtual void* getBase() const = 0;
virtual size_t getSize() const = 0;
virtual uint32_t getFlags() const = 0;
virtual uint32_t getOffset() 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
@@ -0,0 +1,135 @@
/*
* 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>
#if defined(_WIN32)
typedef int uid_t;
#endif
// ---------------------------------------------------------------------------
namespace android {
class IPCThreadState
{
public:
static IPCThreadState* self();
static IPCThreadState* selfOrNull(); // self(), but won't instantiate
sp<ProcessState> process();
status_t clearLastError();
pid_t getCallingPid() const;
uid_t getCallingUid() const;
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);
int setupPolling(int* fd);
status_t handlePolledCommands();
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);
// Call blocks until the number of executing binder threads is less than
// the maximum number of binder threads threads allowed for this process.
void blockUntilThreadAvailable();
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 getAndExecuteCommand();
status_t executeCommand(int32_t command);
void processPendingDerefs();
void clearCaller();
static void threadDestructor(void *st);
static void freeBuffer(Parcel* parcel,
const uint8_t* data, size_t dataSize,
const binder_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,62 @@
/*
* 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>
#include <stdlib.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;
virtual void getPackagesForUid(const uid_t uid, Vector<String16> &packages) = 0;
virtual bool isRuntimePermission(const String16& permission) = 0;
enum {
CHECK_PERMISSION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
GET_PACKAGES_FOR_UID_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION + 1,
IS_RUNTIME_PERMISSION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION + 2
};
};
// ----------------------------------------------------------------------
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
@@ -0,0 +1,53 @@
/*
* Copyright 2015 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_I_PROCESS_INFO_SERVICE_H
#define ANDROID_I_PROCESS_INFO_SERVICE_H
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------
class IProcessInfoService : public IInterface {
public:
DECLARE_META_INTERFACE(ProcessInfoService);
virtual status_t getProcessStatesFromPids( size_t length,
/*in*/ int32_t* pids,
/*out*/ int32_t* states) = 0;
enum {
GET_PROCESS_STATES_FROM_PIDS = IBinder::FIRST_CALL_TRANSACTION,
};
};
// ----------------------------------------------------------------------
class BnProcessInfoService : public BnInterface<IProcessInfoService> {
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_I_PROCESS_INFO_SERVICE_H
@@ -0,0 +1,101 @@
/*
* 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,
bool allowIsolated = false) = 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
@@ -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
@@ -0,0 +1,61 @@
/*
* 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,
uint32_t flags = 0 /* or bits such as MemoryHeapBase::READ_ONLY */ );
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
@@ -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_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
};
/*
* 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 address of the heap. returns MAP_FAILED in case of error */
virtual void* getBase() const;
virtual size_t getSize() const;
virtual uint32_t getFlags() const;
virtual uint32_t getOffset() 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;
uint32_t mOffset;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_HEAP_BASE_H
@@ -0,0 +1,68 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* Copyright 2011, Samsung Electronics Co. LTD
*
* 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.
*/
/*!
* \file MemoryHeapIon.h
* \brief header file for MemoryHeapIon
* \author MinGu, Jeon(mingu85.jeon)
* \date 2011/11/20
*
* <b>Revision History: </b>
* - 2011/11/21 : MinGu, Jeon(mingu85.jeon)) \n
* Initial version
* - 2012/11/29 : MinGu, Jeon(mingu85.jeon)) \n
* Change name
*/
#ifndef ANDROID_MEMORY_HEAP_ION_H
#define ANDROID_MEMORY_HEAP_ION_H
#include <binder/IMemory.h>
#include <binder/MemoryHeapBase.h>
#include <stdlib.h>
#define MHB_ION_HEAP_SYSTEM_CONTIG_MASK (1 << 1)
#define MHB_ION_HEAP_EXYNOS_CONTIG_MASK (1 << 4)
#define MHB_ION_HEAP_EXYNOS_MASK (1 << 5)
#define MHB_ION_HEAP_SYSTEM_MASK (1 << 6)
#define MHB_ION_FLAG_CACHED (1 << 16)
#define MHB_ION_FLAG_CACHED_NEEDS_SYNC (1 << 17)
#define MHB_ION_FLAG_PRESERVE_KMAP (1 << 18)
#define MHB_ION_EXYNOS_VIDEO_MASK (1 << 21)
#define MHB_ION_EXYNOS_MFC_INPUT_MASK (1 << 25)
#define MHB_ION_EXYNOS_MFC_OUTPUT_MASK (1 << 26)
#define MHB_ION_EXYNOS_GSC_MASK (1 << 27)
#define MHB_ION_EXYNOS_FIMD_VIDEO_MASK (1 << 28)
namespace android {
class MemoryHeapIon : public MemoryHeapBase
{
public:
enum {
USE_ION_FD = IMemoryHeap::USE_ION_FD
};
MemoryHeapIon(size_t size, uint32_t flags = 0, char const* name = NULL);
MemoryHeapIon(int fd, size_t size, uint32_t flags = 0, uint32_t offset = 0);
~MemoryHeapIon();
private:
int mIonClient;
};
};
#endif
@@ -0,0 +1,436 @@
/*
* 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>
#include <utils/Flattenable.h>
#include <linux/binder.h>
// ---------------------------------------------------------------------------
namespace android {
template <typename T> class Flattenable;
template <typename T> class LightFlattenable;
class IBinder;
class IPCThreadState;
class ProcessState;
class String8;
class TextOutput;
class Parcel {
friend class IPCThreadState;
public:
class ReadableBlob;
class WritableBlob;
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(const Parcel *parcel,
size_t start, size_t len);
bool allowFds() const;
bool pushAllowFds(bool allowFds);
void restoreAllowFds(bool lastValue);
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();
private:
const binder_size_t* objects() const;
public:
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 writeUint32(uint32_t val);
status_t writeInt64(int64_t val);
status_t writeUint64(uint64_t val);
status_t writeFloat(float val);
status_t writeDouble(double 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 writeInt32Array(size_t len, const int32_t *val);
status_t writeByteArray(size_t len, const uint8_t *val);
template<typename T>
status_t write(const Flattenable<T>& val);
template<typename T>
status_t write(const LightFlattenable<T>& 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.
// The Parcel does not take ownership of the given fd unless you ask it to.
status_t writeFileDescriptor(int fd, bool takeOwnership = false);
// 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);
// Writes a blob to the parcel.
// If the blob is small, then it is stored in-place, otherwise it is
// transferred by way of an anonymous shared memory region. Prefer sending
// immutable blobs if possible since they may be subsequently transferred between
// processes without further copying whereas mutable blobs always need to be copied.
// The caller should call release() on the blob after writing its contents.
status_t writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob);
// Write an existing immutable blob file descriptor to the parcel.
// This allows the client to send the same blob to multiple processes
// as long as it keeps a dup of the blob file descriptor handy for later.
status_t writeDupImmutableBlobFileDescriptor(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;
uint32_t readUint32() const;
status_t readUint32(uint32_t *pArg) const;
int64_t readInt64() const;
status_t readInt64(int64_t *pArg) const;
uint64_t readUint64() const;
status_t readUint64(uint64_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;
template<typename T>
status_t read(Flattenable<T>& val) const;
template<typename T>
status_t read(LightFlattenable<T>& 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;
// Reads a blob from the parcel.
// The caller should call release() on the blob after reading its contents.
status_t readBlob(size_t len, ReadableBlob* outBlob) const;
const flat_binder_object* readObject(bool nullMetaData) const;
// Explicitly close all file descriptors in the parcel.
void closeFileDescriptors();
// Debugging: get metrics on current allocations.
static size_t getGlobalAllocSize();
static size_t getGlobalAllocCount();
private:
typedef void (*release_func)(Parcel* parcel,
const uint8_t* data, size_t dataSize,
const binder_size_t* objects, size_t objectsSize,
void* cookie);
uintptr_t ipcData() const;
size_t ipcDataSize() const;
uintptr_t ipcObjects() const;
size_t ipcObjectsCount() const;
void ipcSetDataReference(const uint8_t* data, size_t dataSize,
const binder_size_t* objects, size_t objectsCount,
release_func relFunc, void* relCookie);
public:
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);
status_t writePointer(uintptr_t val);
status_t readPointer(uintptr_t *pArg) const;
uintptr_t readPointer() const;
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;
binder_size_t* mObjects;
size_t mObjectsSize;
size_t mObjectsCapacity;
mutable size_t mNextObjectHint;
mutable bool mFdsKnown;
mutable bool mHasFds;
bool mAllowFds;
release_func mOwner;
void* mOwnerCookie;
class Blob {
public:
Blob();
~Blob();
void clear();
void release();
inline size_t size() const { return mSize; }
inline int fd() const { return mFd; };
inline bool isMutable() const { return mMutable; }
protected:
void init(int fd, void* data, size_t size, bool isMutable);
int mFd; // owned by parcel so not closed when released
void* mData;
size_t mSize;
bool mMutable;
};
class FlattenableHelperInterface {
protected:
~FlattenableHelperInterface() { }
public:
virtual size_t getFlattenedSize() const = 0;
virtual size_t getFdCount() const = 0;
virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
};
template<typename T>
class FlattenableHelper : public FlattenableHelperInterface {
friend class Parcel;
const Flattenable<T>& val;
explicit FlattenableHelper(const Flattenable<T>& val) : val(val) { }
public:
virtual size_t getFlattenedSize() const {
return val.getFlattenedSize();
}
virtual size_t getFdCount() const {
return val.getFdCount();
}
virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
return val.flatten(buffer, size, fds, count);
}
virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
}
};
status_t write(const FlattenableHelperInterface& val);
status_t read(FlattenableHelperInterface& val) const;
public:
class ReadableBlob : public Blob {
friend class Parcel;
public:
inline const void* data() const { return mData; }
inline void* mutableData() { return isMutable() ? mData : NULL; }
};
class WritableBlob : public Blob {
friend class Parcel;
public:
inline void* data() { return mData; }
};
#ifndef DISABLE_ASHMEM_TRACKING
private:
size_t mOpenAshmemSize;
#endif
public:
// TODO: Remove once ABI can be changed.
size_t getBlobAshmemSize() const;
size_t getOpenAshmemSize() const;
};
// ---------------------------------------------------------------------------
template<typename T>
status_t Parcel::write(const Flattenable<T>& val) {
const FlattenableHelper<T> helper(val);
return write(helper);
}
template<typename T>
status_t Parcel::write(const LightFlattenable<T>& val) {
size_t size(val.getFlattenedSize());
if (!val.isFixedSize()) {
status_t err = writeInt32(size);
if (err != NO_ERROR) {
return err;
}
}
if (size) {
void* buffer = writeInplace(size);
if (buffer == NULL)
return NO_MEMORY;
return val.flatten(buffer, size);
}
return NO_ERROR;
}
template<typename T>
status_t Parcel::read(Flattenable<T>& val) const {
FlattenableHelper<T> helper(val);
return read(helper);
}
template<typename T>
status_t Parcel::read(LightFlattenable<T>& val) const {
size_t size;
if (val.isFixedSize()) {
size = val.getFlattenedSize();
} else {
int32_t s;
status_t err = readInt32(&s);
if (err != NO_ERROR) {
return err;
}
size = s;
}
if (size) {
void const* buffer = readInplace(size);
return buffer == NULL ? NO_MEMORY :
val.unflatten(buffer, size);
}
return NO_ERROR;
}
// ---------------------------------------------------------------------------
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
@@ -0,0 +1,80 @@
/*
* 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/String16.h>
#include <utils/Singleton.h>
#include <utils/SortedVector.h>
namespace android {
// ---------------------------------------------------------------------------
/*
* PermissionCache caches permission checks for a given uid.
*
* Currently the cache is not updated when there is a permission change,
* for instance when an application is uninstalled.
*
* IMPORTANT: for the reason stated above, only system permissions are safe
* to cache. This restriction may be lifted at a later time.
*
*/
class PermissionCache : Singleton<PermissionCache> {
struct Entry {
String16 name;
uid_t uid;
bool granted;
inline bool operator < (const Entry& e) const {
return (uid == e.uid) ? (name < e.name) : (uid < e.uid);
}
};
mutable Mutex mLock;
// we pool all the permission names we see, as many permissions checks
// will have identical names
SortedVector< String16 > mPermissionNamesPool;
// this is our cache per say. it stores pooled names.
SortedVector< Entry > mCache;
// free the whole cache, but keep the permission name pool
void purge();
status_t check(bool* granted,
const String16& permission, uid_t uid) const;
void cache(const String16& permission, uid_t uid, bool granted);
public:
PermissionCache();
static bool checkCallingPermission(const String16& permission);
static bool checkCallingPermission(const String16& permission,
int32_t* outPid, int32_t* outUid);
static bool checkPermission(const String16& permission,
pid_t pid, uid_t uid);
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif /* BINDER_PERMISSION_H */
@@ -0,0 +1,65 @@
/*
* Copyright 2015 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_INFO_SERVICE_H
#define ANDROID_PROCESS_INFO_SERVICE_H
#include <binder/IProcessInfoService.h>
#include <utils/Errors.h>
#include <utils/Singleton.h>
#include <sys/types.h>
namespace android {
// ----------------------------------------------------------------------
class ProcessInfoService : public Singleton<ProcessInfoService> {
friend class Singleton<ProcessInfoService>;
sp<IProcessInfoService> mProcessInfoService;
Mutex mProcessInfoLock;
ProcessInfoService();
status_t getProcessStatesImpl(size_t length, /*in*/ int32_t* pids, /*out*/ int32_t* states);
void updateBinderLocked();
static const int BINDER_ATTEMPT_LIMIT = 5;
public:
/**
* For each PID in the given "pids" input array, write the current process state
* for that process into the "states" output array, or
* ActivityManager.PROCESS_STATE_NONEXISTENT * to indicate that no process with the given PID
* exists.
*
* Returns NO_ERROR if this operation was successful, or a negative error code otherwise.
*/
static status_t getProcessStatesFromPids(size_t length, /*in*/ int32_t* pids,
/*out*/ int32_t* states) {
return ProcessInfoService::getInstance().getProcessStatesImpl(length, /*in*/ pids,
/*out*/ states);
}
};
// ----------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_PROCESS_INFO_SERVICE_H
@@ -0,0 +1,116 @@
/*
* 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>
#include <pthread.h>
// ---------------------------------------------------------------------------
namespace android {
class IPCThreadState;
class ProcessState : public virtual RefBase
{
public:
static sp<ProcessState> self();
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);
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 spawnPooledThread(bool isMain);
status_t setThreadPoolMaxThreadCount(size_t maxThreads);
void giveThreadPoolName();
private:
friend class IPCThreadState;
ProcessState();
~ProcessState();
ProcessState(const ProcessState& o);
ProcessState& operator=(const ProcessState& o);
String8 makeBinderThreadName();
struct handle_entry {
IBinder* binder;
RefBase::weakref_type* refs;
};
handle_entry* lookupHandleLocked(int32_t handle);
int mDriverFD;
void* mVMStart;
// Protects thread count variable below.
pthread_mutex_t mThreadCountLock;
pthread_cond_t mThreadCountDecrement;
// Number of binder threads current executing a command.
size_t mExecutingThreadsCount;
// Maximum number for binder threads allowed for this process.
size_t mMaxThreads;
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
@@ -0,0 +1,195 @@
/*
* Copyright (C) 2006 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_TEXTOUTPUT_H
#define ANDROID_TEXTOUTPUT_H
#include <utils/Errors.h>
#include <stdint.h>
#include <string.h>
// ---------------------------------------------------------------------------
namespace android {
class String8;
class String16;
class TextOutput
{
public:
TextOutput();
virtual ~TextOutput();
virtual status_t print(const char* txt, size_t len) = 0;
virtual void moveIndent(int delta) = 0;
class Bundle {
public:
inline Bundle(TextOutput& to) : mTO(to) { to.pushBundle(); }
inline ~Bundle() { mTO.popBundle(); }
private:
TextOutput& mTO;
};
virtual void pushBundle() = 0;
virtual void popBundle() = 0;
};
// ---------------------------------------------------------------------------
// Text output stream for printing to the log (via utils/Log.h).
extern TextOutput& alog;
// Text output stream for printing to stdout.
extern TextOutput& aout;
// Text output stream for printing to stderr.
extern TextOutput& aerr;
typedef TextOutput& (*TextOutputManipFunc)(TextOutput&);
TextOutput& endl(TextOutput& to);
TextOutput& indent(TextOutput& to);
TextOutput& dedent(TextOutput& to);
TextOutput& operator<<(TextOutput& to, const char* str);
TextOutput& operator<<(TextOutput& to, char); // writes raw character
TextOutput& operator<<(TextOutput& to, bool);
TextOutput& operator<<(TextOutput& to, int);
TextOutput& operator<<(TextOutput& to, long);
TextOutput& operator<<(TextOutput& to, unsigned int);
TextOutput& operator<<(TextOutput& to, unsigned long);
TextOutput& operator<<(TextOutput& to, long long);
TextOutput& operator<<(TextOutput& to, unsigned long long);
TextOutput& operator<<(TextOutput& to, float);
TextOutput& operator<<(TextOutput& to, double);
TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func);
TextOutput& operator<<(TextOutput& to, const void*);
TextOutput& operator<<(TextOutput& to, const String8& val);
TextOutput& operator<<(TextOutput& to, const String16& val);
class TypeCode
{
public:
inline TypeCode(uint32_t code);
inline ~TypeCode();
inline uint32_t typeCode() const;
private:
uint32_t mCode;
};
TextOutput& operator<<(TextOutput& to, const TypeCode& val);
class HexDump
{
public:
HexDump(const void *buf, size_t size, size_t bytesPerLine=16);
inline ~HexDump();
inline HexDump& setBytesPerLine(size_t bytesPerLine);
inline HexDump& setSingleLineCutoff(int32_t bytes);
inline HexDump& setAlignment(size_t alignment);
inline HexDump& setCArrayStyle(bool enabled);
inline const void* buffer() const;
inline size_t size() const;
inline size_t bytesPerLine() const;
inline int32_t singleLineCutoff() const;
inline size_t alignment() const;
inline bool carrayStyle() const;
private:
const void* mBuffer;
size_t mSize;
size_t mBytesPerLine;
int32_t mSingleLineCutoff;
size_t mAlignment;
bool mCArrayStyle;
};
TextOutput& operator<<(TextOutput& to, const HexDump& val);
// ---------------------------------------------------------------------------
// No user servicable parts below.
inline TextOutput& endl(TextOutput& to)
{
to.print("\n", 1);
return to;
}
inline TextOutput& indent(TextOutput& to)
{
to.moveIndent(1);
return to;
}
inline TextOutput& dedent(TextOutput& to)
{
to.moveIndent(-1);
return to;
}
inline TextOutput& operator<<(TextOutput& to, const char* str)
{
to.print(str, strlen(str));
return to;
}
inline TextOutput& operator<<(TextOutput& to, char c)
{
to.print(&c, 1);
return to;
}
inline TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func)
{
return (*func)(to);
}
inline TypeCode::TypeCode(uint32_t code) : mCode(code) { }
inline TypeCode::~TypeCode() { }
inline uint32_t TypeCode::typeCode() const { return mCode; }
inline HexDump::~HexDump() { }
inline HexDump& HexDump::setBytesPerLine(size_t bytesPerLine) {
mBytesPerLine = bytesPerLine; return *this;
}
inline HexDump& HexDump::setSingleLineCutoff(int32_t bytes) {
mSingleLineCutoff = bytes; return *this;
}
inline HexDump& HexDump::setAlignment(size_t alignment) {
mAlignment = alignment; return *this;
}
inline HexDump& HexDump::setCArrayStyle(bool enabled) {
mCArrayStyle = enabled; return *this;
}
inline const void* HexDump::buffer() const { return mBuffer; }
inline size_t HexDump::size() const { return mSize; }
inline size_t HexDump::bytesPerLine() const { return mBytesPerLine; }
inline int32_t HexDump::singleLineCutoff() const { return mSingleLineCutoff; }
inline size_t HexDump::alignment() const { return mAlignment; }
inline bool HexDump::carrayStyle() const { return mCArrayStyle; }
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_TEXTOUTPUT_H
@@ -0,0 +1,30 @@
/*
*
* 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 __LIBDISKUSAGE_DIRSIZE_H
#define __LIBDISKUSAGE_DIRSIZE_H
#include <stdint.h>
__BEGIN_DECLS
int64_t stat_size(struct stat *s);
int64_t calculate_dir_size(int dfd);
__END_DECLS
#endif /* __LIBDISKUSAGE_DIRSIZE_H */
@@ -0,0 +1,95 @@
/*
* 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>
#include <cutils/log.h>
namespace android {
// ----------------------------------------------------------------------------
class Parcel;
class BitTube : public RefBase
{
public:
// creates a BitTube with a default (4KB) send buffer
BitTube();
// creates a BitTube with a a specified send and receive buffer size
explicit BitTube(size_t bufsize);
explicit BitTube(const Parcel& data);
virtual ~BitTube();
// check state after construction
status_t initCheck() const;
// get receive file-descriptor
int getFd() const;
// get the send file-descriptor.
int getSendFd() const;
// send objects (sized blobs). All objects are guaranteed to be written or the call fails.
template <typename T>
static ssize_t sendObjects(const sp<BitTube>& tube,
T const* events, size_t count) {
return sendObjects(tube, events, count, sizeof(T));
}
// receive objects (sized blobs). If the receiving buffer isn't large enough,
// excess messages are silently discarded.
template <typename T>
static ssize_t recvObjects(const sp<BitTube>& tube,
T* events, size_t count) {
return recvObjects(tube, events, count, sizeof(T));
}
// parcels this BitTube
status_t writeToParcel(Parcel* reply) const;
private:
void init(size_t rcvbuf, size_t sndbuf);
// send a message. The write is guaranteed to send the whole message or fail.
ssize_t write(void const* vaddr, size_t size);
// receive a message. the passed buffer must be at least as large as the
// write call used to send the message, excess data is silently discarded.
ssize_t read(void* vaddr, size_t size);
int mSendFd;
mutable int mReceiveFd;
static ssize_t sendObjects(const sp<BitTube>& tube,
void const* events, size_t count, size_t objSize);
static ssize_t recvObjects(const sp<BitTube>& tube,
void* events, size_t count, size_t objSize);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SENSOR_CHANNEL_H
@@ -0,0 +1,130 @@
/*
* Copyright 2014 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_BUFFERITEM_H
#define ANDROID_GUI_BUFFERITEM_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <ui/Rect.h>
#include <ui/Region.h>
#include <system/graphics.h>
#include <utils/Flattenable.h>
#include <utils/StrongPointer.h>
namespace android {
class Fence;
class GraphicBuffer;
class BufferItem : public Flattenable<BufferItem> {
friend class Flattenable<BufferItem>;
size_t getPodSize() const;
size_t getFlattenedSize() const;
size_t getFdCount() const;
status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
public:
// The default value of mBuf, used to indicate this doesn't correspond to a slot.
enum { INVALID_BUFFER_SLOT = -1 };
BufferItem();
~BufferItem();
static const char* scalingModeName(uint32_t scalingMode);
// mGraphicBuffer points to the buffer allocated for this slot, or is NULL
// if the buffer in this slot has been acquired in the past (see
// BufferSlot.mAcquireCalled).
sp<GraphicBuffer> mGraphicBuffer;
// mFence is a fence that will signal when the buffer is idle.
sp<Fence> mFence;
// mCrop is the current crop rectangle for this buffer slot.
Rect mCrop;
// mTransform is the current transform flags for this buffer slot.
// refer to NATIVE_WINDOW_TRANSFORM_* in <window.h>
uint32_t mTransform;
// mScalingMode is the current scaling mode for this buffer slot.
// refer to NATIVE_WINDOW_SCALING_* in <window.h>
uint32_t mScalingMode;
// mTimestamp is the current timestamp for this buffer slot. This gets
// to set by queueBuffer each time this slot is queued. This value
// is guaranteed to be monotonically increasing for each newly
// acquired buffer.
union {
int64_t mTimestamp;
struct {
uint32_t mTimestampLo;
uint32_t mTimestampHi;
};
};
// mIsAutoTimestamp indicates whether mTimestamp was generated
// automatically when the buffer was queued.
bool mIsAutoTimestamp;
// mDataSpace is the current dataSpace value for this buffer slot. This gets
// set by queueBuffer each time this slot is queued. The meaning of the
// dataSpace is format-dependent.
android_dataspace mDataSpace;
// mFrameNumber is the number of the queued frame for this slot.
union {
uint64_t mFrameNumber;
struct {
uint32_t mFrameNumberLo;
uint32_t mFrameNumberHi;
};
};
union {
// mSlot is the slot index of this buffer (default INVALID_BUFFER_SLOT).
int mSlot;
// mBuf is the former name for mSlot
int mBuf;
};
// mIsDroppable whether this buffer was queued with the
// property that it can be replaced by a new buffer for the purpose of
// making sure dequeueBuffer() won't block.
// i.e.: was the BufferQueue in "mDequeueBufferCannotBlock" when this buffer
// was queued.
bool mIsDroppable;
// Indicates whether this buffer has been seen by a consumer yet
bool mAcquireCalled;
// Indicates this buffer must be transformed by the inverse transform of the screen
// it is displayed onto. This is applied after mTransform.
bool mTransformToDisplayInverse;
// Describes the portion of the surface that has been modified since the
// previous frame
Region mSurfaceDamage;
};
} // namespace android
#endif
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2012 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_BUFFERITEMCONSUMER_H
#define ANDROID_GUI_BUFFERITEMCONSUMER_H
#include <gui/ConsumerBase.h>
#include <ui/GraphicBuffer.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/threads.h>
#define ANDROID_GRAPHICS_BUFFERITEMCONSUMER_JNI_ID "mBufferItemConsumer"
namespace android {
class BufferQueue;
/**
* BufferItemConsumer is a BufferQueue consumer endpoint that allows clients
* access to the whole BufferItem entry from BufferQueue. Multiple buffers may
* be acquired at once, to be used concurrently by the client. This consumer can
* operate either in synchronous or asynchronous mode.
*/
class BufferItemConsumer: public ConsumerBase
{
public:
typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
enum { DEFAULT_MAX_BUFFERS = -1 };
enum { INVALID_BUFFER_SLOT = BufferQueue::INVALID_BUFFER_SLOT };
enum { NO_BUFFER_AVAILABLE = BufferQueue::NO_BUFFER_AVAILABLE };
// Create a new buffer item consumer. The consumerUsage parameter determines
// the consumer usage flags passed to the graphics allocator. The
// bufferCount parameter specifies how many buffers can be locked for user
// access at the same time.
// controlledByApp tells whether this consumer is controlled by the
// application.
BufferItemConsumer(const sp<IGraphicBufferConsumer>& consumer,
uint32_t consumerUsage, int bufferCount = DEFAULT_MAX_BUFFERS,
bool controlledByApp = false);
virtual ~BufferItemConsumer();
// set the name of the BufferItemConsumer that will be used to identify it in
// log messages.
void setName(const String8& name);
// Gets the next graphics buffer from the producer, filling out the
// passed-in BufferItem structure. Returns NO_BUFFER_AVAILABLE if the queue
// of buffers is empty, and INVALID_OPERATION if the maximum number of
// buffers is already acquired.
//
// Only a fixed number of buffers can be acquired at a time, determined by
// the construction-time bufferCount parameter. If INVALID_OPERATION is
// returned by acquireBuffer, then old buffers must be returned to the
// queue by calling releaseBuffer before more buffers can be acquired.
//
// If waitForFence is true, and the acquired BufferItem has a valid fence object,
// acquireBuffer will wait on the fence with no timeout before returning.
status_t acquireBuffer(BufferItem* item, nsecs_t presentWhen,
bool waitForFence = true);
// Returns an acquired buffer to the queue, allowing it to be reused. Since
// only a fixed number of buffers may be acquired at a time, old buffers
// must be released by calling releaseBuffer to ensure new buffers can be
// acquired by acquireBuffer. Once a BufferItem is released, the caller must
// not access any members of the BufferItem, and should immediately remove
// all of its references to the BufferItem itself.
status_t releaseBuffer(const BufferItem &item,
const sp<Fence>& releaseFence = Fence::NO_FENCE);
};
} // namespace android
#endif // ANDROID_GUI_CPUCONSUMER_H
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2012 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_BUFFERQUEUE_H
#define ANDROID_GUI_BUFFERQUEUE_H
#include <gui/BufferItem.h>
#include <gui/BufferQueueDefs.h>
#include <gui/IGraphicBufferConsumer.h>
#include <gui/IGraphicBufferProducer.h>
#include <gui/IConsumerListener.h>
// These are only required to keep other parts of the framework with incomplete
// dependencies building successfully
#include <gui/IGraphicBufferAlloc.h>
namespace android {
class BufferQueue {
public:
// BufferQueue will keep track of at most this value of buffers.
// Attempts at runtime to increase the number of buffers past this will fail.
enum { NUM_BUFFER_SLOTS = BufferQueueDefs::NUM_BUFFER_SLOTS };
// Used as a placeholder slot# when the value isn't pointing to an existing buffer.
enum { INVALID_BUFFER_SLOT = BufferItem::INVALID_BUFFER_SLOT };
// Alias to <IGraphicBufferConsumer.h> -- please scope from there in future code!
enum {
NO_BUFFER_AVAILABLE = IGraphicBufferConsumer::NO_BUFFER_AVAILABLE,
PRESENT_LATER = IGraphicBufferConsumer::PRESENT_LATER,
};
// When in async mode we reserve two slots in order to guarantee that the
// producer and consumer can run asynchronously.
enum { MAX_MAX_ACQUIRED_BUFFERS = NUM_BUFFER_SLOTS - 2 };
// for backward source compatibility
typedef ::android::ConsumerListener ConsumerListener;
// ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
// reference to the actual consumer object. It forwards all calls to that
// consumer object so long as it exists.
//
// This class exists to avoid having a circular reference between the
// BufferQueue object and the consumer object. The reason this can't be a weak
// reference in the BufferQueue class is because we're planning to expose the
// consumer side of a BufferQueue as a binder interface, which doesn't support
// weak references.
class ProxyConsumerListener : public BnConsumerListener {
public:
ProxyConsumerListener(const wp<ConsumerListener>& consumerListener);
virtual ~ProxyConsumerListener();
virtual void onFrameAvailable(const BufferItem& item) override;
virtual void onFrameReplaced(const BufferItem& item) override;
virtual void onBuffersReleased() override;
virtual void onSidebandStreamChanged() override;
private:
// mConsumerListener is a weak reference to the IConsumerListener. This is
// the raison d'etre of ProxyConsumerListener.
wp<ConsumerListener> mConsumerListener;
};
// BufferQueue manages a pool of gralloc memory slots to be used by
// producers and consumers. allocator is used to allocate all the
// needed gralloc buffers.
static void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
sp<IGraphicBufferConsumer>* outConsumer,
const sp<IGraphicBufferAlloc>& allocator = NULL);
private:
BufferQueue(); // Create through createBufferQueue
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_BUFFERQUEUE_H
@@ -0,0 +1,187 @@
/*
* Copyright 2014 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_BUFFERQUEUECONSUMER_H
#define ANDROID_GUI_BUFFERQUEUECONSUMER_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <gui/BufferQueueDefs.h>
#include <gui/IGraphicBufferConsumer.h>
namespace android {
class BufferQueueCore;
class BufferQueueConsumer : public BnGraphicBufferConsumer {
public:
BufferQueueConsumer(const sp<BufferQueueCore>& core);
virtual ~BufferQueueConsumer();
// acquireBuffer attempts to acquire ownership of the next pending buffer in
// the BufferQueue. If no buffer is pending then it returns
// NO_BUFFER_AVAILABLE. If a buffer is successfully acquired, the
// information about the buffer is returned in BufferItem. If the buffer
// returned had previously been acquired then the BufferItem::mGraphicBuffer
// field of buffer is set to NULL and it is assumed that the consumer still
// holds a reference to the buffer.
//
// If expectedPresent is nonzero, it indicates the time when the buffer
// will be displayed on screen. If the buffer's timestamp is farther in the
// future, the buffer won't be acquired, and PRESENT_LATER will be
// returned. The presentation time is in nanoseconds, and the time base
// is CLOCK_MONOTONIC.
virtual status_t acquireBuffer(BufferItem* outBuffer,
nsecs_t expectedPresent, uint64_t maxFrameNumber = 0) override;
// See IGraphicBufferConsumer::detachBuffer
virtual status_t detachBuffer(int slot);
// See IGraphicBufferConsumer::attachBuffer
virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer);
// releaseBuffer releases a buffer slot from the consumer back to the
// BufferQueue. This may be done while the buffer's contents are still
// being accessed. The fence will signal when the buffer is no longer
// in use. frameNumber is used to indentify the exact buffer returned.
//
// If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
// any references to the just-released buffer that it might have, as if it
// had received a onBuffersReleased() call with a mask set for the released
// buffer.
//
// Note that the dependencies on EGL will be removed once we switch to using
// the Android HW Sync HAL.
virtual status_t releaseBuffer(int slot, uint64_t frameNumber,
const sp<Fence>& releaseFence, EGLDisplay display,
EGLSyncKHR fence);
// connect connects a consumer to the BufferQueue. Only one
// consumer may be connected, and when that consumer disconnects the
// BufferQueue is placed into the "abandoned" state, causing most
// interactions with the BufferQueue by the producer to fail.
// controlledByApp indicates whether the consumer is controlled by
// the application.
//
// consumerListener may not be NULL.
virtual status_t connect(const sp<IConsumerListener>& consumerListener,
bool controlledByApp);
// disconnect disconnects a consumer from the BufferQueue. All
// buffers will be freed and the BufferQueue is placed in the "abandoned"
// state, causing most interactions with the BufferQueue by the producer to
// fail.
virtual status_t disconnect();
// getReleasedBuffers sets the value pointed to by outSlotMask to a bit mask
// indicating which buffer slots have been released by the BufferQueue
// but have not yet been released by the consumer.
//
// This should be called from the onBuffersReleased() callback.
virtual status_t getReleasedBuffers(uint64_t* outSlotMask);
// setDefaultBufferSize is used to set the size of buffers returned by
// dequeueBuffer when a width and height of zero is requested. Default
// is 1x1.
virtual status_t setDefaultBufferSize(uint32_t width, uint32_t height);
// setDefaultMaxBufferCount sets the default value for the maximum buffer
// count (the initial default is 2). If the producer has requested a
// buffer count using setBufferCount, the default buffer count will only
// take effect if the producer sets the count back to zero.
//
// The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
virtual status_t setDefaultMaxBufferCount(int bufferCount);
// disableAsyncBuffer disables the extra buffer used in async mode
// (when both producer and consumer have set their "isControlledByApp"
// flag) and has dequeueBuffer() return WOULD_BLOCK instead.
//
// This can only be called before connect().
virtual status_t disableAsyncBuffer();
// setMaxAcquiredBufferCount sets the maximum number of buffers that can
// be acquired by the consumer at one time (default 1). This call will
// fail if a producer is connected to the BufferQueue.
virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
// setConsumerName sets the name used in logging
virtual void setConsumerName(const String8& name);
// setDefaultBufferFormat allows the BufferQueue to create
// GraphicBuffers of a defaultFormat if no format is specified
// in dequeueBuffer. The initial default is HAL_PIXEL_FORMAT_RGBA_8888.
virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat);
// setDefaultBufferDataSpace allows the BufferQueue to create
// GraphicBuffers of a defaultDataSpace if no data space is specified
// in queueBuffer.
// The initial default is HAL_DATASPACE_UNKNOWN
virtual status_t setDefaultBufferDataSpace(
android_dataspace defaultDataSpace);
// setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
// These are merged with the bits passed to dequeueBuffer. The values are
// enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
virtual status_t setConsumerUsageBits(uint32_t usage);
// setTransformHint bakes in rotation to buffers so overlays can be used.
// The values are enumerated in window.h, e.g.
// NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
virtual status_t setTransformHint(uint32_t hint);
// Retrieve the sideband buffer stream, if any.
virtual sp<NativeHandle> getSidebandStream() const;
// dump our state in a String
virtual void dump(String8& result, const char* prefix) const;
// Functions required for backwards compatibility.
// These will be modified/renamed in IGraphicBufferConsumer and will be
// removed from this class at that time. See b/13306289.
virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
EGLDisplay display, EGLSyncKHR fence,
const sp<Fence>& releaseFence) {
return releaseBuffer(buf, frameNumber, releaseFence, display, fence);
}
virtual status_t consumerConnect(const sp<IConsumerListener>& consumer,
bool controlledByApp) {
return connect(consumer, controlledByApp);
}
virtual status_t consumerDisconnect() { return disconnect(); }
// End functions required for backwards compatibility
private:
sp<BufferQueueCore> mCore;
// This references mCore->mSlots. Lock mCore->mMutex while accessing.
BufferQueueDefs::SlotsType& mSlots;
// This is a cached copy of the name stored in the BufferQueueCore.
// It's updated during setConsumerName.
String8 mConsumerName;
}; // class BufferQueueConsumer
} // namespace android
#endif
@@ -0,0 +1,287 @@
/*
* Copyright 2014 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_BUFFERQUEUECORE_H
#define ANDROID_GUI_BUFFERQUEUECORE_H
#include <gui/BufferItem.h>
#include <gui/BufferQueueDefs.h>
#include <gui/BufferSlot.h>
#include <utils/Condition.h>
#include <utils/Mutex.h>
#include <utils/NativeHandle.h>
#include <utils/RefBase.h>
#include <utils/String8.h>
#include <utils/StrongPointer.h>
#include <utils/Trace.h>
#include <utils/Vector.h>
#include <list>
#include <set>
#define BQ_LOGV(x, ...) ALOGV("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
#define BQ_LOGD(x, ...) ALOGD("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
#define BQ_LOGI(x, ...) ALOGI("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
#define BQ_LOGW(x, ...) ALOGW("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
#define BQ_LOGE(x, ...) ALOGE("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
#define ATRACE_BUFFER_INDEX(index) \
if (ATRACE_ENABLED()) { \
char ___traceBuf[1024]; \
snprintf(___traceBuf, 1024, "%s: %d", \
mCore->mConsumerName.string(), (index)); \
android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf); \
}
namespace android {
class IConsumerListener;
class IGraphicBufferAlloc;
class IProducerListener;
class BufferQueueCore : public virtual RefBase {
friend class BufferQueueProducer;
friend class BufferQueueConsumer;
public:
// Used as a placeholder slot number when the value isn't pointing to an
// existing buffer.
enum { INVALID_BUFFER_SLOT = BufferItem::INVALID_BUFFER_SLOT };
// We reserve two slots in order to guarantee that the producer and
// consumer can run asynchronously.
enum { MAX_MAX_ACQUIRED_BUFFERS = BufferQueueDefs::NUM_BUFFER_SLOTS - 2 };
// The default API number used to indicate that no producer is connected
enum { NO_CONNECTED_API = 0 };
typedef Vector<BufferItem> Fifo;
// BufferQueueCore manages a pool of gralloc memory slots to be used by
// producers and consumers. allocator is used to allocate all the needed
// gralloc buffers.
BufferQueueCore(const sp<IGraphicBufferAlloc>& allocator = NULL);
virtual ~BufferQueueCore();
private:
// Dump our state in a string
void dump(String8& result, const char* prefix) const;
// getMinUndequeuedBufferCountLocked returns the minimum number of buffers
// that must remain in a state other than DEQUEUED. The async parameter
// tells whether we're in asynchronous mode.
int getMinUndequeuedBufferCountLocked(bool async) const;
// getMinMaxBufferCountLocked returns the minimum number of buffers allowed
// given the current BufferQueue state. The async parameter tells whether
// we're in asynchonous mode.
int getMinMaxBufferCountLocked(bool async) const;
// getMaxBufferCountLocked returns the maximum number of buffers that can be
// allocated at once. This value depends on the following member variables:
//
// mDequeueBufferCannotBlock
// mMaxAcquiredBufferCount
// mDefaultMaxBufferCount
// mOverrideMaxBufferCount
// async parameter
//
// Any time one of these member variables is changed while a producer is
// connected, mDequeueCondition must be broadcast.
int getMaxBufferCountLocked(bool async) const;
// setDefaultMaxBufferCountLocked sets the maximum number of buffer slots
// that will be used if the producer does not override the buffer slot
// count. The count must be between 2 and NUM_BUFFER_SLOTS, inclusive. The
// initial default is 2.
status_t setDefaultMaxBufferCountLocked(int count);
// freeBufferLocked frees the GraphicBuffer and sync resources for the
// given slot.
void freeBufferLocked(int slot);
// freeAllBuffersLocked frees the GraphicBuffer and sync resources for
// all slots.
void freeAllBuffersLocked();
// stillTracking returns true iff the buffer item is still being tracked
// in one of the slots.
bool stillTracking(const BufferItem* item) const;
// waitWhileAllocatingLocked blocks until mIsAllocating is false.
void waitWhileAllocatingLocked() const;
// validateConsistencyLocked ensures that the free lists are in sync with
// the information stored in mSlots
void validateConsistencyLocked() const;
// mAllocator is the connection to SurfaceFlinger that is used to allocate
// new GraphicBuffer objects.
sp<IGraphicBufferAlloc> mAllocator;
// mMutex is the mutex used to prevent concurrent access to the member
// variables of BufferQueueCore objects. It must be locked whenever any
// member variable is accessed.
mutable Mutex mMutex;
// mIsAbandoned indicates that the BufferQueue will no longer be used to
// consume image buffers pushed to it using the IGraphicBufferProducer
// interface. It is initialized to false, and set to true in the
// consumerDisconnect method. A BufferQueue that is abandoned will return
// the NO_INIT error from all IGraphicBufferProducer methods capable of
// returning an error.
bool mIsAbandoned;
// mConsumerControlledByApp indicates whether the connected consumer is
// controlled by the application.
bool mConsumerControlledByApp;
// mConsumerName is a string used to identify the BufferQueue in log
// messages. It is set by the IGraphicBufferConsumer::setConsumerName
// method.
String8 mConsumerName;
// mConsumerListener is used to notify the connected consumer of
// asynchronous events that it may wish to react to. It is initially
// set to NULL and is written by consumerConnect and consumerDisconnect.
sp<IConsumerListener> mConsumerListener;
// mConsumerUsageBits contains flags that the consumer wants for
// GraphicBuffers.
uint32_t mConsumerUsageBits;
// mConnectedApi indicates the producer API that is currently connected
// to this BufferQueue. It defaults to NO_CONNECTED_API, and gets updated
// by the connect and disconnect methods.
int mConnectedApi;
// mConnectedProducerToken is used to set a binder death notification on
// the producer.
sp<IProducerListener> mConnectedProducerListener;
// mSlots is an array of buffer slots that must be mirrored on the producer
// side. This allows buffer ownership to be transferred between the producer
// and consumer without sending a GraphicBuffer over Binder. The entire
// array is initialized to NULL at construction time, and buffers are
// allocated for a slot when requestBuffer is called with that slot's index.
BufferQueueDefs::SlotsType mSlots;
// mQueue is a FIFO of queued buffers used in synchronous mode.
Fifo mQueue;
// mFreeSlots contains all of the slots which are FREE and do not currently
// have a buffer attached
std::set<int> mFreeSlots;
// mFreeBuffers contains all of the slots which are FREE and currently have
// a buffer attached
std::list<int> mFreeBuffers;
// mOverrideMaxBufferCount is the limit on the number of buffers that will
// be allocated at one time. This value is set by the producer by calling
// setBufferCount. The default is 0, which means that the producer doesn't
// care about the number of buffers in the pool. In that case,
// mDefaultMaxBufferCount is used as the limit.
int mOverrideMaxBufferCount;
// mDequeueCondition is a condition variable used for dequeueBuffer in
// synchronous mode.
mutable Condition mDequeueCondition;
// mUseAsyncBuffer indicates whether an extra buffer is used in async mode
// to prevent dequeueBuffer from blocking.
bool mUseAsyncBuffer;
// mDequeueBufferCannotBlock indicates whether dequeueBuffer is allowed to
// block. This flag is set during connect when both the producer and
// consumer are controlled by the application.
bool mDequeueBufferCannotBlock;
// mDefaultBufferFormat can be set so it will override the buffer format
// when it isn't specified in dequeueBuffer.
PixelFormat mDefaultBufferFormat;
// mDefaultWidth holds the default width of allocated buffers. It is used
// in dequeueBuffer if a width and height of 0 are specified.
uint32_t mDefaultWidth;
// mDefaultHeight holds the default height of allocated buffers. It is used
// in dequeueBuffer if a width and height of 0 are specified.
uint32_t mDefaultHeight;
// mDefaultBufferDataSpace holds the default dataSpace of queued buffers.
// It is used in queueBuffer if a dataspace of 0 (HAL_DATASPACE_UNKNOWN)
// is specified.
android_dataspace mDefaultBufferDataSpace;
// mDefaultMaxBufferCount is the default limit on the number of buffers that
// will be allocated at one time. This default limit is set by the consumer.
// The limit (as opposed to the default limit) may be overriden by the
// producer.
int mDefaultMaxBufferCount;
// mMaxAcquiredBufferCount is the number of buffers that the consumer may
// acquire at one time. It defaults to 1, and can be changed by the consumer
// via setMaxAcquiredBufferCount, but this may only be done while no
// producer is connected to the BufferQueue. This value is used to derive
// the value returned for the MIN_UNDEQUEUED_BUFFERS query to the producer.
int mMaxAcquiredBufferCount;
// mBufferHasBeenQueued is true once a buffer has been queued. It is reset
// when something causes all buffers to be freed (e.g., changing the buffer
// count).
bool mBufferHasBeenQueued;
// mFrameCounter is the free running counter, incremented on every
// successful queueBuffer call and buffer allocation.
uint64_t mFrameCounter;
// mTransformHint is used to optimize for screen rotations.
uint32_t mTransformHint;
// mSidebandStream is a handle to the sideband buffer stream, if any
sp<NativeHandle> mSidebandStream;
// mIsAllocating indicates whether a producer is currently trying to allocate buffers (which
// releases mMutex while doing the allocation proper). Producers should not modify any of the
// FREE slots while this is true. mIsAllocatingCondition is signaled when this value changes to
// false.
bool mIsAllocating;
// mIsAllocatingCondition is a condition variable used by producers to wait until mIsAllocating
// becomes false.
mutable Condition mIsAllocatingCondition;
// mAllowAllocation determines whether dequeueBuffer is allowed to allocate
// new buffers
bool mAllowAllocation;
// mBufferAge tracks the age of the contents of the most recently dequeued
// buffer as the number of frames that have elapsed since it was last queued
uint64_t mBufferAge;
// mGenerationNumber stores the current generation number of the attached
// producer. Any attempt to attach a buffer with a different generation
// number will fail.
uint32_t mGenerationNumber;
}; // class BufferQueueCore
} // namespace android
#endif
@@ -0,0 +1,35 @@
/*
* Copyright 2014 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_BUFFERQUEUECOREDEFS_H
#define ANDROID_GUI_BUFFERQUEUECOREDEFS_H
#include <gui/BufferSlot.h>
namespace android {
class BufferQueueCore;
namespace BufferQueueDefs {
// BufferQueue will keep track of at most this value of buffers.
// Attempts at runtime to increase the number of buffers past this
// will fail.
enum { NUM_BUFFER_SLOTS = 64 };
typedef BufferSlot SlotsType[NUM_BUFFER_SLOTS];
} // namespace BufferQueueDefs
} // namespace android
#endif
@@ -0,0 +1,228 @@
/*
* Copyright 2014 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_BUFFERQUEUEPRODUCER_H
#define ANDROID_GUI_BUFFERQUEUEPRODUCER_H
#include <gui/BufferQueueDefs.h>
#include <gui/IGraphicBufferProducer.h>
namespace android {
class BufferSlot;
class BufferQueueProducer : public BnGraphicBufferProducer,
private IBinder::DeathRecipient {
public:
friend class BufferQueue; // Needed to access binderDied
BufferQueueProducer(const sp<BufferQueueCore>& core);
virtual ~BufferQueueProducer();
// requestBuffer returns the GraphicBuffer for slot N.
//
// In normal operation, this is called the first time slot N is returned
// by dequeueBuffer. It must be called again if dequeueBuffer returns
// flags indicating that previously-returned buffers are no longer valid.
virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
// setBufferCount updates the number of available buffer slots. If this
// method succeeds, buffer slots will be both unallocated and owned by
// the BufferQueue object (i.e. they are not owned by the producer or
// consumer).
//
// This will fail if the producer has dequeued any buffers, or if
// bufferCount is invalid. bufferCount must generally be a value
// between the minimum undequeued buffer count (exclusive) and NUM_BUFFER_SLOTS
// (inclusive). It may also be set to zero (the default) to indicate
// that the producer does not wish to set a value. The minimum value
// can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
// ...).
//
// This may only be called by the producer. The consumer will be told
// to discard buffers through the onBuffersReleased callback.
virtual status_t setBufferCount(int bufferCount);
// dequeueBuffer gets the next buffer slot index for the producer to use.
// If a buffer slot is available then that slot index is written to the
// location pointed to by the buf argument and a status of OK is returned.
// If no slot is available then a status of -EBUSY is returned and buf is
// unmodified.
//
// The outFence parameter will be updated to hold the fence associated with
// the buffer. The contents of the buffer must not be overwritten until the
// fence signals. If the fence is Fence::NO_FENCE, the buffer may be
// written immediately.
//
// The width and height parameters must be no greater than the minimum of
// GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
// An error due to invalid dimensions might not be reported until
// updateTexImage() is called. If width and height are both zero, the
// default values specified by setDefaultBufferSize() are used instead.
//
// If the format is 0, the default format will be used.
//
// The usage argument specifies gralloc buffer usage flags. The values
// are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER. These
// will be merged with the usage flags specified by setConsumerUsageBits.
//
// The return value may be a negative error value or a non-negative
// collection of flags. If the flags are set, the return values are
// valid, but additional actions must be performed.
//
// If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
// producer must discard cached GraphicBuffer references for the slot
// returned in buf.
// If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
// must discard cached GraphicBuffer references for all slots.
//
// In both cases, the producer will need to call requestBuffer to get a
// GraphicBuffer handle for the returned slot.
virtual status_t dequeueBuffer(int *outSlot, sp<Fence>* outFence,
bool async, uint32_t width, uint32_t height, PixelFormat format,
uint32_t usage);
// See IGraphicBufferProducer::detachBuffer
virtual status_t detachBuffer(int slot);
// See IGraphicBufferProducer::detachNextBuffer
virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
sp<Fence>* outFence);
// See IGraphicBufferProducer::attachBuffer
virtual status_t attachBuffer(int* outSlot, const sp<GraphicBuffer>& buffer);
// queueBuffer returns a filled buffer to the BufferQueue.
//
// Additional data is provided in the QueueBufferInput struct. Notably,
// a timestamp must be provided for the buffer. The timestamp is in
// nanoseconds, and must be monotonically increasing. Its other semantics
// (zero point, etc) are producer-specific and should be documented by the
// producer.
//
// The caller may provide a fence that signals when all rendering
// operations have completed. Alternatively, NO_FENCE may be used,
// indicating that the buffer is ready immediately.
//
// Some values are returned in the output struct: the current settings
// for default width and height, the current transform hint, and the
// number of queued buffers.
virtual status_t queueBuffer(int slot,
const QueueBufferInput& input, QueueBufferOutput* output);
// cancelBuffer returns a dequeued buffer to the BufferQueue, but doesn't
// queue it for use by the consumer.
//
// The buffer will not be overwritten until the fence signals. The fence
// will usually be the one obtained from dequeueBuffer.
virtual void cancelBuffer(int slot, const sp<Fence>& fence);
// Query native window attributes. The "what" values are enumerated in
// window.h (e.g. NATIVE_WINDOW_FORMAT).
virtual int query(int what, int* outValue);
// connect attempts to connect a producer API to the BufferQueue. This
// must be called before any other IGraphicBufferProducer methods are
// called except for getAllocator. A consumer must already be connected.
//
// This method will fail if connect was previously called on the
// BufferQueue and no corresponding disconnect call was made (i.e. if
// it's still connected to a producer).
//
// APIs are enumerated in window.h (e.g. NATIVE_WINDOW_API_CPU).
virtual status_t connect(const sp<IProducerListener>& listener,
int api, bool producerControlledByApp, QueueBufferOutput* output);
// disconnect attempts to disconnect a producer API from the BufferQueue.
// Calling this method will cause any subsequent calls to other
// IGraphicBufferProducer methods to fail except for getAllocator and connect.
// Successfully calling connect after this will allow the other methods to
// succeed again.
//
// This method will fail if the the BufferQueue is not currently
// connected to the specified producer API.
virtual status_t disconnect(int api);
// Attaches a sideband buffer stream to the IGraphicBufferProducer.
//
// A sideband stream is a device-specific mechanism for passing buffers
// from the producer to the consumer without using dequeueBuffer/
// queueBuffer. If a sideband stream is present, the consumer can choose
// whether to acquire buffers from the sideband stream or from the queued
// buffers.
//
// Passing NULL or a different stream handle will detach the previous
// handle if any.
virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
// See IGraphicBufferProducer::allocateBuffers
virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
PixelFormat format, uint32_t usage);
// See IGraphicBufferProducer::allowAllocation
virtual status_t allowAllocation(bool allow);
// See IGraphicBufferProducer::setGenerationNumber
virtual status_t setGenerationNumber(uint32_t generationNumber);
// See IGraphicBufferProducer::getConsumerName
virtual String8 getConsumerName() const override;
private:
// This is required by the IBinder::DeathRecipient interface
virtual void binderDied(const wp<IBinder>& who);
// waitForFreeSlotThenRelock finds the oldest slot in the FREE state. It may
// block if there are no available slots and we are not in non-blocking
// mode (producer and consumer controlled by the application). If it blocks,
// it will release mCore->mMutex while blocked so that other operations on
// the BufferQueue may succeed.
status_t waitForFreeSlotThenRelock(const char* caller, bool async,
int* found, status_t* returnFlags) const;
sp<BufferQueueCore> mCore;
// This references mCore->mSlots. Lock mCore->mMutex while accessing.
BufferQueueDefs::SlotsType& mSlots;
// This is a cached copy of the name stored in the BufferQueueCore.
// It's updated during connect and dequeueBuffer (which should catch
// most updates).
String8 mConsumerName;
uint32_t mStickyTransform;
// This saves the fence from the last queueBuffer, such that the
// next queueBuffer call can throttle buffer production. The prior
// queueBuffer's fence is not nessessarily available elsewhere,
// since the previous buffer might have already been acquired.
sp<Fence> mLastQueueBufferFence;
// Take-a-ticket system for ensuring that onFrame* callbacks are called in
// the order that frames are queued. While the BufferQueue lock
// (mCore->mMutex) is held, a ticket is retained by the producer. After
// dropping the BufferQueue lock, the producer must wait on the condition
// variable until the current callback ticket matches its retained ticket.
Mutex mCallbackMutex;
int mNextCallbackTicket; // Protected by mCore->mMutex
int mCurrentCallbackTicket; // Protected by mCallbackMutex
Condition mCallbackCondition;
}; // class BufferQueueProducer
} // namespace android
#endif
@@ -0,0 +1,142 @@
/*
* Copyright 2014 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_BUFFERSLOT_H
#define ANDROID_GUI_BUFFERSLOT_H
#include <ui/Fence.h>
#include <ui/GraphicBuffer.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <utils/StrongPointer.h>
namespace android {
class Fence;
struct BufferSlot {
BufferSlot()
: mEglDisplay(EGL_NO_DISPLAY),
mBufferState(BufferSlot::FREE),
mRequestBufferCalled(false),
mFrameNumber(0),
mEglFence(EGL_NO_SYNC_KHR),
mAcquireCalled(false),
mNeedsCleanupOnRelease(false),
mAttachedByConsumer(false) {
}
// mGraphicBuffer points to the buffer allocated for this slot or is NULL
// if no buffer has been allocated.
sp<GraphicBuffer> mGraphicBuffer;
// mEglDisplay is the EGLDisplay used to create EGLSyncKHR objects.
EGLDisplay mEglDisplay;
// BufferState represents the different states in which a buffer slot
// can be. All slots are initially FREE.
enum BufferState {
// FREE indicates that the buffer is available to be dequeued
// by the producer. The buffer may be in use by the consumer for
// a finite time, so the buffer must not be modified until the
// associated fence is signaled.
//
// The slot is "owned" by BufferQueue. It transitions to DEQUEUED
// when dequeueBuffer is called.
FREE = 0,
// DEQUEUED indicates that the buffer has been dequeued by the
// producer, but has not yet been queued or canceled. The
// producer may modify the buffer's contents as soon as the
// associated ready fence is signaled.
//
// The slot is "owned" by the producer. It can transition to
// QUEUED (via queueBuffer) or back to FREE (via cancelBuffer).
DEQUEUED = 1,
// QUEUED indicates that the buffer has been filled by the
// producer and queued for use by the consumer. The buffer
// contents may continue to be modified for a finite time, so
// the contents must not be accessed until the associated fence
// is signaled.
//
// The slot is "owned" by BufferQueue. It can transition to
// ACQUIRED (via acquireBuffer) or to FREE (if another buffer is
// queued in asynchronous mode).
QUEUED = 2,
// ACQUIRED indicates that the buffer has been acquired by the
// consumer. As with QUEUED, the contents must not be accessed
// by the consumer until the fence is signaled.
//
// The slot is "owned" by the consumer. It transitions to FREE
// when releaseBuffer is called.
ACQUIRED = 3
};
static const char* bufferStateName(BufferState state);
// mBufferState is the current state of this buffer slot.
BufferState mBufferState;
// mRequestBufferCalled is used for validating that the producer did
// call requestBuffer() when told to do so. Technically this is not
// needed but useful for debugging and catching producer bugs.
bool mRequestBufferCalled;
// mFrameNumber is the number of the queued frame for this slot. This
// is used to dequeue buffers in LRU order (useful because buffers
// may be released before their release fence is signaled).
uint64_t mFrameNumber;
// mEglFence is the EGL sync object that must signal before the buffer
// associated with this buffer slot may be dequeued. It is initialized
// to EGL_NO_SYNC_KHR when the buffer is created and may be set to a
// new sync object in releaseBuffer. (This is deprecated in favor of
// mFence, below.)
EGLSyncKHR mEglFence;
// mFence is a fence which will signal when work initiated by the
// previous owner of the buffer is finished. When the buffer is FREE,
// the fence indicates when the consumer has finished reading
// from the buffer, or when the producer has finished writing if it
// called cancelBuffer after queueing some writes. When the buffer is
// QUEUED, it indicates when the producer has finished filling the
// buffer. When the buffer is DEQUEUED or ACQUIRED, the fence has been
// passed to the consumer or producer along with ownership of the
// buffer, and mFence is set to NO_FENCE.
sp<Fence> mFence;
// Indicates whether this buffer has been seen by a consumer yet
bool mAcquireCalled;
// Indicates whether this buffer needs to be cleaned up by the
// consumer. This is set when a buffer in ACQUIRED state is freed.
// It causes releaseBuffer to return STALE_BUFFER_SLOT.
bool mNeedsCleanupOnRelease;
// Indicates whether the buffer was attached on the consumer side.
// If so, it needs to set the BUFFER_NEEDS_REALLOCATION flag when dequeued
// to prevent the producer from using a stale cached buffer.
bool mAttachedByConsumer;
};
} // namespace android
#endif
@@ -0,0 +1,252 @@
/*
* 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_CONSUMERBASE_H
#define ANDROID_GUI_CONSUMERBASE_H
#include <gui/BufferQueue.h>
#include <ui/GraphicBuffer.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/threads.h>
#include <gui/IConsumerListener.h>
namespace android {
// ----------------------------------------------------------------------------
class String8;
// ConsumerBase is a base class for BufferQueue consumer end-points. It
// handles common tasks like management of the connection to the BufferQueue
// and the buffer pool.
class ConsumerBase : public virtual RefBase,
protected ConsumerListener {
public:
struct FrameAvailableListener : public virtual RefBase {
// See IConsumerListener::onFrame{Available,Replaced}
virtual void onFrameAvailable(const BufferItem& item) = 0;
virtual void onFrameReplaced(const BufferItem& /* item */) {}
};
virtual ~ConsumerBase();
// abandon frees all the buffers and puts the ConsumerBase into the
// 'abandoned' state. Once put in this state the ConsumerBase can never
// leave it. When in the 'abandoned' state, all methods of the
// IGraphicBufferProducer interface will fail with the NO_INIT error.
//
// Note that while calling this method causes all the buffers to be freed
// from the perspective of the the ConsumerBase, if there are additional
// references on the buffers (e.g. if a buffer is referenced by a client
// or by OpenGL ES as a texture) then those buffer will remain allocated.
void abandon();
// Returns true if the ConsumerBase is in the 'abandoned' state
bool isAbandoned();
// set the name of the ConsumerBase that will be used to identify it in
// log messages.
void setName(const String8& name);
// dump writes the current state to a string. Child classes should add
// their state to the dump by overriding the dumpLocked method, which is
// called by these methods after locking the mutex.
void dump(String8& result) const;
void dump(String8& result, const char* prefix) const;
// setFrameAvailableListener sets the listener object that will be notified
// when a new frame becomes available.
void setFrameAvailableListener(const wp<FrameAvailableListener>& listener);
// See IGraphicBufferConsumer::detachBuffer
status_t detachBuffer(int slot);
// See IGraphicBufferConsumer::setDefaultBufferSize
status_t setDefaultBufferSize(uint32_t width, uint32_t height);
// See IGraphicBufferConsumer::setDefaultBufferFormat
status_t setDefaultBufferFormat(PixelFormat defaultFormat);
// See IGraphicBufferConsumer::setDefaultBufferDataSpace
status_t setDefaultBufferDataSpace(android_dataspace defaultDataSpace);
private:
ConsumerBase(const ConsumerBase&);
void operator=(const ConsumerBase&);
protected:
// ConsumerBase constructs a new ConsumerBase object to consume image
// buffers from the given IGraphicBufferConsumer.
// The controlledByApp flag indicates that this consumer is under the application's
// control.
ConsumerBase(const sp<IGraphicBufferConsumer>& consumer, bool controlledByApp = false);
// onLastStrongRef gets called by RefBase just before the dtor of the most
// derived class. It is used to clean up the buffers so that ConsumerBase
// can coordinate the clean-up by calling into virtual methods implemented
// by the derived classes. This would not be possible from the
// ConsuemrBase dtor because by the time that gets called the derived
// classes have already been destructed.
//
// This methods should not need to be overridden by derived classes, but
// if they are overridden the ConsumerBase implementation must be called
// from the derived class.
virtual void onLastStrongRef(const void* id);
// Implementation of the IConsumerListener interface. These
// calls are used to notify the ConsumerBase of asynchronous events in the
// BufferQueue. The onFrameAvailable, onFrameReplaced, and
// onBuffersReleased methods should not need to be overridden by derived
// classes, but if they are overridden the ConsumerBase implementation must
// be called from the derived class. The ConsumerBase version of
// onSidebandStreamChanged does nothing and can be overriden by derived
// classes if they want the notification.
virtual void onFrameAvailable(const BufferItem& item) override;
virtual void onFrameReplaced(const BufferItem& item) override;
virtual void onBuffersReleased() override;
virtual void onSidebandStreamChanged() override;
// freeBufferLocked frees up the given buffer slot. If the slot has been
// initialized this will release the reference to the GraphicBuffer in that
// slot. Otherwise it has no effect.
//
// Derived classes should override this method to clean up any state they
// keep per slot. If it is overridden, the derived class's implementation
// must call ConsumerBase::freeBufferLocked.
//
// This method must be called with mMutex locked.
virtual void freeBufferLocked(int slotIndex);
// abandonLocked puts the BufferQueue into the abandoned state, causing
// all future operations on it to fail. This method rather than the public
// abandon method should be overridden by child classes to add abandon-
// time behavior.
//
// Derived classes should override this method to clean up any object
// state they keep (as opposed to per-slot state). If it is overridden,
// the derived class's implementation must call ConsumerBase::abandonLocked.
//
// This method must be called with mMutex locked.
virtual void abandonLocked();
// dumpLocked dumps the current state of the ConsumerBase object to the
// result string. Each line is prefixed with the string pointed to by the
// prefix argument. The buffer argument points to a buffer that may be
// used for intermediate formatting data, and the size of that buffer is
// indicated by the size argument.
//
// Derived classes should override this method to dump their internal
// state. If this method is overridden the derived class's implementation
// should call ConsumerBase::dumpLocked.
//
// This method must be called with mMutex locked.
virtual void dumpLocked(String8& result, const char* prefix) const;
// acquireBufferLocked fetches the next buffer from the BufferQueue and
// updates the buffer slot for the buffer returned.
//
// Derived classes should override this method to perform any
// initialization that must take place the first time a buffer is assigned
// to a slot. If it is overridden the derived class's implementation must
// call ConsumerBase::acquireBufferLocked.
virtual status_t acquireBufferLocked(BufferItem *item, nsecs_t presentWhen,
uint64_t maxFrameNumber = 0);
// releaseBufferLocked relinquishes control over a buffer, returning that
// control to the BufferQueue.
//
// Derived classes should override this method to perform any cleanup that
// must take place when a buffer is released back to the BufferQueue. If
// it is overridden the derived class's implementation must call
// ConsumerBase::releaseBufferLocked.e
virtual status_t releaseBufferLocked(int slot,
const sp<GraphicBuffer> graphicBuffer,
EGLDisplay display, EGLSyncKHR eglFence);
// returns true iff the slot still has the graphicBuffer in it.
bool stillTracking(int slot, const sp<GraphicBuffer> graphicBuffer);
// addReleaseFence* adds the sync points associated with a fence to the set
// of sync points that must be reached before the buffer in the given slot
// may be used after the slot has been released. This should be called by
// derived classes each time some asynchronous work is kicked off that
// references the buffer.
status_t addReleaseFence(int slot,
const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
status_t addReleaseFenceLocked(int slot,
const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
// Slot contains the information and object references that
// ConsumerBase maintains about a BufferQueue buffer slot.
struct Slot {
// mGraphicBuffer is the Gralloc buffer store in the slot or NULL if
// no Gralloc buffer is in the slot.
sp<GraphicBuffer> mGraphicBuffer;
// mFence is a fence which will signal when the buffer associated with
// this buffer slot is no longer being used by the consumer and can be
// overwritten. The buffer can be dequeued before the fence signals;
// the producer is responsible for delaying writes until it signals.
sp<Fence> mFence;
// the frame number of the last acquired frame for this slot
uint64_t mFrameNumber;
};
// mSlots stores the buffers that have been allocated by the BufferQueue
// for each buffer slot. It is initialized to null pointers, and gets
// filled in with the result of BufferQueue::acquire when the
// client dequeues a buffer from a
// slot that has not yet been used. The buffer allocated to a slot will also
// be replaced if the requested buffer usage or geometry differs from that
// of the buffer allocated to a slot.
Slot mSlots[BufferQueue::NUM_BUFFER_SLOTS];
// mAbandoned indicates that the BufferQueue will no longer be used to
// consume images buffers pushed to it using the IGraphicBufferProducer
// interface. It is initialized to false, and set to true in the abandon
// method. A BufferQueue that has been abandoned will return the NO_INIT
// error from all IConsumerBase methods capable of returning an error.
bool mAbandoned;
// mName is a string used to identify the ConsumerBase in log messages.
// It can be set by the setName method.
String8 mName;
// mFrameAvailableListener is the listener object that will be called when a
// new frame becomes available. If it is not NULL it will be called from
// queueBuffer.
wp<FrameAvailableListener> mFrameAvailableListener;
// The ConsumerBase has-a BufferQueue and is responsible for creating this object
// if none is supplied
sp<IGraphicBufferConsumer> mConsumer;
// mMutex is the mutex used to prevent concurrent access to the member
// variables of ConsumerBase objects. It must be locked whenever the
// member variables are accessed or when any of the *Locked methods are
// called.
//
// This mutex is intended to be locked by derived classes.
mutable Mutex mMutex;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_CONSUMERBASE_H
@@ -0,0 +1,131 @@
/*
* Copyright (C) 2012 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_CPUCONSUMER_H
#define ANDROID_GUI_CPUCONSUMER_H
#include <gui/ConsumerBase.h>
#include <ui/GraphicBuffer.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/threads.h>
namespace android {
class BufferQueue;
/**
* CpuConsumer is a BufferQueue consumer endpoint that allows direct CPU
* access to the underlying gralloc buffers provided by BufferQueue. Multiple
* buffers may be acquired by it at once, to be used concurrently by the
* CpuConsumer owner. Sets gralloc usage flags to be software-read-only.
* This queue is synchronous by default.
*/
class CpuConsumer : public ConsumerBase
{
public:
typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
struct LockedBuffer {
uint8_t *data;
uint32_t width;
uint32_t height;
PixelFormat format;
uint32_t stride;
Rect crop;
uint32_t transform;
uint32_t scalingMode;
int64_t timestamp;
android_dataspace dataSpace;
uint64_t frameNumber;
// this is the same as format, except for formats that are compatible with
// a flexible format (e.g. HAL_PIXEL_FORMAT_YCbCr_420_888). In the latter
// case this contains that flexible format
PixelFormat flexFormat;
// Values below are only valid when using HAL_PIXEL_FORMAT_YCbCr_420_888
// or compatible format, in which case LockedBuffer::data
// contains the Y channel, and stride is the Y channel stride. For other
// formats, these will all be 0.
uint8_t *dataCb;
uint8_t *dataCr;
uint32_t chromaStride;
uint32_t chromaStep;
};
// Create a new CPU consumer. The maxLockedBuffers parameter specifies
// how many buffers can be locked for user access at the same time.
CpuConsumer(const sp<IGraphicBufferConsumer>& bq,
size_t maxLockedBuffers, bool controlledByApp = false);
virtual ~CpuConsumer();
// set the name of the CpuConsumer that will be used to identify it in
// log messages.
void setName(const String8& name);
// Gets the next graphics buffer from the producer and locks it for CPU use,
// filling out the passed-in locked buffer structure with the native pointer
// and metadata. Returns BAD_VALUE if no new buffer is available, and
// NOT_ENOUGH_DATA if the maximum number of buffers is already locked.
//
// Only a fixed number of buffers can be locked at a time, determined by the
// construction-time maxLockedBuffers parameter. If INVALID_OPERATION is
// returned by lockNextBuffer, then old buffers must be returned to the queue
// by calling unlockBuffer before more buffers can be acquired.
status_t lockNextBuffer(LockedBuffer *nativeBuffer);
// Returns a locked buffer to the queue, allowing it to be reused. Since
// only a fixed number of buffers may be locked at a time, old buffers must
// be released by calling unlockBuffer to ensure new buffers can be acquired by
// lockNextBuffer.
status_t unlockBuffer(const LockedBuffer &nativeBuffer);
private:
// Maximum number of buffers that can be locked at a time
size_t mMaxLockedBuffers;
status_t releaseAcquiredBufferLocked(size_t lockedIdx);
virtual void freeBufferLocked(int slotIndex);
// Tracking for buffers acquired by the user
struct AcquiredBuffer {
// Need to track the original mSlot index and the buffer itself because
// the mSlot entry may be freed/reused before the acquired buffer is
// released.
int mSlot;
sp<GraphicBuffer> mGraphicBuffer;
void *mBufferPointer;
AcquiredBuffer() :
mSlot(BufferQueue::INVALID_BUFFER_SLOT),
mBufferPointer(NULL) {
}
};
Vector<AcquiredBuffer> mAcquiredBuffers;
// Count of currently locked buffers
size_t mCurrentLockedBuffers;
};
} // namespace android
#endif // ANDROID_GUI_CPUCONSUMER_H
@@ -0,0 +1,137 @@
/*
* Copyright (C) 2011 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_DISPLAY_EVENT_H
#define ANDROID_GUI_DISPLAY_EVENT_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/Timers.h>
#include <binder/IInterface.h>
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
class BitTube;
class IDisplayEventConnection;
// ----------------------------------------------------------------------------
class DisplayEventReceiver {
public:
enum {
DISPLAY_EVENT_VSYNC = 'vsyn',
DISPLAY_EVENT_HOTPLUG = 'plug'
};
struct Event {
struct Header {
uint32_t type;
uint32_t id;
nsecs_t timestamp __attribute__((aligned(8)));
};
struct VSync {
uint32_t count;
};
struct Hotplug {
bool connected;
};
Header header;
union {
VSync vsync;
Hotplug hotplug;
};
};
public:
/*
* DisplayEventReceiver creates and registers an event connection with
* SurfaceFlinger. VSync events are disabled by default. Call setVSyncRate
* or requestNextVsync to receive them.
* Other events start being delivered immediately.
*/
DisplayEventReceiver();
/*
* ~DisplayEventReceiver severs the connection with SurfaceFlinger, new events
* stop being delivered immediately. Note that the queue could have
* some events pending. These will be delivered.
*/
~DisplayEventReceiver();
/*
* initCheck returns the state of DisplayEventReceiver after construction.
*/
status_t initCheck() const;
/*
* getFd returns the file descriptor to use to receive events.
* OWNERSHIP IS RETAINED by DisplayEventReceiver. DO NOT CLOSE this
* file-descriptor.
*/
int getFd() const;
/*
* getEvents reads events from the queue and returns how many events were
* read. Returns 0 if there are no more events or a negative error code.
* If NOT_ENOUGH_DATA is returned, the object has become invalid forever, it
* should be destroyed and getEvents() shouldn't be called again.
*/
ssize_t getEvents(Event* events, size_t count);
static ssize_t getEvents(const sp<BitTube>& dataChannel,
Event* events, size_t count);
/*
* sendEvents write events to the queue and returns how many events were
* written.
*/
static ssize_t sendEvents(const sp<BitTube>& dataChannel,
Event const* events, size_t count);
/*
* setVsyncRate() sets the Event::VSync delivery rate. A value of
* 1 returns every Event::VSync. A value of 2 returns every other event,
* etc... a value of 0 returns no event unless requestNextVsync() has
* been called.
*/
status_t setVsyncRate(uint32_t count);
/*
* requestNextVsync() schedules the next Event::VSync. It has no effect
* if the vsync rate is > 0.
*/
status_t requestNextVsync();
private:
sp<IDisplayEventConnection> mEventConnection;
sp<BitTube> mDataChannel;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_DISPLAY_EVENT_H
@@ -0,0 +1,488 @@
/*
* 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_CONSUMER_H
#define ANDROID_GUI_CONSUMER_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <gui/IGraphicBufferProducer.h>
#include <gui/BufferQueue.h>
#include <gui/ConsumerBase.h>
#include <ui/GraphicBuffer.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/threads.h>
namespace android {
// ----------------------------------------------------------------------------
class String8;
/*
* GLConsumer consumes buffers of graphics data from a BufferQueue,
* and makes them available to OpenGL as a texture.
*
* A typical usage pattern is to set up the GLConsumer with the
* desired options, and call updateTexImage() when a new frame is desired.
* If a new frame is available, the texture will be updated. If not,
* the previous contents are retained.
*
* By default, the texture is attached to the GL_TEXTURE_EXTERNAL_OES
* texture target, in the EGL context of the first thread that calls
* updateTexImage().
*
* This class was previously called SurfaceTexture.
*/
class GLConsumer : public ConsumerBase {
public:
enum { TEXTURE_EXTERNAL = 0x8D65 }; // GL_TEXTURE_EXTERNAL_OES
typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
// GLConsumer constructs a new GLConsumer object. If the constructor with
// the tex parameter is used, tex indicates the name of the OpenGL ES
// texture to which images are to be streamed. texTarget specifies the
// OpenGL ES texture target to which the texture will be bound in
// updateTexImage. useFenceSync specifies whether fences should be used to
// synchronize access to buffers if that behavior is enabled at
// compile-time.
//
// A GLConsumer may be detached from one OpenGL ES context and then
// attached to a different context using the detachFromContext and
// attachToContext methods, respectively. The intention of these methods is
// purely to allow a GLConsumer to be transferred from one consumer
// context to another. If such a transfer is not needed there is no
// requirement that either of these methods be called.
//
// If the constructor with the tex parameter is used, the GLConsumer is
// created in a state where it is considered attached to an OpenGL ES
// context for the purposes of the attachToContext and detachFromContext
// methods. However, despite being considered "attached" to a context, the
// specific OpenGL ES context doesn't get latched until the first call to
// updateTexImage. After that point, all calls to updateTexImage must be
// made with the same OpenGL ES context current.
//
// If the constructor without the tex parameter is used, the GLConsumer is
// created in a detached state, and attachToContext must be called before
// calls to updateTexImage.
GLConsumer(const sp<IGraphicBufferConsumer>& bq,
uint32_t tex, uint32_t texureTarget, bool useFenceSync,
bool isControlledByApp);
GLConsumer(const sp<IGraphicBufferConsumer>& bq, uint32_t texureTarget,
bool useFenceSync, bool isControlledByApp);
// updateTexImage acquires the most recently queued buffer, and sets the
// image contents of the target texture to it.
//
// This call may only be made while the OpenGL ES context to which the
// target texture belongs is bound to the calling thread.
//
// This calls doGLFenceWait to ensure proper synchronization.
status_t updateTexImage();
// releaseTexImage releases the texture acquired in updateTexImage().
// This is intended to be used in single buffer mode.
//
// This call may only be made while the OpenGL ES context to which the
// target texture belongs is bound to the calling thread.
status_t releaseTexImage();
// setReleaseFence stores a fence that will signal when the current buffer
// is no longer being read. This fence will be returned to the producer
// when the current buffer is released by updateTexImage(). Multiple
// fences can be set for a given buffer; they will be merged into a single
// union fence.
void setReleaseFence(const sp<Fence>& fence);
// setDefaultMaxBufferCount sets the default limit on the maximum number
// of buffers that will be allocated at one time. The image producer may
// override the limit.
status_t setDefaultMaxBufferCount(int bufferCount);
// getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
// associated with the texture image set by the most recent call to
// updateTexImage.
//
// This transform matrix maps 2D homogeneous texture coordinates of the form
// (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
// coordinate that should be used to sample that location from the texture.
// Sampling the texture outside of the range of this transform is undefined.
//
// This transform is necessary to compensate for transforms that the stream
// content producer may implicitly apply to the content. By forcing users of
// a GLConsumer to apply this transform we avoid performing an extra
// copy of the data that would be needed to hide the transform from the
// user.
//
// The matrix is stored in column-major order so that it may be passed
// directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
// functions.
void getTransformMatrix(float mtx[16]);
// getTimestamp retrieves the timestamp associated with the texture image
// set by the most recent call to updateTexImage.
//
// The timestamp is in nanoseconds, and is monotonically increasing. Its
// other semantics (zero point, etc) are source-dependent and should be
// documented by the source.
int64_t getTimestamp();
// getFrameNumber retrieves the frame number associated with the texture
// image set by the most recent call to updateTexImage.
//
// The frame number is an incrementing counter set to 0 at the creation of
// the BufferQueue associated with this consumer.
uint64_t getFrameNumber();
// setDefaultBufferSize is used to set the size of buffers returned by
// requestBuffers when a with and height of zero is requested.
// A call to setDefaultBufferSize() may trigger requestBuffers() to
// be called from the client.
// The width and height parameters must be no greater than the minimum of
// GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
// An error due to invalid dimensions might not be reported until
// updateTexImage() is called.
status_t setDefaultBufferSize(uint32_t width, uint32_t height);
// setFilteringEnabled sets whether the transform matrix should be computed
// for use with bilinear filtering.
void setFilteringEnabled(bool enabled);
// getCurrentBuffer returns the buffer associated with the current image.
sp<GraphicBuffer> getCurrentBuffer() const;
// getCurrentTextureTarget returns the texture target of the current
// texture as returned by updateTexImage().
uint32_t getCurrentTextureTarget() const;
// getCurrentCrop returns the cropping rectangle of the current buffer.
Rect getCurrentCrop() const;
// getCurrentTransform returns the transform of the current buffer.
uint32_t getCurrentTransform() const;
// getCurrentScalingMode returns the scaling mode of the current buffer.
uint32_t getCurrentScalingMode() const;
// getCurrentFence returns the fence indicating when the current buffer is
// ready to be read from.
sp<Fence> getCurrentFence() const;
// doGLFenceWait inserts a wait command into the OpenGL ES command stream
// to ensure that it is safe for future OpenGL ES commands to access the
// current texture buffer.
status_t doGLFenceWait() const;
// set the name of the GLConsumer that will be used to identify it in
// log messages.
void setName(const String8& name);
// These functions call the corresponding BufferQueue implementation
// so the refactoring can proceed smoothly
status_t setDefaultBufferFormat(PixelFormat defaultFormat);
status_t setDefaultBufferDataSpace(android_dataspace defaultDataSpace);
status_t setConsumerUsageBits(uint32_t usage);
status_t setTransformHint(uint32_t hint);
// detachFromContext detaches the GLConsumer from the calling thread's
// current OpenGL ES context. This context must be the same as the context
// that was current for previous calls to updateTexImage.
//
// Detaching a GLConsumer from an OpenGL ES context will result in the
// deletion of the OpenGL ES texture object into which the images were being
// streamed. After a GLConsumer has been detached from the OpenGL ES
// context calls to updateTexImage will fail returning INVALID_OPERATION
// until the GLConsumer is attached to a new OpenGL ES context using the
// attachToContext method.
status_t detachFromContext();
// attachToContext attaches a GLConsumer that is currently in the
// 'detached' state to the current OpenGL ES context. A GLConsumer is
// in the 'detached' state iff detachFromContext has successfully been
// called and no calls to attachToContext have succeeded since the last
// detachFromContext call. Calls to attachToContext made on a
// GLConsumer that is not in the 'detached' state will result in an
// INVALID_OPERATION error.
//
// The tex argument specifies the OpenGL ES texture object name in the
// new context into which the image contents will be streamed. A successful
// call to attachToContext will result in this texture object being bound to
// the texture target and populated with the image contents that were
// current at the time of the last call to detachFromContext.
status_t attachToContext(uint32_t tex);
protected:
// abandonLocked overrides the ConsumerBase method to clear
// mCurrentTextureImage in addition to the ConsumerBase behavior.
virtual void abandonLocked();
// dumpLocked overrides the ConsumerBase method to dump GLConsumer-
// specific info in addition to the ConsumerBase behavior.
virtual void dumpLocked(String8& result, const char* prefix) const;
// acquireBufferLocked overrides the ConsumerBase method to update the
// mEglSlots array in addition to the ConsumerBase behavior.
virtual status_t acquireBufferLocked(BufferItem *item, nsecs_t presentWhen,
uint64_t maxFrameNumber = 0) override;
// releaseBufferLocked overrides the ConsumerBase method to update the
// mEglSlots array in addition to the ConsumerBase.
virtual status_t releaseBufferLocked(int slot,
const sp<GraphicBuffer> graphicBuffer,
EGLDisplay display, EGLSyncKHR eglFence);
status_t releaseBufferLocked(int slot,
const sp<GraphicBuffer> graphicBuffer, EGLSyncKHR eglFence) {
return releaseBufferLocked(slot, graphicBuffer, mEglDisplay, eglFence);
}
static bool isExternalFormat(PixelFormat format);
// This releases the buffer in the slot referenced by mCurrentTexture,
// then updates state to refer to the BufferItem, which must be a
// newly-acquired buffer.
status_t updateAndReleaseLocked(const BufferItem& item);
// Binds mTexName and the current buffer to mTexTarget. Uses
// mCurrentTexture if it's set, mCurrentTextureImage if not. If the
// bind succeeds, this calls doGLFenceWait.
status_t bindTextureImageLocked();
// Gets the current EGLDisplay and EGLContext values, and compares them
// to mEglDisplay and mEglContext. If the fields have been previously
// set, the values must match; if not, the fields are set to the current
// values.
// The contextCheck argument is used to ensure that a GL context is
// properly set; when set to false, the check is not performed.
status_t checkAndUpdateEglStateLocked(bool contextCheck = false);
private:
// EglImage is a utility class for tracking and creating EGLImageKHRs. There
// is primarily just one image per slot, but there is also special cases:
// - For releaseTexImage, we use a debug image (mReleasedTexImage)
// - After freeBuffer, we must still keep the current image/buffer
// Reference counting EGLImages lets us handle all these cases easily while
// also only creating new EGLImages from buffers when required.
class EglImage : public LightRefBase<EglImage> {
public:
EglImage(sp<GraphicBuffer> graphicBuffer);
// createIfNeeded creates an EGLImage if required (we haven't created
// one yet, or the EGLDisplay or crop-rect has changed).
status_t createIfNeeded(EGLDisplay display,
const Rect& cropRect,
bool forceCreate = false);
// This calls glEGLImageTargetTexture2DOES to bind the image to the
// texture in the specified texture target.
void bindToTextureTarget(uint32_t texTarget);
const sp<GraphicBuffer>& graphicBuffer() { return mGraphicBuffer; }
const native_handle* graphicBufferHandle() {
return mGraphicBuffer == NULL ? NULL : mGraphicBuffer->handle;
}
private:
// Only allow instantiation using ref counting.
friend class LightRefBase<EglImage>;
virtual ~EglImage();
// createImage creates a new EGLImage from a GraphicBuffer.
EGLImageKHR createImage(EGLDisplay dpy,
const sp<GraphicBuffer>& graphicBuffer, const Rect& crop);
// Disallow copying
EglImage(const EglImage& rhs);
void operator = (const EglImage& rhs);
// mGraphicBuffer is the buffer that was used to create this image.
sp<GraphicBuffer> mGraphicBuffer;
// mEglImage is the EGLImage created from mGraphicBuffer.
EGLImageKHR mEglImage;
// mEGLDisplay is the EGLDisplay that was used to create mEglImage.
EGLDisplay mEglDisplay;
// mCropRect is the crop rectangle passed to EGL when mEglImage
// was created.
Rect mCropRect;
};
// freeBufferLocked frees up the given buffer slot. If the slot has been
// initialized this will release the reference to the GraphicBuffer in that
// slot and destroy the EGLImage in that slot. Otherwise it has no effect.
//
// This method must be called with mMutex locked.
virtual void freeBufferLocked(int slotIndex);
// computeCurrentTransformMatrixLocked computes the transform matrix for the
// current texture. It uses mCurrentTransform and the current GraphicBuffer
// to compute this matrix and stores it in mCurrentTransformMatrix.
// mCurrentTextureImage must not be NULL.
void computeCurrentTransformMatrixLocked();
// doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
// stream to ensure that it is safe for future OpenGL ES commands to
// access the current texture buffer.
status_t doGLFenceWaitLocked() const;
// syncForReleaseLocked performs the synchronization needed to release the
// current slot from an OpenGL ES context. If needed it will set the
// current slot's fence to guard against a producer accessing the buffer
// before the outstanding accesses have completed.
status_t syncForReleaseLocked(EGLDisplay dpy);
// returns a graphic buffer used when the texture image has been released
static sp<GraphicBuffer> getDebugTexImageBuffer();
// The default consumer usage flags that GLConsumer always sets on its
// BufferQueue instance; these will be OR:d with any additional flags passed
// from the GLConsumer user. In particular, GLConsumer will always
// consume buffers as hardware textures.
static const uint32_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
// mCurrentTextureImage is the EglImage/buffer of the current texture. It's
// possible that this buffer is not associated with any buffer slot, so we
// must track it separately in order to support the getCurrentBuffer method.
sp<EglImage> mCurrentTextureImage;
// mCurrentCrop is the crop rectangle that applies to the current texture.
// It gets set each time updateTexImage is called.
Rect mCurrentCrop;
// mCurrentTransform is the transform identifier for the current texture. It
// gets set each time updateTexImage is called.
uint32_t mCurrentTransform;
// mCurrentScalingMode is the scaling mode for the current texture. It gets
// set each time updateTexImage is called.
uint32_t mCurrentScalingMode;
// mCurrentFence is the fence received from BufferQueue in updateTexImage.
sp<Fence> mCurrentFence;
// mCurrentTransformMatrix is the transform matrix for the current texture.
// It gets computed by computeTransformMatrix each time updateTexImage is
// called.
float mCurrentTransformMatrix[16];
// mCurrentTimestamp is the timestamp for the current texture. It
// gets set each time updateTexImage is called.
int64_t mCurrentTimestamp;
// mCurrentFrameNumber is the frame counter for the current texture.
// It gets set each time updateTexImage is called.
uint64_t mCurrentFrameNumber;
uint32_t mDefaultWidth, mDefaultHeight;
// mFilteringEnabled indicates whether the transform matrix is computed for
// use with bilinear filtering. It defaults to true and is changed by
// setFilteringEnabled().
bool mFilteringEnabled;
// mTexName is the name of the OpenGL texture to which streamed images will
// be bound when updateTexImage is called. It is set at construction time
// and can be changed with a call to attachToContext.
uint32_t mTexName;
// mUseFenceSync indicates whether creation of the EGL_KHR_fence_sync
// extension should be used to prevent buffers from being dequeued before
// it's safe for them to be written. It gets set at construction time and
// never changes.
const bool mUseFenceSync;
// mTexTarget is the GL texture target with which the GL texture object is
// associated. It is set in the constructor and never changed. It is
// almost always GL_TEXTURE_EXTERNAL_OES except for one use case in Android
// Browser. In that case it is set to GL_TEXTURE_2D to allow
// glCopyTexSubImage to read from the texture. This is a hack to work
// around a GL driver limitation on the number of FBO attachments, which the
// browser's tile cache exceeds.
const uint32_t mTexTarget;
// EGLSlot contains the information and object references that
// GLConsumer maintains about a BufferQueue buffer slot.
struct EglSlot {
EglSlot() : mEglFence(EGL_NO_SYNC_KHR) {}
// mEglImage is the EGLImage created from mGraphicBuffer.
sp<EglImage> mEglImage;
// mFence is the EGL sync object that must signal before the buffer
// associated with this buffer slot may be dequeued. It is initialized
// to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
// on a compile-time option) set to a new sync object in updateTexImage.
EGLSyncKHR mEglFence;
};
// mEglDisplay is the EGLDisplay with which this GLConsumer is currently
// associated. It is intialized to EGL_NO_DISPLAY and gets set to the
// current display when updateTexImage is called for the first time and when
// attachToContext is called.
EGLDisplay mEglDisplay;
// mEglContext is the OpenGL ES context with which this GLConsumer is
// currently associated. It is initialized to EGL_NO_CONTEXT and gets set
// to the current GL context when updateTexImage is called for the first
// time and when attachToContext is called.
EGLContext mEglContext;
// mEGLSlots stores the buffers that have been allocated by the BufferQueue
// for each buffer slot. It is initialized to null pointers, and gets
// filled in with the result of BufferQueue::acquire when the
// client dequeues a buffer from a
// slot that has not yet been used. The buffer allocated to a slot will also
// be replaced if the requested buffer usage or geometry differs from that
// of the buffer allocated to a slot.
EglSlot mEglSlots[BufferQueue::NUM_BUFFER_SLOTS];
// mCurrentTexture is the buffer slot index of the buffer that is currently
// bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
// indicating that no buffer slot is currently bound to the texture. Note,
// however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
// that no buffer is bound to the texture. A call to setBufferCount will
// reset mCurrentTexture to INVALID_BUFFER_SLOT.
int mCurrentTexture;
// mAttached indicates whether the ConsumerBase is currently attached to
// an OpenGL ES context. For legacy reasons, this is initialized to true,
// indicating that the ConsumerBase is considered to be attached to
// whatever context is current at the time of the first updateTexImage call.
// It is set to false by detachFromContext, and then set to true again by
// attachToContext.
bool mAttached;
// protects static initialization
static Mutex sStaticInitLock;
// mReleasedTexImageBuffer is a dummy buffer used when in single buffer
// mode and releaseTexImage() has been called
static sp<GraphicBuffer> sReleasedTexImageBuffer;
sp<EglImage> mReleasedTexImage;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_CONSUMER_H
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2012 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_SF_GRAPHIC_BUFFER_ALLOC_H
#define ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H
#include <stdint.h>
#include <sys/types.h>
#include <gui/IGraphicBufferAlloc.h>
#include <ui/PixelFormat.h>
#include <utils/Errors.h>
namespace android {
// ---------------------------------------------------------------------------
class GraphicBuffer;
class GraphicBufferAlloc : public BnGraphicBufferAlloc {
public:
GraphicBufferAlloc();
virtual ~GraphicBufferAlloc();
virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t width,
uint32_t height, PixelFormat format, uint32_t usage,
status_t* error);
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2012 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_CONFIG_H
#define ANDROID_GUI_CONFIG_H
#include <utils/String8.h>
namespace android {
// Append the libgui configuration details to configStr.
void appendGuiConfigString(String8& configStr);
}; // namespace android
#endif /*ANDROID_GUI_CONFIG_H*/
@@ -0,0 +1,104 @@
/*
* Copyright (C) 2013 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_ICONSUMERLISTENER_H
#define ANDROID_GUI_ICONSUMERLISTENER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
namespace android {
// ----------------------------------------------------------------------------
class BufferItem;
// ConsumerListener is the interface through which the BufferQueue notifies
// the consumer of events that the consumer may wish to react to. Because
// the consumer will generally have a mutex that is locked during calls from
// the consumer to the BufferQueue, these calls from the BufferQueue to the
// consumer *MUST* be called only when the BufferQueue mutex is NOT locked.
class ConsumerListener : public virtual RefBase {
public:
ConsumerListener() { }
virtual ~ConsumerListener() { }
// onFrameAvailable is called from queueBuffer each time an additional
// frame becomes available for consumption. This means that frames that
// are queued while in asynchronous mode only trigger the callback if no
// previous frames are pending. Frames queued while in synchronous mode
// always trigger the callback. The item passed to the callback will contain
// all of the information about the queued frame except for its
// GraphicBuffer pointer, which will always be null.
//
// This is called without any lock held and can be called concurrently
// by multiple threads.
virtual void onFrameAvailable(const BufferItem& item) = 0; /* Asynchronous */
// onFrameReplaced is called from queueBuffer if the frame being queued is
// replacing an existing slot in the queue. Any call to queueBuffer that
// doesn't call onFrameAvailable will call this callback instead. The item
// passed to the callback will contain all of the information about the
// queued frame except for its GraphicBuffer pointer, which will always be
// null.
//
// This is called without any lock held and can be called concurrently
// by multiple threads.
virtual void onFrameReplaced(const BufferItem& /* item */) {} /* Asynchronous */
// onBuffersReleased is called to notify the buffer consumer that the
// BufferQueue has released its references to one or more GraphicBuffers
// contained in its slots. The buffer consumer should then call
// BufferQueue::getReleasedBuffers to retrieve the list of buffers
//
// This is called without any lock held and can be called concurrently
// by multiple threads.
virtual void onBuffersReleased() = 0; /* Asynchronous */
// onSidebandStreamChanged is called to notify the buffer consumer that the
// BufferQueue's sideband buffer stream has changed. This is called when a
// stream is first attached and when it is either detached or replaced by a
// different stream.
virtual void onSidebandStreamChanged() = 0; /* Asynchronous */
};
class IConsumerListener : public ConsumerListener, public IInterface
{
public:
DECLARE_META_INTERFACE(ConsumerListener);
};
// ----------------------------------------------------------------------------
class BnConsumerListener : public BnInterface<IConsumerListener>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_ICONSUMERLISTENER_H
@@ -0,0 +1,73 @@
/*
* Copyright (C) 2011 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_IDISPLAY_EVENT_CONNECTION_H
#define ANDROID_GUI_IDISPLAY_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 BitTube;
class IDisplayEventConnection : public IInterface
{
public:
DECLARE_META_INTERFACE(DisplayEventConnection);
/*
* getDataChannel() returns a BitTube where to receive the events from
*/
virtual sp<BitTube> getDataChannel() const = 0;
/*
* setVsyncRate() sets the vsync event delivery rate. A value of
* 1 returns every vsync events. A value of 2 returns every other events,
* etc... a value of 0 returns no event unless requestNextVsync() has
* been called.
*/
virtual void setVsyncRate(uint32_t count) = 0;
/*
* requestNextVsync() schedules the next vsync event. It has no effect
* if the vsync rate is > 0.
*/
virtual void requestNextVsync() = 0; // asynchronous
};
// ----------------------------------------------------------------------------
class BnDisplayEventConnection : public BnInterface<IDisplayEventConnection>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_IDISPLAY_EVENT_CONNECTION_H
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2011 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_IGRAPHIC_BUFFER_ALLOC_H
#define ANDROID_GUI_IGRAPHIC_BUFFER_ALLOC_H
#include <stdint.h>
#include <sys/types.h>
#include <binder/IInterface.h>
#include <ui/PixelFormat.h>
#include <utils/RefBase.h>
namespace android {
// ----------------------------------------------------------------------------
class GraphicBuffer;
class IGraphicBufferAlloc : public IInterface
{
public:
DECLARE_META_INTERFACE(GraphicBufferAlloc);
/* Create a new GraphicBuffer for the client to use.
*/
virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
PixelFormat format, uint32_t usage, status_t* error) = 0;
};
// ----------------------------------------------------------------------------
class BnGraphicBufferAlloc : public BnInterface<IGraphicBufferAlloc>
{
public:
virtual status_t onTransact(uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_IGRAPHIC_BUFFER_ALLOC_H
@@ -0,0 +1,280 @@
/*
* Copyright (C) 2013 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_IGRAPHICBUFFERCONSUMER_H
#define ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/Timers.h>
#include <binder/IInterface.h>
#include <ui/PixelFormat.h>
#include <ui/Rect.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
namespace android {
// ----------------------------------------------------------------------------
class BufferItem;
class Fence;
class GraphicBuffer;
class IConsumerListener;
class NativeHandle;
class IGraphicBufferConsumer : public IInterface {
public:
enum {
// Returned by releaseBuffer, after which the consumer must
// free any references to the just-released buffer that it might have.
STALE_BUFFER_SLOT = 1,
// Returned by dequeueBuffer if there are no pending buffers available.
NO_BUFFER_AVAILABLE,
// Returned by dequeueBuffer if it's too early for the buffer to be acquired.
PRESENT_LATER,
};
// acquireBuffer attempts to acquire ownership of the next pending buffer in
// the BufferQueue. If no buffer is pending then it returns
// NO_BUFFER_AVAILABLE. If a buffer is successfully acquired, the
// information about the buffer is returned in BufferItem.
//
// If the buffer returned had previously been
// acquired then the BufferItem::mGraphicBuffer field of buffer is set to
// NULL and it is assumed that the consumer still holds a reference to the
// buffer.
//
// If presentWhen is non-zero, it indicates the time when the buffer will
// be displayed on screen. If the buffer's timestamp is farther in the
// future, the buffer won't be acquired, and PRESENT_LATER will be
// returned. The presentation time is in nanoseconds, and the time base
// is CLOCK_MONOTONIC.
//
// If maxFrameNumber is non-zero, it indicates that acquireBuffer should
// only return a buffer with a frame number less than or equal to
// maxFrameNumber. If no such frame is available (such as when a buffer has
// been replaced but the consumer has not received the onFrameReplaced
// callback), then PRESENT_LATER will be returned.
//
// Return of NO_ERROR means the operation completed as normal.
//
// Return of a positive value means the operation could not be completed
// at this time, but the user should try again later:
// * NO_BUFFER_AVAILABLE - no buffer is pending (nothing queued by producer)
// * PRESENT_LATER - the buffer's timestamp is farther in the future
//
// Return of a negative value means an error has occurred:
// * INVALID_OPERATION - too many buffers have been acquired
virtual status_t acquireBuffer(BufferItem* buffer, nsecs_t presentWhen,
uint64_t maxFrameNumber = 0) = 0;
// detachBuffer attempts to remove all ownership of the buffer in the given
// slot from the buffer queue. If this call succeeds, the slot will be
// freed, and there will be no way to obtain the buffer from this interface.
// The freed slot will remain unallocated until either it is selected to
// hold a freshly allocated buffer in dequeueBuffer or a buffer is attached
// to the slot. The buffer must have already been acquired.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - the given slot number is invalid, either because it is
// out of the range [0, NUM_BUFFER_SLOTS) or because the slot
// it refers to is not currently acquired.
virtual status_t detachBuffer(int slot) = 0;
// attachBuffer attempts to transfer ownership of a buffer to the buffer
// queue. If this call succeeds, it will be as if this buffer was acquired
// from the returned slot number. As such, this call will fail if attaching
// this buffer would cause too many buffers to be simultaneously acquired.
//
// If the buffer is successfully attached, its frameNumber is initialized
// to 0. This must be passed into the releaseBuffer call or else the buffer
// will be deallocated as stale.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - outSlot or buffer were NULL, or the generation number of
// the buffer did not match the buffer queue.
// * INVALID_OPERATION - cannot attach the buffer because it would cause too
// many buffers to be acquired.
// * NO_MEMORY - no free slots available
virtual status_t attachBuffer(int *outSlot,
const sp<GraphicBuffer>& buffer) = 0;
// releaseBuffer releases a buffer slot from the consumer back to the
// BufferQueue. This may be done while the buffer's contents are still
// being accessed. The fence will signal when the buffer is no longer
// in use. frameNumber is used to indentify the exact buffer returned.
//
// If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
// any references to the just-released buffer that it might have, as if it
// had received a onBuffersReleased() call with a mask set for the released
// buffer.
//
// Note that the dependencies on EGL will be removed once we switch to using
// the Android HW Sync HAL.
//
// Return of NO_ERROR means the operation completed as normal.
//
// Return of a positive value means the operation could not be completed
// at this time, but the user should try again later:
// * STALE_BUFFER_SLOT - see above (second paragraph)
//
// Return of a negative value means an error has occurred:
// * BAD_VALUE - one of the following could've happened:
// * the buffer slot was invalid
// * the fence was NULL
// * the buffer slot specified is not in the acquired state
virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
EGLDisplay display, EGLSyncKHR fence,
const sp<Fence>& releaseFence) = 0;
// consumerConnect connects a consumer to the BufferQueue. Only one
// consumer may be connected, and when that consumer disconnects the
// BufferQueue is placed into the "abandoned" state, causing most
// interactions with the BufferQueue by the producer to fail.
// controlledByApp indicates whether the consumer is controlled by
// the application.
//
// consumer may not be NULL.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned
// * BAD_VALUE - a NULL consumer was provided
virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) = 0;
// consumerDisconnect disconnects a consumer from the BufferQueue. All
// buffers will be freed and the BufferQueue is placed in the "abandoned"
// state, causing most interactions with the BufferQueue by the producer to
// fail.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - no consumer is currently connected
virtual status_t consumerDisconnect() = 0;
// getReleasedBuffers sets the value pointed to by slotMask to a bit set.
// Each bit index with a 1 corresponds to a released buffer slot with that
// index value. In particular, a released buffer is one that has
// been released by the BufferQueue but have not yet been released by the consumer.
//
// This should be called from the onBuffersReleased() callback.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
virtual status_t getReleasedBuffers(uint64_t* slotMask) = 0;
// setDefaultBufferSize is used to set the size of buffers returned by
// dequeueBuffer when a width and height of zero is requested. Default
// is 1x1.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - either w or h was zero
virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) = 0;
// setDefaultMaxBufferCount sets the default value for the maximum buffer
// count (the initial default is 2). If the producer has requested a
// buffer count using setBufferCount, the default buffer count will only
// take effect if the producer sets the count back to zero.
//
// The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - bufferCount was out of range (see above).
virtual status_t setDefaultMaxBufferCount(int bufferCount) = 0;
// disableAsyncBuffer disables the extra buffer used in async mode
// (when both producer and consumer have set their "isControlledByApp"
// flag) and has dequeueBuffer() return WOULD_BLOCK instead.
//
// This can only be called before consumerConnect().
//
// Return of a value other than NO_ERROR means an error has occurred:
// * INVALID_OPERATION - attempting to call this after consumerConnect.
virtual status_t disableAsyncBuffer() = 0;
// setMaxAcquiredBufferCount sets the maximum number of buffers that can
// be acquired by the consumer at one time (default 1). This call will
// fail if a producer is connected to the BufferQueue.
//
// maxAcquiredBuffers must be (inclusive) between 1 and MAX_MAX_ACQUIRED_BUFFERS.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - maxAcquiredBuffers was out of range (see above).
// * INVALID_OPERATION - attempting to call this after a producer connected.
virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) = 0;
// setConsumerName sets the name used in logging
virtual void setConsumerName(const String8& name) = 0;
// setDefaultBufferFormat allows the BufferQueue to create
// GraphicBuffers of a defaultFormat if no format is specified
// in dequeueBuffer.
// The initial default is PIXEL_FORMAT_RGBA_8888.
//
// Return of a value other than NO_ERROR means an unknown error has occurred.
virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat) = 0;
// setDefaultBufferDataSpace is a request to the producer to provide buffers
// of the indicated dataSpace. The producer may ignore this request.
// The initial default is HAL_DATASPACE_UNKNOWN.
//
// Return of a value other than NO_ERROR means an unknown error has occurred.
virtual status_t setDefaultBufferDataSpace(
android_dataspace defaultDataSpace) = 0;
// setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
// These are merged with the bits passed to dequeueBuffer. The values are
// enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
//
// Return of a value other than NO_ERROR means an unknown error has occurred.
virtual status_t setConsumerUsageBits(uint32_t usage) = 0;
// setTransformHint bakes in rotation to buffers so overlays can be used.
// The values are enumerated in window.h, e.g.
// NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
//
// Return of a value other than NO_ERROR means an unknown error has occurred.
virtual status_t setTransformHint(uint32_t hint) = 0;
// Retrieve the sideband buffer stream, if any.
virtual sp<NativeHandle> getSidebandStream() const = 0;
// dump state into a string
virtual void dump(String8& result, const char* prefix) const = 0;
public:
DECLARE_META_INTERFACE(GraphicBufferConsumer);
};
// ----------------------------------------------------------------------------
class BnGraphicBufferConsumer : public BnInterface<IGraphicBufferConsumer>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H
@@ -0,0 +1,502 @@
/*
* 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_IGRAPHICBUFFERPRODUCER_H
#define ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <ui/Fence.h>
#include <ui/GraphicBuffer.h>
#include <ui/Rect.h>
#include <ui/Region.h>
namespace android {
// ----------------------------------------------------------------------------
class IProducerListener;
class NativeHandle;
class Surface;
/*
* This class defines the Binder IPC interface for the producer side of
* a queue of graphics buffers. It's used to send graphics data from one
* component to another. For example, a class that decodes video for
* playback might use this to provide frames. This is typically done
* indirectly, through Surface.
*
* The underlying mechanism is a BufferQueue, which implements
* BnGraphicBufferProducer. In normal operation, the producer calls
* dequeueBuffer() to get an empty buffer, fills it with data, then
* calls queueBuffer() to make it available to the consumer.
*
* This class was previously called ISurfaceTexture.
*/
class IGraphicBufferProducer : public IInterface
{
public:
DECLARE_META_INTERFACE(GraphicBufferProducer);
enum {
// A flag returned by dequeueBuffer when the client needs to call
// requestBuffer immediately thereafter.
BUFFER_NEEDS_REALLOCATION = 0x1,
// A flag returned by dequeueBuffer when all mirrored slots should be
// released by the client. This flag should always be processed first.
RELEASE_ALL_BUFFERS = 0x2,
};
// requestBuffer requests a new buffer for the given index. The server (i.e.
// the IGraphicBufferProducer implementation) assigns the newly created
// buffer to the given slot index, and the client is expected to mirror the
// slot->buffer mapping so that it's not necessary to transfer a
// GraphicBuffer for every dequeue operation.
//
// The slot must be in the range of [0, NUM_BUFFER_SLOTS).
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - one of the two conditions occurred:
// * slot was out of range (see above)
// * buffer specified by the slot is not dequeued
virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf) = 0;
// setBufferCount sets the number of buffer slots available. Calling this
// will also cause all buffer slots to be emptied. The caller should empty
// its mirrored copy of the buffer slots when calling this method.
//
// This function should not be called when there are any dequeued buffer
// slots, doing so will result in a BAD_VALUE error returned.
//
// The buffer count should be at most NUM_BUFFER_SLOTS (inclusive), but at least
// the minimum undequeued buffer count (exclusive). The minimum value
// can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS).
// In particular the range is (minUndequeudBuffers, NUM_BUFFER_SLOTS].
//
// The buffer count may also be set to 0 (the default), to indicate that
// the producer does not wish to set a value.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - one of the below conditions occurred:
// * bufferCount was out of range (see above)
// * client has one or more buffers dequeued
virtual status_t setBufferCount(int bufferCount) = 0;
// dequeueBuffer requests a new buffer slot for the client to use. Ownership
// of the slot is transfered to the client, meaning that the server will not
// use the contents of the buffer associated with that slot.
//
// The slot index returned may or may not contain a buffer (client-side).
// If the slot is empty the client should call requestBuffer to assign a new
// buffer to that slot.
//
// Once the client is done filling this buffer, it is expected to transfer
// buffer ownership back to the server with either cancelBuffer on
// the dequeued slot or to fill in the contents of its associated buffer
// contents and call queueBuffer.
//
// If dequeueBuffer returns the BUFFER_NEEDS_REALLOCATION flag, the client is
// expected to call requestBuffer immediately.
//
// If dequeueBuffer returns the RELEASE_ALL_BUFFERS flag, the client is
// expected to release all of the mirrored slot->buffer mappings.
//
// The fence parameter will be updated to hold the fence associated with
// the buffer. The contents of the buffer must not be overwritten until the
// fence signals. If the fence is Fence::NO_FENCE, the buffer may be written
// immediately.
//
// The async parameter sets whether we're in asynchronous mode for this
// dequeueBuffer() call.
//
// The width and height parameters must be no greater than the minimum of
// GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
// An error due to invalid dimensions might not be reported until
// updateTexImage() is called. If width and height are both zero, the
// default values specified by setDefaultBufferSize() are used instead.
//
// If the format is 0, the default format will be used.
//
// The usage argument specifies gralloc buffer usage flags. The values
// are enumerated in <gralloc.h>, e.g. GRALLOC_USAGE_HW_RENDER. These
// will be merged with the usage flags specified by
// IGraphicBufferConsumer::setConsumerUsageBits.
//
// This call will block until a buffer is available to be dequeued. If
// both the producer and consumer are controlled by the app, then this call
// can never block and will return WOULD_BLOCK if no buffer is available.
//
// A non-negative value with flags set (see above) will be returned upon
// success.
//
// Return of a negative means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - both in async mode and buffer count was less than the
// max numbers of buffers that can be allocated at once.
// * INVALID_OPERATION - cannot attach the buffer because it would cause
// too many buffers to be dequeued, either because
// the producer already has a single buffer dequeued
// and did not set a buffer count, or because a
// buffer count was set and this call would cause
// it to be exceeded.
// * WOULD_BLOCK - no buffer is currently available, and blocking is disabled
// since both the producer/consumer are controlled by app
// * NO_MEMORY - out of memory, cannot allocate the graphics buffer.
//
// All other negative values are an unknown error returned downstream
// from the graphics allocator (typically errno).
virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, bool async,
uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) = 0;
// detachBuffer attempts to remove all ownership of the buffer in the given
// slot from the buffer queue. If this call succeeds, the slot will be
// freed, and there will be no way to obtain the buffer from this interface.
// The freed slot will remain unallocated until either it is selected to
// hold a freshly allocated buffer in dequeueBuffer or a buffer is attached
// to the slot. The buffer must have already been dequeued, and the caller
// must already possesses the sp<GraphicBuffer> (i.e., must have called
// requestBuffer).
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - the given slot number is invalid, either because it is
// out of the range [0, NUM_BUFFER_SLOTS), or because the slot
// it refers to is not currently dequeued and requested.
virtual status_t detachBuffer(int slot) = 0;
// detachNextBuffer is equivalent to calling dequeueBuffer, requestBuffer,
// and detachBuffer in sequence, except for two things:
//
// 1) It is unnecessary to know the dimensions, format, or usage of the
// next buffer.
// 2) It will not block, since if it cannot find an appropriate buffer to
// return, it will return an error instead.
//
// Only slots that are free but still contain a GraphicBuffer will be
// considered, and the oldest of those will be returned. outBuffer is
// equivalent to outBuffer from the requestBuffer call, and outFence is
// equivalent to fence from the dequeueBuffer call.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - either outBuffer or outFence were NULL.
// * NO_MEMORY - no slots were found that were both free and contained a
// GraphicBuffer.
virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
sp<Fence>* outFence) = 0;
// attachBuffer attempts to transfer ownership of a buffer to the buffer
// queue. If this call succeeds, it will be as if this buffer was dequeued
// from the returned slot number. As such, this call will fail if attaching
// this buffer would cause too many buffers to be simultaneously dequeued.
//
// If attachBuffer returns the RELEASE_ALL_BUFFERS flag, the caller is
// expected to release all of the mirrored slot->buffer mappings.
//
// A non-negative value with flags set (see above) will be returned upon
// success.
//
// Return of a negative value means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - outSlot or buffer were NULL, invalid combination of
// async mode and buffer count override, or the generation
// number of the buffer did not match the buffer queue.
// * INVALID_OPERATION - cannot attach the buffer because it would cause
// too many buffers to be dequeued, either because
// the producer already has a single buffer dequeued
// and did not set a buffer count, or because a
// buffer count was set and this call would cause
// it to be exceeded.
// * WOULD_BLOCK - no buffer slot is currently available, and blocking is
// disabled since both the producer/consumer are
// controlled by the app.
virtual status_t attachBuffer(int* outSlot,
const sp<GraphicBuffer>& buffer) = 0;
// queueBuffer indicates that the client has finished filling in the
// contents of the buffer associated with slot and transfers ownership of
// that slot back to the server.
//
// It is not valid to call queueBuffer on a slot that is not owned
// by the client or one for which a buffer associated via requestBuffer
// (an attempt to do so will fail with a return value of BAD_VALUE).
//
// In addition, the input must be described by the client (as documented
// below). Any other properties (zero point, etc)
// are client-dependent, and should be documented by the client.
//
// The slot must be in the range of [0, NUM_BUFFER_SLOTS).
//
// Upon success, the output will be filled with meaningful values
// (refer to the documentation below).
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - one of the below conditions occurred:
// * fence was NULL
// * scaling mode was unknown
// * both in async mode and buffer count was less than the
// max numbers of buffers that can be allocated at once
// * slot index was out of range (see above).
// * the slot was not in the dequeued state
// * the slot was enqueued without requesting a buffer
// * crop rect is out of bounds of the buffer dimensions
struct QueueBufferInput : public Flattenable<QueueBufferInput> {
friend class Flattenable<QueueBufferInput>;
inline QueueBufferInput(const Parcel& parcel);
// timestamp - a monotonically increasing value in nanoseconds
// isAutoTimestamp - if the timestamp was synthesized at queue time
// dataSpace - description of the contents, interpretation depends on format
// crop - a crop rectangle that's used as a hint to the consumer
// scalingMode - a set of flags from NATIVE_WINDOW_SCALING_* in <window.h>
// transform - a set of flags from NATIVE_WINDOW_TRANSFORM_* in <window.h>
// async - if the buffer is queued in asynchronous mode
// fence - a fence that the consumer must wait on before reading the buffer,
// set this to Fence::NO_FENCE if the buffer is ready immediately
// sticky - the sticky transform set in Surface (only used by the LEGACY
// camera mode).
inline QueueBufferInput(int64_t timestamp, bool isAutoTimestamp,
android_dataspace dataSpace, const Rect& crop, int scalingMode,
uint32_t transform, bool async, const sp<Fence>& fence,
uint32_t sticky = 0)
: timestamp(timestamp), isAutoTimestamp(isAutoTimestamp),
dataSpace(dataSpace), crop(crop), scalingMode(scalingMode),
transform(transform), stickyTransform(sticky),
async(async), fence(fence), surfaceDamage() { }
inline void deflate(int64_t* outTimestamp, bool* outIsAutoTimestamp,
android_dataspace* outDataSpace,
Rect* outCrop, int* outScalingMode,
uint32_t* outTransform, bool* outAsync, sp<Fence>* outFence,
uint32_t* outStickyTransform = NULL) const {
*outTimestamp = timestamp;
*outIsAutoTimestamp = bool(isAutoTimestamp);
*outDataSpace = dataSpace;
*outCrop = crop;
*outScalingMode = scalingMode;
*outTransform = transform;
*outAsync = bool(async);
*outFence = fence;
if (outStickyTransform != NULL) {
*outStickyTransform = stickyTransform;
}
}
// Flattenable protocol
size_t getFlattenedSize() const;
size_t getFdCount() const;
status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
const Region& getSurfaceDamage() const { return surfaceDamage; }
void setSurfaceDamage(const Region& damage) { surfaceDamage = damage; }
private:
int64_t timestamp;
int isAutoTimestamp;
android_dataspace dataSpace;
Rect crop;
int scalingMode;
uint32_t transform;
uint32_t stickyTransform;
int async;
sp<Fence> fence;
Region surfaceDamage;
};
// QueueBufferOutput must be a POD structure
struct __attribute__ ((__packed__)) QueueBufferOutput {
inline QueueBufferOutput() { }
// outWidth - filled with default width applied to the buffer
// outHeight - filled with default height applied to the buffer
// outTransformHint - filled with default transform applied to the buffer
// outNumPendingBuffers - num buffers queued that haven't yet been acquired
// (counting the currently queued buffer)
inline void deflate(uint32_t* outWidth,
uint32_t* outHeight,
uint32_t* outTransformHint,
uint32_t* outNumPendingBuffers) const {
*outWidth = width;
*outHeight = height;
*outTransformHint = transformHint;
*outNumPendingBuffers = numPendingBuffers;
}
inline void inflate(uint32_t inWidth, uint32_t inHeight,
uint32_t inTransformHint, uint32_t inNumPendingBuffers) {
width = inWidth;
height = inHeight;
transformHint = inTransformHint;
numPendingBuffers = inNumPendingBuffers;
}
private:
uint32_t width;
uint32_t height;
uint32_t transformHint;
uint32_t numPendingBuffers;
};
virtual status_t queueBuffer(int slot,
const QueueBufferInput& input, QueueBufferOutput* output) = 0;
// cancelBuffer indicates that the client does not wish to fill in the
// buffer associated with slot and transfers ownership of the slot back to
// the server.
//
// The buffer is not queued for use by the consumer.
//
// The buffer will not be overwritten until the fence signals. The fence
// will usually be the one obtained from dequeueBuffer.
virtual void cancelBuffer(int slot, const sp<Fence>& fence) = 0;
// query retrieves some information for this surface
// 'what' tokens allowed are that of NATIVE_WINDOW_* in <window.h>
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - the buffer queue has been abandoned.
// * BAD_VALUE - what was out of range
virtual int query(int what, int* value) = 0;
// connect attempts to connect a client API to the IGraphicBufferProducer.
// This must be called before any other IGraphicBufferProducer methods are
// called except for getAllocator. A consumer must be already connected.
//
// This method will fail if the connect was previously called on the
// IGraphicBufferProducer and no corresponding disconnect call was made.
//
// The listener is an optional binder callback object that can be used if
// the producer wants to be notified when the consumer releases a buffer
// back to the BufferQueue. It is also used to detect the death of the
// producer. If only the latter functionality is desired, there is a
// DummyProducerListener class in IProducerListener.h that can be used.
//
// The api should be one of the NATIVE_WINDOW_API_* values in <window.h>
//
// The producerControlledByApp should be set to true if the producer is hosted
// by an untrusted process (typically app_process-forked processes). If both
// the producer and the consumer are app-controlled then all buffer queues
// will operate in async mode regardless of the async flag.
//
// Upon success, the output will be filled with meaningful data
// (refer to QueueBufferOutput documentation above).
//
// Return of a value other than NO_ERROR means an error has occurred:
// * NO_INIT - one of the following occurred:
// * the buffer queue was abandoned
// * no consumer has yet connected
// * BAD_VALUE - one of the following has occurred:
// * the producer is already connected
// * api was out of range (see above).
// * output was NULL.
// * DEAD_OBJECT - the token is hosted by an already-dead process
//
// Additional negative errors may be returned by the internals, they
// should be treated as opaque fatal unrecoverable errors.
virtual status_t connect(const sp<IProducerListener>& listener,
int api, bool producerControlledByApp, QueueBufferOutput* output) = 0;
// disconnect attempts to disconnect a client API from the
// IGraphicBufferProducer. Calling this method will cause any subsequent
// calls to other IGraphicBufferProducer methods to fail except for
// getAllocator and connect. Successfully calling connect after this will
// allow the other methods to succeed again.
//
// This method will fail if the the IGraphicBufferProducer is not currently
// connected to the specified client API.
//
// The api should be one of the NATIVE_WINDOW_API_* values in <window.h>
//
// Disconnecting from an abandoned IGraphicBufferProducer is legal and
// is considered a no-op.
//
// Return of a value other than NO_ERROR means an error has occurred:
// * BAD_VALUE - one of the following has occurred:
// * the api specified does not match the one that was connected
// * api was out of range (see above).
// * DEAD_OBJECT - the token is hosted by an already-dead process
virtual status_t disconnect(int api) = 0;
// Attaches a sideband buffer stream to the IGraphicBufferProducer.
//
// A sideband stream is a device-specific mechanism for passing buffers
// from the producer to the consumer without using dequeueBuffer/
// queueBuffer. If a sideband stream is present, the consumer can choose
// whether to acquire buffers from the sideband stream or from the queued
// buffers.
//
// Passing NULL or a different stream handle will detach the previous
// handle if any.
virtual status_t setSidebandStream(const sp<NativeHandle>& stream) = 0;
// Allocates buffers based on the given dimensions/format.
//
// This function will allocate up to the maximum number of buffers
// permitted by the current BufferQueue configuration. It will use the
// given format, dimensions, and usage bits, which are interpreted in the
// same way as for dequeueBuffer, and the async flag must be set the same
// way as for dequeueBuffer to ensure that the correct number of buffers are
// allocated. This is most useful to avoid an allocation delay during
// dequeueBuffer. If there are already the maximum number of buffers
// allocated, this function has no effect.
virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
PixelFormat format, uint32_t usage) = 0;
// Sets whether dequeueBuffer is allowed to allocate new buffers.
//
// Normally dequeueBuffer does not discriminate between free slots which
// already have an allocated buffer and those which do not, and will
// allocate a new buffer if the slot doesn't have a buffer or if the slot's
// buffer doesn't match the requested size, format, or usage. This method
// allows the producer to restrict the eligible slots to those which already
// have an allocated buffer of the correct size, format, and usage. If no
// eligible slot is available, dequeueBuffer will block or return an error
// as usual.
virtual status_t allowAllocation(bool allow) = 0;
// Sets the current generation number of the BufferQueue.
//
// This generation number will be inserted into any buffers allocated by the
// BufferQueue, and any attempts to attach a buffer with a different
// generation number will fail. Buffers already in the queue are not
// affected and will retain their current generation number. The generation
// number defaults to 0.
virtual status_t setGenerationNumber(uint32_t generationNumber) = 0;
// Returns the name of the connected consumer.
virtual String8 getConsumerName() const = 0;
};
// ----------------------------------------------------------------------------
class BnGraphicBufferProducer : public BnInterface<IGraphicBufferProducer>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H
@@ -0,0 +1,67 @@
/*
* Copyright 2014 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_IPRODUCERLISTENER_H
#define ANDROID_GUI_IPRODUCERLISTENER_H
#include <binder/IInterface.h>
#include <utils/RefBase.h>
namespace android {
// ProducerListener is the interface through which the BufferQueue notifies the
// producer of events that the producer may wish to react to. Because the
// producer will generally have a mutex that is locked during calls from the
// producer to the BufferQueue, these calls from the BufferQueue to the
// producer *MUST* be called only when the BufferQueue mutex is NOT locked.
class ProducerListener : public virtual RefBase
{
public:
ProducerListener() {}
virtual ~ProducerListener() {}
// onBufferReleased is called from IGraphicBufferConsumer::releaseBuffer to
// notify the producer that a new buffer is free and ready to be dequeued.
//
// This is called without any lock held and can be called concurrently by
// multiple threads.
virtual void onBufferReleased() = 0; // Asynchronous
};
class IProducerListener : public ProducerListener, public IInterface
{
public:
DECLARE_META_INTERFACE(ProducerListener)
};
class BnProducerListener : public BnInterface<IProducerListener>
{
public:
virtual status_t onTransact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0);
};
class DummyProducerListener : public BnProducerListener
{
public:
virtual void onBufferReleased() {}
};
} // namespace android
#endif
@@ -0,0 +1,59 @@
/*
* 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 BitTube;
class ISensorEventConnection : public IInterface
{
public:
DECLARE_META_INTERFACE(SensorEventConnection);
virtual sp<BitTube> getSensorChannel() const = 0;
virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs,
nsecs_t maxBatchReportLatencyNs, int reservedFlags) = 0;
virtual status_t setEventRate(int handle, nsecs_t ns) = 0;
virtual status_t flush() = 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
@@ -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_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 String8;
class ISensorServer : public IInterface
{
public:
DECLARE_META_INTERFACE(SensorServer);
virtual Vector<Sensor> getSensorList(const String16& opPackageName) = 0;
virtual sp<ISensorEventConnection> createSensorEventConnection(const String8& packageName,
int mode, const String16& opPackageName) = 0;
virtual int32_t isDataInjectionEnabled() = 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
@@ -0,0 +1,201 @@
/*
* Copyright (C) 2006 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_ISURFACE_COMPOSER_H
#define ANDROID_GUI_ISURFACE_COMPOSER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <utils/Timers.h>
#include <utils/Vector.h>
#include <binder/IInterface.h>
#include <ui/FrameStats.h>
#include <gui/IGraphicBufferAlloc.h>
#include <gui/ISurfaceComposerClient.h>
namespace android {
// ----------------------------------------------------------------------------
class ComposerState;
class DisplayState;
struct DisplayInfo;
struct DisplayStatInfo;
class IDisplayEventConnection;
class IMemoryHeap;
class Rect;
/*
* This class defines the Binder IPC interface for accessing various
* SurfaceFlinger features.
*/
class ISurfaceComposer: public IInterface {
public:
DECLARE_META_INTERFACE(SurfaceComposer);
// flags for setTransactionState()
enum {
eSynchronous = 0x01,
eAnimation = 0x02,
};
enum {
eDisplayIdMain = 0,
eDisplayIdHdmi = 1,
#ifdef QTI_BSP
eDisplayIdTertiary = 2
#endif
};
enum Rotation {
eRotateNone = 0,
eRotate90 = 1,
eRotate180 = 2,
eRotate270 = 3
};
/* create connection with surface flinger, requires
* ACCESS_SURFACE_FLINGER permission
*/
virtual sp<ISurfaceComposerClient> createConnection() = 0;
/* create a graphic buffer allocator
*/
virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc() = 0;
/* return an IDisplayEventConnection */
virtual sp<IDisplayEventConnection> createDisplayEventConnection() = 0;
/* create a virtual display
* requires ACCESS_SURFACE_FLINGER permission.
*/
virtual sp<IBinder> createDisplay(const String8& displayName,
bool secure) = 0;
/* destroy a virtual display
* requires ACCESS_SURFACE_FLINGER permission.
*/
virtual void destroyDisplay(const sp<IBinder>& display) = 0;
/* get the token for the existing default displays. possible values
* for id are eDisplayIdMain and eDisplayIdHdmi.
*/
virtual sp<IBinder> getBuiltInDisplay(int32_t id) = 0;
/* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */
virtual void setTransactionState(const Vector<ComposerState>& state,
const Vector<DisplayState>& displays, uint32_t flags) = 0;
/* signal that we're done booting.
* Requires ACCESS_SURFACE_FLINGER permission
*/
virtual void bootFinished() = 0;
/* verify that an IGraphicBufferProducer was created by SurfaceFlinger.
*/
virtual bool authenticateSurfaceTexture(
const sp<IGraphicBufferProducer>& surface) const = 0;
/* set display power mode. depending on the mode, it can either trigger
* screen on, off or low power mode and wait for it to complete.
* requires ACCESS_SURFACE_FLINGER permission.
*/
virtual void setPowerMode(const sp<IBinder>& display, int mode) = 0;
/* returns information for each configuration of the given display
* intended to be used to get information about built-in displays */
virtual status_t getDisplayConfigs(const sp<IBinder>& display,
Vector<DisplayInfo>* configs) = 0;
/* returns display statistics for a given display
* intended to be used by the media framework to properly schedule
* video frames */
virtual status_t getDisplayStats(const sp<IBinder>& display,
DisplayStatInfo* stats) = 0;
/* indicates which of the configurations returned by getDisplayInfo is
* currently active */
virtual int getActiveConfig(const sp<IBinder>& display) = 0;
/* specifies which configuration (of those returned by getDisplayInfo)
* should be used */
virtual status_t setActiveConfig(const sp<IBinder>& display, int id) = 0;
/* Capture the specified screen. requires READ_FRAME_BUFFER permission
* This function will fail if there is a secure window on screen.
*/
virtual status_t captureScreen(const sp<IBinder>& display,
const sp<IGraphicBufferProducer>& producer,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ,
bool useIdentityTransform,
Rotation rotation = eRotateNone,
bool isCpuConsumer = false) = 0;
/* Clears the frame statistics for animations.
*
* Requires the ACCESS_SURFACE_FLINGER permission.
*/
virtual status_t clearAnimationFrameStats() = 0;
/* Gets the frame statistics for animations.
*
* Requires the ACCESS_SURFACE_FLINGER permission.
*/
virtual status_t getAnimationFrameStats(FrameStats* outStats) const = 0;
};
// ----------------------------------------------------------------------------
class BnSurfaceComposer: public BnInterface<ISurfaceComposer> {
public:
enum {
// Note: BOOT_FINISHED must remain this value, it is called from
// Java by ActivityManagerService.
BOOT_FINISHED = IBinder::FIRST_CALL_TRANSACTION,
CREATE_CONNECTION,
CREATE_GRAPHIC_BUFFER_ALLOC,
CREATE_DISPLAY_EVENT_CONNECTION,
CREATE_DISPLAY,
DESTROY_DISPLAY,
GET_BUILT_IN_DISPLAY,
SET_TRANSACTION_STATE,
AUTHENTICATE_SURFACE,
GET_DISPLAY_CONFIGS,
GET_ACTIVE_CONFIG,
SET_ACTIVE_CONFIG,
CONNECT_DISPLAY,
CAPTURE_SCREEN,
CLEAR_ANIMATION_FRAME_STATS,
GET_ANIMATION_FRAME_STATS,
SET_POWER_MODE,
GET_DISPLAY_STATS,
};
virtual status_t onTransact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_ISURFACE_COMPOSER_H
@@ -0,0 +1,95 @@
/*
* 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_GUI_ISURFACE_COMPOSER_CLIENT_H
#define ANDROID_GUI_ISURFACE_COMPOSER_CLIENT_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <ui/FrameStats.h>
#include <ui/PixelFormat.h>
namespace android {
// ----------------------------------------------------------------------------
class IGraphicBufferProducer;
class ISurfaceComposerClient : public IInterface
{
public:
DECLARE_META_INTERFACE(SurfaceComposerClient);
// flags for createSurface()
enum { // (keep in sync with Surface.java)
eHidden = 0x00000004,
eDestroyBackbuffer = 0x00000020,
eSecure = 0x00000080,
eNonPremultiplied = 0x00000100,
eOpaque = 0x00000400,
eProtectedByApp = 0x00000800,
eProtectedByDRM = 0x00001000,
eCursorWindow = 0x00002000,
eFXSurfaceNormal = 0x00000000,
eFXSurfaceBlur = 0x00010000,
eFXSurfaceDim = 0x00020000,
eFXSurfaceMask = 0x000F0000,
};
/*
* Requires ACCESS_SURFACE_FLINGER permission
*/
virtual status_t createSurface(
const String8& name, uint32_t w, uint32_t h,
PixelFormat format, uint32_t flags,
sp<IBinder>* handle,
sp<IGraphicBufferProducer>* gbp) = 0;
/*
* Requires ACCESS_SURFACE_FLINGER permission
*/
virtual status_t destroySurface(const sp<IBinder>& handle) = 0;
/*
* Requires ACCESS_SURFACE_FLINGER permission
*/
virtual status_t clearLayerFrameStats(const sp<IBinder>& handle) const = 0;
/*
* Requires ACCESS_SURFACE_FLINGER permission
*/
virtual status_t getLayerFrameStats(const sp<IBinder>& handle, FrameStats* outStats) const = 0;
};
// ----------------------------------------------------------------------------
class BnSurfaceComposerClient: public BnInterface<ISurfaceComposerClient> {
public:
virtual status_t onTransact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_ISURFACE_COMPOSER_CLIENT_H
@@ -0,0 +1,113 @@
/*
* 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/Flattenable.h>
#include <utils/String8.h>
#include <utils/Timers.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 LightFlattenable<Sensor>
{
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, int halVersion = 0);
~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;
nsecs_t getMinDelayNs() const;
int32_t getVersion() const;
uint32_t getFifoReservedEventCount() const;
uint32_t getFifoMaxEventCount() const;
const String8& getStringType() const;
const String8& getRequiredPermission() const;
bool isRequiredPermissionRuntime() const;
int32_t getRequiredAppOp() const;
int32_t getMaxDelay() const;
uint32_t getFlags() const;
bool isWakeUpSensor() const;
int32_t getReportingMode() const;
// LightFlattenable protocol
inline bool isFixedSize() const { return false; }
size_t getFlattenedSize() const;
status_t flatten(void* buffer, size_t size) const;
status_t unflatten(void const* buffer, size_t size);
private:
String8 mName;
String8 mVendor;
int32_t mHandle;
int32_t mType;
float mMinValue;
float mMaxValue;
float mResolution;
float mPower;
int32_t mMinDelay;
int32_t mVersion;
uint32_t mFifoReservedEventCount;
uint32_t mFifoMaxEventCount;
String8 mStringType;
String8 mRequiredPermission;
bool mRequiredPermissionRuntime = false;
int32_t mRequiredAppOp;
int32_t mMaxDelay;
uint32_t mFlags;
static void flattenString8(void*& buffer, size_t& size, const String8& string8);
static bool unflattenString8(void const*& buffer, size_t& size, String8& outputString8);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SENSOR_H
@@ -0,0 +1,98 @@
/*
* 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 <utils/String16.h>
#include <gui/BitTube.h>
// ----------------------------------------------------------------------------
#define WAKE_UP_SENSOR_EVENT_NEEDS_ACK (1U << 31)
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:
enum { MAX_RECEIVE_BUFFER_EVENT_COUNT = 256 };
SensorEventQueue(const sp<ISensorEventConnection>& connection);
virtual ~SensorEventQueue();
virtual void onFirstRef();
int getFd() const;
static ssize_t write(const sp<BitTube>& tube,
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 samplingPeriodUs, int maxBatchReportLatencyUs,
int reservedFlags) const;
status_t disableSensor(int32_t handle) const;
status_t flush() const;
// Send an ack for every wake_up sensor event that is set to WAKE_UP_SENSOR_EVENT_NEEDS_ACK.
void sendAck(const ASensorEvent* events, int count);
status_t injectSensorEvent(const ASensorEvent& event);
private:
sp<Looper> getLooper() const;
sp<ISensorEventConnection> mSensorEventConnection;
sp<BitTube> mSensorChannel;
mutable Mutex mLock;
mutable sp<Looper> mLooper;
ASensorEvent* mRecBuffer;
size_t mAvailable;
size_t mConsumed;
uint32_t mNumAcksToSend;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SENSOR_EVENT_QUEUE_H
@@ -0,0 +1,84 @@
/*
* 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 <map>
#include <stdint.h>
#include <sys/types.h>
#include <binder/IBinder.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/Singleton.h>
#include <utils/Vector.h>
#include <utils/String8.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:
static SensorManager& getInstanceForPackage(const String16& packageName);
~SensorManager();
ssize_t getSensorList(Sensor const* const** list) const;
Sensor const* getDefaultSensor(int type);
sp<SensorEventQueue> createEventQueue(String8 packageName = String8(""), int mode = 0);
bool isDataInjectionEnabled();
private:
// DeathRecipient interface
void sensorManagerDied();
SensorManager(const String16& opPackageName);
status_t assertStateLocked() const;
private:
static Mutex sLock;
static std::map<String16, SensorManager*> sPackageInstances;
mutable Mutex mLock;
mutable sp<ISensorServer> mSensorServer;
mutable Sensor const** mSensorList;
mutable Vector<Sensor> mSensors;
mutable sp<IBinder::DeathRecipient> mDeathObserver;
const String16 mOpPackageName;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SENSOR_MANAGER_H
@@ -0,0 +1,184 @@
/*
* Copyright 2014 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_STREAMSPLITTER_H
#define ANDROID_GUI_STREAMSPLITTER_H
#include <gui/IConsumerListener.h>
#include <gui/IProducerListener.h>
#include <utils/Condition.h>
#include <utils/KeyedVector.h>
#include <utils/Mutex.h>
#include <utils/StrongPointer.h>
namespace android {
class GraphicBuffer;
class IGraphicBufferConsumer;
class IGraphicBufferProducer;
// StreamSplitter is an autonomous class that manages one input BufferQueue
// and multiple output BufferQueues. By using the buffer attach and detach logic
// in BufferQueue, it is able to present the illusion of a single split
// BufferQueue, where each buffer queued to the input is available to be
// acquired by each of the outputs, and is able to be dequeued by the input
// again only once all of the outputs have released it.
class StreamSplitter : public BnConsumerListener {
public:
// createSplitter creates a new splitter, outSplitter, using inputQueue as
// the input BufferQueue. Output BufferQueues must be added using addOutput
// before queueing any buffers to the input.
//
// A return value other than NO_ERROR means that an error has occurred and
// outSplitter has not been modified. BAD_VALUE is returned if inputQueue or
// outSplitter is NULL. See IGraphicBufferConsumer::consumerConnect for
// explanations of other error codes.
static status_t createSplitter(const sp<IGraphicBufferConsumer>& inputQueue,
sp<StreamSplitter>* outSplitter);
// addOutput adds an output BufferQueue to the splitter. The splitter
// connects to outputQueue as a CPU producer, and any buffers queued
// to the input will be queued to each output. It is assumed that all of the
// outputs are added before any buffers are queued on the input. If any
// output is abandoned by its consumer, the splitter will abandon its input
// queue (see onAbandoned).
//
// A return value other than NO_ERROR means that an error has occurred and
// outputQueue has not been added to the splitter. BAD_VALUE is returned if
// outputQueue is NULL. See IGraphicBufferProducer::connect for explanations
// of other error codes.
status_t addOutput(const sp<IGraphicBufferProducer>& outputQueue);
// setName sets the consumer name of the input queue
void setName(const String8& name);
private:
// From IConsumerListener
//
// During this callback, we store some tracking information, detach the
// buffer from the input, and attach it to each of the outputs. This call
// can block if there are too many outstanding buffers. If it blocks, it
// will resume when onBufferReleasedByOutput releases a buffer back to the
// input.
virtual void onFrameAvailable(const BufferItem& item);
// From IConsumerListener
// We don't care about released buffers because we detach each buffer as
// soon as we acquire it. See the comment for onBufferReleased below for
// some clarifying notes about the name.
virtual void onBuffersReleased() {}
// From IConsumerListener
// We don't care about sideband streams, since we won't be splitting them
virtual void onSidebandStreamChanged() {}
// This is the implementation of the onBufferReleased callback from
// IProducerListener. It gets called from an OutputListener (see below), and
// 'from' is which producer interface from which the callback was received.
//
// During this callback, we detach the buffer from the output queue that
// generated the callback, update our state tracking to see if this is the
// last output releasing the buffer, and if so, release it to the input.
// If we release the buffer to the input, we allow a blocked
// onFrameAvailable call to proceed.
void onBufferReleasedByOutput(const sp<IGraphicBufferProducer>& from);
// When this is called, the splitter disconnects from (i.e., abandons) its
// input queue and signals any waiting onFrameAvailable calls to wake up.
// It still processes callbacks from other outputs, but only detaches their
// buffers so they can continue operating until they run out of buffers to
// acquire. This must be called with mMutex locked.
void onAbandonedLocked();
// This is a thin wrapper class that lets us determine which BufferQueue
// the IProducerListener::onBufferReleased callback is associated with. We
// create one of these per output BufferQueue, and then pass the producer
// into onBufferReleasedByOutput above.
class OutputListener : public BnProducerListener,
public IBinder::DeathRecipient {
public:
OutputListener(const sp<StreamSplitter>& splitter,
const sp<IGraphicBufferProducer>& output);
virtual ~OutputListener();
// From IProducerListener
virtual void onBufferReleased();
// From IBinder::DeathRecipient
virtual void binderDied(const wp<IBinder>& who);
private:
sp<StreamSplitter> mSplitter;
sp<IGraphicBufferProducer> mOutput;
};
class BufferTracker : public LightRefBase<BufferTracker> {
public:
BufferTracker(const sp<GraphicBuffer>& buffer);
const sp<GraphicBuffer>& getBuffer() const { return mBuffer; }
const sp<Fence>& getMergedFence() const { return mMergedFence; }
void mergeFence(const sp<Fence>& with);
// Returns the new value
// Only called while mMutex is held
size_t incrementReleaseCountLocked() { return ++mReleaseCount; }
private:
// Only destroy through LightRefBase
friend LightRefBase<BufferTracker>;
~BufferTracker();
// Disallow copying
BufferTracker(const BufferTracker& other);
BufferTracker& operator=(const BufferTracker& other);
sp<GraphicBuffer> mBuffer; // One instance that holds this native handle
sp<Fence> mMergedFence;
size_t mReleaseCount;
};
// Only called from createSplitter
StreamSplitter(const sp<IGraphicBufferConsumer>& inputQueue);
// Must be accessed through RefBase
virtual ~StreamSplitter();
static const int MAX_OUTSTANDING_BUFFERS = 2;
// mIsAbandoned is set to true when an output dies. Once the StreamSplitter
// has been abandoned, it will continue to detach buffers from other
// outputs, but it will disconnect from the input and not attempt to
// communicate with it further.
bool mIsAbandoned;
Mutex mMutex;
Condition mReleaseCondition;
int mOutstandingBuffers;
sp<IGraphicBufferConsumer> mInput;
Vector<sp<IGraphicBufferProducer> > mOutputs;
// Map of GraphicBuffer IDs (GraphicBuffer::getId()) to buffer tracking
// objects (which are mostly for counting how many outputs have released the
// buffer, but also contain merged release fences).
KeyedVector<uint64_t, sp<BufferTracker> > mBuffers;
};
} // namespace android
#endif
@@ -0,0 +1,324 @@
/*
* 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_SURFACE_H
#define ANDROID_GUI_SURFACE_H
#include <gui/IGraphicBufferProducer.h>
#include <gui/BufferQueue.h>
#include <ui/ANativeObjectBase.h>
#include <ui/Region.h>
#include <utils/RefBase.h>
#include <utils/threads.h>
#include <utils/KeyedVector.h>
struct ANativeWindow_Buffer;
namespace android {
/*
* An implementation of ANativeWindow that feeds graphics buffers into a
* BufferQueue.
*
* This is typically used by programs that want to render frames through
* some means (maybe OpenGL, a software renderer, or a hardware decoder)
* and have the frames they create forwarded to SurfaceFlinger for
* compositing. For example, a video decoder could render a frame and call
* eglSwapBuffers(), which invokes ANativeWindow callbacks defined by
* Surface. Surface then forwards the buffers through Binder IPC
* to the BufferQueue's producer interface, providing the new frame to a
* consumer such as GLConsumer.
*/
class Surface
: public ANativeObjectBase<ANativeWindow, Surface, RefBase>
{
public:
/*
* creates a Surface from the given IGraphicBufferProducer (which concrete
* implementation is a BufferQueue).
*
* Surface is mainly state-less while it's disconnected, it can be
* viewed as a glorified IGraphicBufferProducer holder. It's therefore
* safe to create other Surfaces from the same IGraphicBufferProducer.
*
* However, once a Surface is connected, it'll prevent other Surfaces
* referring to the same IGraphicBufferProducer to become connected and
* therefore prevent them to be used as actual producers of buffers.
*
* the controlledByApp flag indicates that this Surface (producer) is
* controlled by the application. This flag is used at connect time.
*/
Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp = false);
/* getIGraphicBufferProducer() returns the IGraphicBufferProducer this
* Surface was created with. Usually it's an error to use the
* IGraphicBufferProducer while the Surface is connected.
*/
sp<IGraphicBufferProducer> getIGraphicBufferProducer() const;
/* convenience function to check that the given surface is non NULL as
* well as its IGraphicBufferProducer */
static bool isValid(const sp<Surface>& surface) {
return surface != NULL && surface->getIGraphicBufferProducer() != NULL;
}
/* Attaches a sideband buffer stream to the Surface's IGraphicBufferProducer.
*
* A sideband stream is a device-specific mechanism for passing buffers
* from the producer to the consumer without using dequeueBuffer/
* queueBuffer. If a sideband stream is present, the consumer can choose
* whether to acquire buffers from the sideband stream or from the queued
* buffers.
*
* Passing NULL or a different stream handle will detach the previous
* handle if any.
*/
void setSidebandStream(const sp<NativeHandle>& stream);
/* Allocates buffers based on the current dimensions/format.
*
* This function will allocate up to the maximum number of buffers
* permitted by the current BufferQueue configuration. It will use the
* default format and dimensions. This is most useful to avoid an allocation
* delay during dequeueBuffer. If there are already the maximum number of
* buffers allocated, this function has no effect.
*/
void allocateBuffers();
/* Sets the generation number on the IGraphicBufferProducer and updates the
* generation number on any buffers attached to the Surface after this call.
* See IGBP::setGenerationNumber for more information. */
status_t setGenerationNumber(uint32_t generationNumber);
// See IGraphicBufferProducer::getConsumerName
String8 getConsumerName() const;
protected:
virtual ~Surface();
private:
// can't be copied
Surface& operator = (const Surface& rhs);
Surface(const Surface& rhs);
// ANativeWindow hooks
static int hook_cancelBuffer(ANativeWindow* window,
ANativeWindowBuffer* buffer, int fenceFd);
static int hook_dequeueBuffer(ANativeWindow* window,
ANativeWindowBuffer** buffer, int* fenceFd);
static int hook_perform(ANativeWindow* window, int operation, ...);
static int hook_query(const ANativeWindow* window, int what, int* value);
static int hook_queueBuffer(ANativeWindow* window,
ANativeWindowBuffer* buffer, int fenceFd);
static int hook_setSwapInterval(ANativeWindow* window, int interval);
static int hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer* buffer);
static int hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer** buffer);
static int hook_lockBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer* buffer);
static int hook_queueBuffer_DEPRECATED(ANativeWindow* window,
ANativeWindowBuffer* buffer);
int dispatchConnect(va_list args);
int dispatchDisconnect(va_list args);
int dispatchSetBufferCount(va_list args);
int dispatchSetBuffersGeometry(va_list args);
int dispatchSetBuffersDimensions(va_list args);
int dispatchSetBuffersUserDimensions(va_list args);
int dispatchSetBuffersFormat(va_list args);
int dispatchSetScalingMode(va_list args);
int dispatchSetBuffersTransform(va_list args);
int dispatchSetBuffersStickyTransform(va_list args);
int dispatchSetBuffersTimestamp(va_list args);
int dispatchSetCrop(va_list args);
int dispatchSetPostTransformCrop(va_list args);
int dispatchSetUsage(va_list args);
int dispatchLock(va_list args);
int dispatchUnlockAndPost(va_list args);
int dispatchSetSidebandStream(va_list args);
int dispatchSetBuffersDataSpace(va_list args);
int dispatchSetSurfaceDamage(va_list args);
protected:
virtual int dequeueBuffer(ANativeWindowBuffer** buffer, int* fenceFd);
virtual int cancelBuffer(ANativeWindowBuffer* buffer, int fenceFd);
virtual int queueBuffer(ANativeWindowBuffer* buffer, int fenceFd);
virtual int perform(int operation, va_list args);
virtual int query(int what, int* value) const;
virtual int setSwapInterval(int interval);
virtual int lockBuffer_DEPRECATED(ANativeWindowBuffer* buffer);
virtual int connect(int api);
virtual int disconnect(int api);
virtual int setBufferCount(int bufferCount);
virtual int setBuffersDimensions(uint32_t width, uint32_t height);
virtual int setBuffersUserDimensions(uint32_t width, uint32_t height);
virtual int setBuffersFormat(PixelFormat format);
virtual int setScalingMode(int mode);
virtual int setBuffersTransform(uint32_t transform);
virtual int setBuffersStickyTransform(uint32_t transform);
virtual int setBuffersTimestamp(int64_t timestamp);
virtual int setBuffersDataSpace(android_dataspace dataSpace);
virtual int setCrop(Rect const* rect);
virtual int setUsage(uint32_t reqUsage);
virtual void setSurfaceDamage(android_native_rect_t* rects, size_t numRects);
public:
virtual int lock(ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds);
virtual int unlockAndPost();
virtual int connect(int api, const sp<IProducerListener>& listener);
virtual int detachNextBuffer(sp<GraphicBuffer>* outBuffer,
sp<Fence>* outFence);
virtual int attachBuffer(ANativeWindowBuffer*);
protected:
enum { NUM_BUFFER_SLOTS = BufferQueue::NUM_BUFFER_SLOTS };
enum { DEFAULT_FORMAT = PIXEL_FORMAT_RGBA_8888 };
private:
void freeAllBuffers();
int getSlotFromBufferLocked(android_native_buffer_t* buffer) const;
struct BufferSlot {
sp<GraphicBuffer> buffer;
Region dirtyRegion;
};
// mSurfaceTexture is the interface to the surface texture server. All
// operations on the surface texture client ultimately translate into
// interactions with the server using this interface.
// TODO: rename to mBufferProducer
sp<IGraphicBufferProducer> mGraphicBufferProducer;
// mSlots stores the buffers that have been allocated for each buffer slot.
// It is initialized to null pointers, and gets filled in with the result of
// IGraphicBufferProducer::requestBuffer when the client dequeues a buffer from a
// slot that has not yet been used. The buffer allocated to a slot will also
// be replaced if the requested buffer usage or geometry differs from that
// of the buffer allocated to a slot.
BufferSlot mSlots[NUM_BUFFER_SLOTS];
// mReqWidth is the buffer width that will be requested at the next dequeue
// operation. It is initialized to 1.
uint32_t mReqWidth;
// mReqHeight is the buffer height that will be requested at the next
// dequeue operation. It is initialized to 1.
uint32_t mReqHeight;
// mReqFormat is the buffer pixel format that will be requested at the next
// deuque operation. It is initialized to PIXEL_FORMAT_RGBA_8888.
PixelFormat mReqFormat;
// mReqUsage is the set of buffer usage flags that will be requested
// at the next deuque operation. It is initialized to 0.
uint32_t mReqUsage;
// mTimestamp is the timestamp that will be used for the next buffer queue
// operation. It defaults to NATIVE_WINDOW_TIMESTAMP_AUTO, which means that
// a timestamp is auto-generated when queueBuffer is called.
int64_t mTimestamp;
// mDataSpace is the buffer dataSpace that will be used for the next buffer
// queue operation. It defaults to HAL_DATASPACE_UNKNOWN, which
// means that the buffer contains some type of color data.
android_dataspace mDataSpace;
// mCrop is the crop rectangle that will be used for the next buffer
// that gets queued. It is set by calling setCrop.
Rect mCrop;
// mScalingMode is the scaling mode that will be used for the next
// buffers that get queued. It is set by calling setScalingMode.
int mScalingMode;
// mTransform is the transform identifier that will be used for the next
// buffer that gets queued. It is set by calling setTransform.
uint32_t mTransform;
// mStickyTransform is a transform that is applied on top of mTransform
// in each buffer that is queued. This is typically used to force the
// compositor to apply a transform, and will prevent the transform hint
// from being set by the compositor.
uint32_t mStickyTransform;
// mDefaultWidth is default width of the buffers, regardless of the
// native_window_set_buffers_dimensions call.
uint32_t mDefaultWidth;
// mDefaultHeight is default height of the buffers, regardless of the
// native_window_set_buffers_dimensions call.
uint32_t mDefaultHeight;
// mUserWidth, if non-zero, is an application-specified override
// of mDefaultWidth. This is lower priority than the width set by
// native_window_set_buffers_dimensions.
uint32_t mUserWidth;
// mUserHeight, if non-zero, is an application-specified override
// of mDefaultHeight. This is lower priority than the height set
// by native_window_set_buffers_dimensions.
uint32_t mUserHeight;
// mTransformHint is the transform probably applied to buffers of this
// window. this is only a hint, actual transform may differ.
uint32_t mTransformHint;
// mProducerControlledByApp whether this buffer producer is controlled
// by the application
bool mProducerControlledByApp;
// mSwapIntervalZero set if we should drop buffers at queue() time to
// achieve an asynchronous swap interval
bool mSwapIntervalZero;
// mConsumerRunningBehind whether the consumer is running more than
// one buffer behind the producer.
mutable bool mConsumerRunningBehind;
// mMutex is the mutex used to prevent concurrent access to the member
// variables of Surface objects. It must be locked whenever the
// member variables are accessed.
mutable Mutex mMutex;
// must be used from the lock/unlock thread
sp<GraphicBuffer> mLockedBuffer;
sp<GraphicBuffer> mPostedBuffer;
bool mConnectedToCpu;
// When a CPU producer is attached, this reflects the region that the
// producer wished to update as well as whether the Surface was able to copy
// the previous buffer back to allow a partial update.
//
// When a non-CPU producer is attached, this reflects the surface damage
// (the change since the previous frame) passed in by the producer.
Region mDirtyRegion;
// Stores the current generation number. See setGenerationNumber and
// IGraphicBufferProducer::setGenerationNumber for more information.
uint32_t mGenerationNumber;
};
}; // namespace android
#endif // ANDROID_GUI_SURFACE_H
@@ -0,0 +1,242 @@
/*
* 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_GUI_SURFACE_COMPOSER_CLIENT_H
#define ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
#include <stdint.h>
#include <sys/types.h>
#include <binder/IBinder.h>
#include <binder/IMemory.h>
#include <utils/RefBase.h>
#include <utils/Singleton.h>
#include <utils/SortedVector.h>
#include <utils/threads.h>
#include <ui/FrameStats.h>
#include <ui/PixelFormat.h>
#include <gui/CpuConsumer.h>
#include <gui/SurfaceControl.h>
namespace android {
// ---------------------------------------------------------------------------
class DisplayInfo;
class Composer;
class ISurfaceComposerClient;
class IGraphicBufferProducer;
class Region;
// ---------------------------------------------------------------------------
class SurfaceComposerClient : public RefBase
{
friend class Composer;
public:
SurfaceComposerClient();
virtual ~SurfaceComposerClient();
// Always make sure we could initialize
status_t initCheck() const;
// Return the connection of this client
sp<IBinder> connection() const;
// Forcibly remove connection before all references have gone away.
void dispose();
// callback when the composer is dies
status_t linkToComposerDeath(const sp<IBinder::DeathRecipient>& recipient,
void* cookie = NULL, uint32_t flags = 0);
// Get a list of supported configurations for a given display
static status_t getDisplayConfigs(const sp<IBinder>& display,
Vector<DisplayInfo>* configs);
// Get the DisplayInfo for the currently-active configuration
static status_t getDisplayInfo(const sp<IBinder>& display,
DisplayInfo* info);
// Get the index of the current active configuration (relative to the list
// returned by getDisplayInfo)
static int getActiveConfig(const sp<IBinder>& display);
// Set a new active configuration using an index relative to the list
// returned by getDisplayInfo
static status_t setActiveConfig(const sp<IBinder>& display, int id);
/* Triggers screen on/off or low power mode and waits for it to complete */
static void setDisplayPowerMode(const sp<IBinder>& display, int mode);
// ------------------------------------------------------------------------
// surface creation / destruction
//! Create a surface
sp<SurfaceControl> createSurface(
const String8& name,// name of the surface
uint32_t w, // width in pixel
uint32_t h, // height in pixel
PixelFormat format, // pixel-format desired
uint32_t flags = 0 // usage flags
);
//! Create a virtual display
static sp<IBinder> createDisplay(const String8& displayName, bool secure);
//! Destroy a virtual display
static void destroyDisplay(const sp<IBinder>& display);
//! Get the token for the existing default displays.
//! Possible values for id are eDisplayIdMain and eDisplayIdHdmi.
static sp<IBinder> getBuiltInDisplay(int32_t id);
// ------------------------------------------------------------------------
// Composer parameters
// All composer parameters must be changed within a transaction
// several surfaces can be updated in one transaction, all changes are
// committed at once when the transaction is closed.
// closeGlobalTransaction() requires an IPC with the server.
//! Open a composer transaction on all active SurfaceComposerClients.
static void openGlobalTransaction();
//! Close a composer transaction on all active SurfaceComposerClients.
static void closeGlobalTransaction(bool synchronous = false);
//! Flag the currently open transaction as an animation transaction.
static void setAnimationTransaction();
status_t hide(const sp<IBinder>& id);
status_t show(const sp<IBinder>& id);
status_t setFlags(const sp<IBinder>& id, uint32_t flags, uint32_t mask);
status_t setTransparentRegionHint(const sp<IBinder>& id, const Region& transparent);
status_t setLayer(const sp<IBinder>& id, uint32_t layer);
status_t setAlpha(const sp<IBinder>& id, float alpha=1.0f);
status_t setMatrix(const sp<IBinder>& id, float dsdx, float dtdx, float dsdy, float dtdy);
status_t setPosition(const sp<IBinder>& id, float x, float y);
status_t setSize(const sp<IBinder>& id, uint32_t w, uint32_t h);
status_t setCrop(const sp<IBinder>& id, const Rect& crop);
status_t setLayerStack(const sp<IBinder>& id, uint32_t layerStack);
status_t destroySurface(const sp<IBinder>& id);
status_t clearLayerFrameStats(const sp<IBinder>& token) const;
status_t getLayerFrameStats(const sp<IBinder>& token, FrameStats* outStats) const;
static status_t clearAnimationFrameStats();
static status_t getAnimationFrameStats(FrameStats* outStats);
static void setDisplaySurface(const sp<IBinder>& token,
const sp<IGraphicBufferProducer>& bufferProducer);
static void setDisplayLayerStack(const sp<IBinder>& token,
uint32_t layerStack);
static void setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height);
/* setDisplayProjection() defines the projection of layer stacks
* to a given display.
*
* - orientation defines the display's orientation.
* - layerStackRect defines which area of the window manager coordinate
* space will be used.
* - displayRect defines where on the display will layerStackRect be
* mapped to. displayRect is specified post-orientation, that is
* it uses the orientation seen by the end-user.
*/
static void setDisplayProjection(const sp<IBinder>& token,
uint32_t orientation,
const Rect& layerStackRect,
const Rect& displayRect);
status_t setBlur(const sp<IBinder>& id, float blur);
status_t setBlurMaskSurface(const sp<IBinder>& id, const sp<IBinder>& maskSurfaceId);
status_t setBlurMaskSampling(const sp<IBinder>& id, uint32_t blurMaskSampling);
status_t setBlurMaskAlphaThreshold(const sp<IBinder>& id, float alpha);
private:
virtual void onFirstRef();
Composer& getComposer();
mutable Mutex mLock;
status_t mStatus;
sp<ISurfaceComposerClient> mClient;
Composer& mComposer;
};
// ---------------------------------------------------------------------------
class ScreenshotClient
{
public:
// if cropping isn't required, callers may pass in a default Rect, e.g.:
// capture(display, producer, Rect(), reqWidth, ...);
static status_t capture(
const sp<IBinder>& display,
const sp<IGraphicBufferProducer>& producer,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ,
bool useIdentityTransform);
private:
mutable sp<CpuConsumer> mCpuConsumer;
mutable sp<IGraphicBufferProducer> mProducer;
CpuConsumer::LockedBuffer mBuffer;
bool mHaveBuffer;
public:
ScreenshotClient();
~ScreenshotClient();
// frees the previous screenshot and captures a new one
// if cropping isn't required, callers may pass in a default Rect, e.g.:
// update(display, Rect(), useIdentityTransform);
status_t update(const sp<IBinder>& display,
Rect sourceCrop, bool useIdentityTransform);
status_t update(const sp<IBinder>& display,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
bool useIdentityTransform);
status_t update(const sp<IBinder>& display,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ,
bool useIdentityTransform);
status_t update(const sp<IBinder>& display,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ,
bool useIdentityTransform, uint32_t rotation);
sp<CpuConsumer> getCpuConsumer() const;
// release memory occupied by the screenshot
void release();
// pixels are valid until this object is freed or
// release() or update() is called
void const* getPixels() const;
uint32_t getWidth() const;
uint32_t getHeight() const;
PixelFormat getFormat() const;
uint32_t getStride() const;
// size of allocated memory in bytes
size_t getSize() const;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SURFACE_COMPOSER_CLIENT_H
@@ -0,0 +1,112 @@
/*
* 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_GUI_SURFACE_CONTROL_H
#define ANDROID_GUI_SURFACE_CONTROL_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
#include <utils/threads.h>
#include <ui/FrameStats.h>
#include <ui/PixelFormat.h>
#include <ui/Region.h>
#include <gui/ISurfaceComposerClient.h>
namespace android {
// ---------------------------------------------------------------------------
class IGraphicBufferProducer;
class Surface;
class SurfaceComposerClient;
// ---------------------------------------------------------------------------
class SurfaceControl : public RefBase
{
public:
static bool isValid(const sp<SurfaceControl>& surface) {
return (surface != 0) && surface->isValid();
}
bool isValid() {
return mHandle!=0 && mClient!=0;
}
static bool isSameSurface(
const sp<SurfaceControl>& lhs, const sp<SurfaceControl>& rhs);
// release surface data from java
void clear();
status_t setLayerStack(uint32_t layerStack);
status_t setLayer(uint32_t layer);
status_t setPosition(float x, float y);
status_t setSize(uint32_t w, uint32_t h);
status_t hide();
status_t show();
status_t setFlags(uint32_t flags, uint32_t mask);
status_t setTransparentRegionHint(const Region& transparent);
status_t setAlpha(float alpha=1.0f);
status_t setMatrix(float dsdx, float dtdx, float dsdy, float dtdy);
status_t setCrop(const Rect& crop);
static status_t writeSurfaceToParcel(
const sp<SurfaceControl>& control, Parcel* parcel);
sp<Surface> getSurface() const;
status_t clearLayerFrameStats() const;
status_t getLayerFrameStats(FrameStats* outStats) const;
status_t setBlur(float blur = 0);
status_t setBlurMaskSurface(const sp<SurfaceControl>& maskSurface);
status_t setBlurMaskSampling(uint32_t blurMaskSampling);
status_t setBlurMaskAlphaThreshold(float alpha);
private:
// can't be copied
SurfaceControl& operator = (SurfaceControl& rhs);
SurfaceControl(const SurfaceControl& rhs);
friend class SurfaceComposerClient;
friend class Surface;
SurfaceControl(
const sp<SurfaceComposerClient>& client,
const sp<IBinder>& handle,
const sp<IGraphicBufferProducer>& gbp);
~SurfaceControl();
status_t validate() const;
void destroy();
sp<SurfaceComposerClient> mClient;
sp<IBinder> mHandle;
sp<IGraphicBufferProducer> mGraphicBufferProducer;
mutable Mutex mLock;
mutable sp<Surface> mSurfaceData;
};
}; // namespace android
#endif // ANDROID_GUI_SURFACE_CONTROL_H
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2013 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 _LIBINPUT_IINPUT_FLINGER_H
#define _LIBINPUT_IINPUT_FLINGER_H
#include <stdint.h>
#include <sys/types.h>
#include <binder/IInterface.h>
namespace android {
/*
* This class defines the Binder IPC interface for accessing various
* InputFlinger features.
*/
class IInputFlinger : public IInterface {
public:
DECLARE_META_INTERFACE(InputFlinger);
};
/**
* Binder implementation.
*/
class BnInputFlinger : public BnInterface<IInputFlinger> {
public:
enum {
DO_SOMETHING_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
};
virtual status_t onTransact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0);
};
} // namespace android
#endif // _LIBINPUT_IINPUT_FLINGER_H
@@ -0,0 +1,681 @@
/*
* 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 _LIBINPUT_INPUT_H
#define _LIBINPUT_INPUT_H
/**
* Native input event structures.
*/
#include <android/input.h>
#include <utils/BitSet.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
#include <utils/String8.h>
#include <utils/Timers.h>
#include <utils/Vector.h>
#include <stdint.h>
/*
* Additional private constants not defined in ndk/ui/input.h.
*/
enum {
/* Signifies that the key is being predispatched */
AKEY_EVENT_FLAG_PREDISPATCH = 0x20000000,
/* Private control to determine when an app is tracking a key sequence. */
AKEY_EVENT_FLAG_START_TRACKING = 0x40000000,
/* Key event is inconsistent with previously sent key events. */
AKEY_EVENT_FLAG_TAINTED = 0x80000000,
};
enum {
/**
* This flag indicates that the window that received this motion event is partly
* or wholly obscured by another visible window above it. This flag is set to true
* even if the event did not directly pass through the obscured area.
* A security sensitive application can check this flag to identify situations in which
* a malicious application may have covered up part of its content for the purpose
* of misleading the user or hijacking touches. An appropriate response might be
* to drop the suspect touches or to take additional precautions to confirm the user's
* actual intent.
*/
AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 0x2,
/* Motion event is inconsistent with previously sent motion events. */
AMOTION_EVENT_FLAG_TAINTED = 0x80000000,
};
enum {
/* Used when a motion event is not associated with any display.
* Typically used for non-pointer events. */
ADISPLAY_ID_NONE = -1,
/* The default display id. */
ADISPLAY_ID_DEFAULT = 0,
};
enum {
/*
* Indicates that an input device has switches.
* This input source flag is hidden from the API because switches are only used by the system
* and applications have no way to interact with them.
*/
AINPUT_SOURCE_SWITCH = 0x80000000,
};
enum {
/**
* Constants for LEDs. Hidden from the API since we don't actually expose a way to interact
* with LEDs to developers
*
* NOTE: If you add LEDs here, you must also add them to InputEventLabels.h
*/
ALED_NUM_LOCK = 0x00,
ALED_CAPS_LOCK = 0x01,
ALED_SCROLL_LOCK = 0x02,
ALED_COMPOSE = 0x03,
ALED_KANA = 0x04,
ALED_SLEEP = 0x05,
ALED_SUSPEND = 0x06,
ALED_MUTE = 0x07,
ALED_MISC = 0x08,
ALED_MAIL = 0x09,
ALED_CHARGING = 0x0a,
ALED_CONTROLLER_1 = 0x10,
ALED_CONTROLLER_2 = 0x11,
ALED_CONTROLLER_3 = 0x12,
ALED_CONTROLLER_4 = 0x13,
};
/* Maximum number of controller LEDs we support */
#define MAX_CONTROLLER_LEDS 4
/*
* SystemUiVisibility constants from View.
*/
enum {
ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE = 0,
ASYSTEM_UI_VISIBILITY_STATUS_BAR_HIDDEN = 0x00000001,
};
/*
* Maximum number of pointers supported per motion event.
* Smallest number of pointers is 1.
* (We want at least 10 but some touch controllers obstensibly configured for 10 pointers
* will occasionally emit 11. There is not much harm making this constant bigger.)
*/
#define MAX_POINTERS 16
/*
* Maximum number of samples supported per motion event.
*/
#define MAX_SAMPLES UINT16_MAX
/*
* Maximum pointer id value supported in a motion event.
* Smallest pointer id is 0.
* (This is limited by our use of BitSet32 to track pointer assignments.)
*/
#define MAX_POINTER_ID 31
/*
* Declare a concrete type for the NDK's input event forward declaration.
*/
struct AInputEvent {
virtual ~AInputEvent() { }
};
/*
* Declare a concrete type for the NDK's input device forward declaration.
*/
struct AInputDevice {
virtual ~AInputDevice() { }
};
namespace android {
#ifdef HAVE_ANDROID_OS
class Parcel;
#endif
/*
* Flags that flow alongside events in the input dispatch system to help with certain
* policy decisions such as waking from device sleep.
*
* These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java.
*/
enum {
/* These flags originate in RawEvents and are generally set in the key map.
* NOTE: If you want a flag to be able to set in a keylayout file, then you must add it to
* InputEventLabels.h as well. */
// Indicates that the event should wake the device.
POLICY_FLAG_WAKE = 0x00000001,
// Indicates that the key is virtual, such as a capacitive button, and should
// generate haptic feedback. Virtual keys may be suppressed for some time
// after a recent touch to prevent accidental activation of virtual keys adjacent
// to the touch screen during an edge swipe.
POLICY_FLAG_VIRTUAL = 0x00000002,
// Indicates that the key is the special function modifier.
POLICY_FLAG_FUNCTION = 0x00000004,
// Indicates that the key represents a special gesture that has been detected by
// the touch firmware or driver. Causes touch events from the same device to be canceled.
POLICY_FLAG_GESTURE = 0x00000008,
POLICY_FLAG_RAW_MASK = 0x0000ffff,
/* These flags are set by the input dispatcher. */
// Indicates that the input event was injected.
POLICY_FLAG_INJECTED = 0x01000000,
// Indicates that the input event is from a trusted source such as a directly attached
// input device or an application with system-wide event injection permission.
POLICY_FLAG_TRUSTED = 0x02000000,
// Indicates that the input event has passed through an input filter.
POLICY_FLAG_FILTERED = 0x04000000,
// Disables automatic key repeating behavior.
POLICY_FLAG_DISABLE_KEY_REPEAT = 0x08000000,
/* These flags are set by the input reader policy as it intercepts each event. */
// Indicates that the device was in an interactive state when the
// event was intercepted.
POLICY_FLAG_INTERACTIVE = 0x20000000,
// Indicates that the event should be dispatched to applications.
// The input event should still be sent to the InputDispatcher so that it can see all
// input events received include those that it will not deliver.
POLICY_FLAG_PASS_TO_USER = 0x40000000,
};
/*
* Pointer coordinate data.
*/
struct PointerCoords {
enum { MAX_AXES = 30 }; // 30 so that sizeof(PointerCoords) == 128
// Bitfield of axes that are present in this structure.
uint64_t bits __attribute__((aligned(8)));
// Values of axes that are stored in this structure packed in order by axis id
// for each axis that is present in the structure according to 'bits'.
float values[MAX_AXES];
inline void clear() {
BitSet64::clear(bits);
}
bool isEmpty() const {
return BitSet64::isEmpty(bits);
}
float getAxisValue(int32_t axis) const;
status_t setAxisValue(int32_t axis, float value);
void scale(float scale);
void applyOffset(float xOffset, float yOffset);
inline float getX() const {
return getAxisValue(AMOTION_EVENT_AXIS_X);
}
inline float getY() const {
return getAxisValue(AMOTION_EVENT_AXIS_Y);
}
#ifdef HAVE_ANDROID_OS
status_t readFromParcel(Parcel* parcel);
status_t writeToParcel(Parcel* parcel) const;
#endif
bool operator==(const PointerCoords& other) const;
inline bool operator!=(const PointerCoords& other) const {
return !(*this == other);
}
void copyFrom(const PointerCoords& other);
private:
void tooManyAxes(int axis);
};
/*
* Pointer property data.
*/
struct PointerProperties {
// The id of the pointer.
int32_t id;
// The pointer tool type.
int32_t toolType;
inline void clear() {
id = -1;
toolType = 0;
}
bool operator==(const PointerProperties& other) const;
inline bool operator!=(const PointerProperties& other) const {
return !(*this == other);
}
void copyFrom(const PointerProperties& other);
};
/*
* Input events.
*/
class InputEvent : public AInputEvent {
public:
virtual ~InputEvent() { }
virtual int32_t getType() const = 0;
inline int32_t getDeviceId() const { return mDeviceId; }
inline int32_t getSource() const { return mSource; }
inline void setSource(int32_t source) { mSource = source; }
protected:
void initialize(int32_t deviceId, int32_t source);
void initialize(const InputEvent& from);
int32_t mDeviceId;
int32_t mSource;
};
/*
* Key events.
*/
class KeyEvent : public InputEvent {
public:
virtual ~KeyEvent() { }
virtual int32_t getType() const { return AINPUT_EVENT_TYPE_KEY; }
inline int32_t getAction() const { return mAction; }
inline int32_t getFlags() const { return mFlags; }
inline void setFlags(int32_t flags) { mFlags = flags; }
inline int32_t getKeyCode() const { return mKeyCode; }
inline int32_t getScanCode() const { return mScanCode; }
inline int32_t getMetaState() const { return mMetaState; }
inline int32_t getRepeatCount() const { return mRepeatCount; }
inline nsecs_t getDownTime() const { return mDownTime; }
inline nsecs_t getEventTime() const { return mEventTime; }
static const char* getLabel(int32_t keyCode);
static int32_t getKeyCodeFromLabel(const char* label);
void initialize(
int32_t deviceId,
int32_t source,
int32_t action,
int32_t flags,
int32_t keyCode,
int32_t scanCode,
int32_t metaState,
int32_t repeatCount,
nsecs_t downTime,
nsecs_t eventTime);
void initialize(const KeyEvent& from);
protected:
int32_t mAction;
int32_t mFlags;
int32_t mKeyCode;
int32_t mScanCode;
int32_t mMetaState;
int32_t mRepeatCount;
nsecs_t mDownTime;
nsecs_t mEventTime;
};
/*
* Motion events.
*/
class MotionEvent : public InputEvent {
public:
virtual ~MotionEvent() { }
virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; }
inline int32_t getAction() const { return mAction; }
inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; }
inline int32_t getActionIndex() const {
return (mAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
>> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
}
inline void setAction(int32_t action) { mAction = action; }
inline int32_t getFlags() const { return mFlags; }
inline void setFlags(int32_t flags) { mFlags = flags; }
inline int32_t getEdgeFlags() const { return mEdgeFlags; }
inline void setEdgeFlags(int32_t edgeFlags) { mEdgeFlags = edgeFlags; }
inline int32_t getMetaState() const { return mMetaState; }
inline void setMetaState(int32_t metaState) { mMetaState = metaState; }
inline int32_t getButtonState() const { return mButtonState; }
inline int32_t setButtonState(int32_t buttonState) { mButtonState = buttonState; }
inline int32_t getActionButton() const { return mActionButton; }
inline void setActionButton(int32_t button) { mActionButton = button; }
inline float getXOffset() const { return mXOffset; }
inline float getYOffset() const { return mYOffset; }
inline float getXPrecision() const { return mXPrecision; }
inline float getYPrecision() const { return mYPrecision; }
inline nsecs_t getDownTime() const { return mDownTime; }
inline void setDownTime(nsecs_t downTime) { mDownTime = downTime; }
inline size_t getPointerCount() const { return mPointerProperties.size(); }
inline const PointerProperties* getPointerProperties(size_t pointerIndex) const {
return &mPointerProperties[pointerIndex];
}
inline int32_t getPointerId(size_t pointerIndex) const {
return mPointerProperties[pointerIndex].id;
}
inline int32_t getToolType(size_t pointerIndex) const {
return mPointerProperties[pointerIndex].toolType;
}
inline nsecs_t getEventTime() const { return mSampleEventTimes[getHistorySize()]; }
const PointerCoords* getRawPointerCoords(size_t pointerIndex) const;
float getRawAxisValue(int32_t axis, size_t pointerIndex) const;
inline float getRawX(size_t pointerIndex) const {
return getRawAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
}
inline float getRawY(size_t pointerIndex) const {
return getRawAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
}
float getAxisValue(int32_t axis, size_t pointerIndex) const;
inline float getX(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
}
inline float getY(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
}
inline float getPressure(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerIndex);
}
inline float getSize(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerIndex);
}
inline float getTouchMajor(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex);
}
inline float getTouchMinor(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex);
}
inline float getToolMajor(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex);
}
inline float getToolMinor(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex);
}
inline float getOrientation(size_t pointerIndex) const {
return getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex);
}
inline size_t getHistorySize() const { return mSampleEventTimes.size() - 1; }
inline nsecs_t getHistoricalEventTime(size_t historicalIndex) const {
return mSampleEventTimes[historicalIndex];
}
const PointerCoords* getHistoricalRawPointerCoords(
size_t pointerIndex, size_t historicalIndex) const;
float getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
size_t historicalIndex) const;
inline float getHistoricalRawX(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalRawAxisValue(
AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
}
inline float getHistoricalRawY(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalRawAxisValue(
AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
}
float getHistoricalAxisValue(int32_t axis, size_t pointerIndex, size_t historicalIndex) const;
inline float getHistoricalX(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
}
inline float getHistoricalY(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
}
inline float getHistoricalPressure(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historicalIndex);
}
inline float getHistoricalSize(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_SIZE, pointerIndex, historicalIndex);
}
inline float getHistoricalTouchMajor(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historicalIndex);
}
inline float getHistoricalTouchMinor(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historicalIndex);
}
inline float getHistoricalToolMajor(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historicalIndex);
}
inline float getHistoricalToolMinor(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historicalIndex);
}
inline float getHistoricalOrientation(size_t pointerIndex, size_t historicalIndex) const {
return getHistoricalAxisValue(
AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historicalIndex);
}
ssize_t findPointerIndex(int32_t pointerId) const;
void initialize(
int32_t deviceId,
int32_t source,
int32_t action,
int32_t actionButton,
int32_t flags,
int32_t edgeFlags,
int32_t metaState,
int32_t buttonState,
float xOffset,
float yOffset,
float xPrecision,
float yPrecision,
nsecs_t downTime,
nsecs_t eventTime,
size_t pointerCount,
const PointerProperties* pointerProperties,
const PointerCoords* pointerCoords);
void copyFrom(const MotionEvent* other, bool keepHistory);
void addSample(
nsecs_t eventTime,
const PointerCoords* pointerCoords);
void offsetLocation(float xOffset, float yOffset);
void scale(float scaleFactor);
// Apply 3x3 perspective matrix transformation.
// Matrix is in row-major form and compatible with SkMatrix.
void transform(const float matrix[9]);
#ifdef HAVE_ANDROID_OS
status_t readFromParcel(Parcel* parcel);
status_t writeToParcel(Parcel* parcel) const;
#endif
static bool isTouchEvent(int32_t source, int32_t action);
inline bool isTouchEvent() const {
return isTouchEvent(mSource, mAction);
}
// Low-level accessors.
inline const PointerProperties* getPointerProperties() const {
return mPointerProperties.array();
}
inline const nsecs_t* getSampleEventTimes() const { return mSampleEventTimes.array(); }
inline const PointerCoords* getSamplePointerCoords() const {
return mSamplePointerCoords.array();
}
static const char* getLabel(int32_t axis);
static int32_t getAxisFromLabel(const char* label);
protected:
int32_t mAction;
int32_t mActionButton;
int32_t mFlags;
int32_t mEdgeFlags;
int32_t mMetaState;
int32_t mButtonState;
float mXOffset;
float mYOffset;
float mXPrecision;
float mYPrecision;
nsecs_t mDownTime;
Vector<PointerProperties> mPointerProperties;
Vector<nsecs_t> mSampleEventTimes;
Vector<PointerCoords> mSamplePointerCoords;
};
/*
* Input event factory.
*/
class InputEventFactoryInterface {
protected:
virtual ~InputEventFactoryInterface() { }
public:
InputEventFactoryInterface() { }
virtual KeyEvent* createKeyEvent() = 0;
virtual MotionEvent* createMotionEvent() = 0;
};
/*
* A simple input event factory implementation that uses a single preallocated instance
* of each type of input event that are reused for each request.
*/
class PreallocatedInputEventFactory : public InputEventFactoryInterface {
public:
PreallocatedInputEventFactory() { }
virtual ~PreallocatedInputEventFactory() { }
virtual KeyEvent* createKeyEvent() { return & mKeyEvent; }
virtual MotionEvent* createMotionEvent() { return & mMotionEvent; }
private:
KeyEvent mKeyEvent;
MotionEvent mMotionEvent;
};
/*
* An input event factory implementation that maintains a pool of input events.
*/
class PooledInputEventFactory : public InputEventFactoryInterface {
public:
PooledInputEventFactory(size_t maxPoolSize = 20);
virtual ~PooledInputEventFactory();
virtual KeyEvent* createKeyEvent();
virtual MotionEvent* createMotionEvent();
void recycle(InputEvent* event);
private:
const size_t mMaxPoolSize;
Vector<KeyEvent*> mKeyEventPool;
Vector<MotionEvent*> mMotionEventPool;
};
} // namespace android
#endif // _LIBINPUT_INPUT_H
@@ -0,0 +1,170 @@
/*
* Copyright (C) 2012 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 _LIBINPUT_INPUT_DEVICE_H
#define _LIBINPUT_INPUT_DEVICE_H
#include <input/Input.h>
#include <input/KeyCharacterMap.h>
namespace android {
/*
* Identifies a device.
*/
struct InputDeviceIdentifier {
inline InputDeviceIdentifier() :
bus(0), vendor(0), product(0), version(0) {
}
// Information provided by the kernel.
String8 name;
String8 location;
String8 uniqueId;
uint16_t bus;
uint16_t vendor;
uint16_t product;
uint16_t version;
// A composite input device descriptor string that uniquely identifies the device
// even across reboots or reconnections. The value of this field is used by
// upper layers of the input system to associate settings with individual devices.
// It is hashed from whatever kernel provided information is available.
// Ideally, the way this value is computed should not change between Android releases
// because that would invalidate persistent settings that rely on it.
String8 descriptor;
// A value added to uniquely identify a device in the absence of a unique id. This
// is intended to be a minimum way to distinguish from other active devices and may
// reuse values that are not associated with an input anymore.
uint16_t nonce;
};
/*
* Describes the characteristics and capabilities of an input device.
*/
class InputDeviceInfo {
public:
InputDeviceInfo();
InputDeviceInfo(const InputDeviceInfo& other);
~InputDeviceInfo();
struct MotionRange {
int32_t axis;
uint32_t source;
float min;
float max;
float flat;
float fuzz;
float resolution;
};
void initialize(int32_t id, int32_t generation, int32_t controllerNumber,
const InputDeviceIdentifier& identifier, const String8& alias, bool isExternal,
bool hasMic);
inline int32_t getId() const { return mId; }
inline int32_t getControllerNumber() const { return mControllerNumber; }
inline int32_t getGeneration() const { return mGeneration; }
inline const InputDeviceIdentifier& getIdentifier() const { return mIdentifier; }
inline const String8& getAlias() const { return mAlias; }
inline const String8& getDisplayName() const {
return mAlias.isEmpty() ? mIdentifier.name : mAlias;
}
inline bool isExternal() const { return mIsExternal; }
inline bool hasMic() const { return mHasMic; }
inline uint32_t getSources() const { return mSources; }
const MotionRange* getMotionRange(int32_t axis, uint32_t source) const;
void addSource(uint32_t source);
void addMotionRange(int32_t axis, uint32_t source,
float min, float max, float flat, float fuzz, float resolution);
void addMotionRange(const MotionRange& range);
inline void setKeyboardType(int32_t keyboardType) { mKeyboardType = keyboardType; }
inline int32_t getKeyboardType() const { return mKeyboardType; }
inline void setKeyCharacterMap(const sp<KeyCharacterMap>& value) {
mKeyCharacterMap = value;
}
inline sp<KeyCharacterMap> getKeyCharacterMap() const {
return mKeyCharacterMap;
}
inline void setVibrator(bool hasVibrator) { mHasVibrator = hasVibrator; }
inline bool hasVibrator() const { return mHasVibrator; }
inline void setButtonUnderPad(bool hasButton) { mHasButtonUnderPad = hasButton; }
inline bool hasButtonUnderPad() const { return mHasButtonUnderPad; }
inline const Vector<MotionRange>& getMotionRanges() const {
return mMotionRanges;
}
private:
int32_t mId;
int32_t mGeneration;
int32_t mControllerNumber;
InputDeviceIdentifier mIdentifier;
String8 mAlias;
bool mIsExternal;
bool mHasMic;
uint32_t mSources;
int32_t mKeyboardType;
sp<KeyCharacterMap> mKeyCharacterMap;
bool mHasVibrator;
bool mHasButtonUnderPad;
Vector<MotionRange> mMotionRanges;
};
/* Types of input device configuration files. */
enum InputDeviceConfigurationFileType {
INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION = 0, /* .idc file */
INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT = 1, /* .kl file */
INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP = 2, /* .kcm file */
};
/*
* Gets the path of an input device configuration file, if one is available.
* Considers both system provided and user installed configuration files.
*
* The device identifier is used to construct several default configuration file
* names to try based on the device name, vendor, product, and version.
*
* Returns an empty string if not found.
*/
extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
const InputDeviceIdentifier& deviceIdentifier,
InputDeviceConfigurationFileType type);
/*
* Gets the path of an input device configuration file, if one is available.
* Considers both system provided and user installed configuration files.
*
* The name is case-sensitive and is used to construct the filename to resolve.
* All characters except 'a'-'z', 'A'-'Z', '0'-'9', '-', and '_' are replaced by underscores.
*
* Returns an empty string if not found.
*/
extern String8 getInputDeviceConfigurationFilePathByName(
const String8& name, InputDeviceConfigurationFileType type);
} // namespace android
#endif // _LIBINPUT_INPUT_DEVICE_H
@@ -0,0 +1,447 @@
/*
* 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 _LIBINPUT_INPUT_EVENT_LABELS_H
#define _LIBINPUT_INPUT_EVENT_LABELS_H
#include <input/Input.h>
#include <android/keycodes.h>
#define DEFINE_KEYCODE(key) { #key, AKEYCODE_##key }
#define DEFINE_AXIS(axis) { #axis, AMOTION_EVENT_AXIS_##axis }
#define DEFINE_LED(led) { #led, ALED_##led }
#define DEFINE_FLAG(flag) { #flag, POLICY_FLAG_##flag }
namespace android {
template<typename T, size_t N>
size_t size(T (&)[N]) { return N; }
struct InputEventLabel {
const char *literal;
int value;
};
static const InputEventLabel KEYCODES[] = {
// NOTE: If you add a new keycode here you must also add it to several other files.
// Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
DEFINE_KEYCODE(UNKNOWN),
DEFINE_KEYCODE(SOFT_LEFT),
DEFINE_KEYCODE(SOFT_RIGHT),
DEFINE_KEYCODE(HOME),
DEFINE_KEYCODE(BACK),
DEFINE_KEYCODE(CALL),
DEFINE_KEYCODE(ENDCALL),
DEFINE_KEYCODE(0),
DEFINE_KEYCODE(1),
DEFINE_KEYCODE(2),
DEFINE_KEYCODE(3),
DEFINE_KEYCODE(4),
DEFINE_KEYCODE(5),
DEFINE_KEYCODE(6),
DEFINE_KEYCODE(7),
DEFINE_KEYCODE(8),
DEFINE_KEYCODE(9),
DEFINE_KEYCODE(STAR),
DEFINE_KEYCODE(POUND),
DEFINE_KEYCODE(DPAD_UP),
DEFINE_KEYCODE(DPAD_DOWN),
DEFINE_KEYCODE(DPAD_LEFT),
DEFINE_KEYCODE(DPAD_RIGHT),
DEFINE_KEYCODE(DPAD_CENTER),
DEFINE_KEYCODE(VOLUME_UP),
DEFINE_KEYCODE(VOLUME_DOWN),
DEFINE_KEYCODE(POWER),
DEFINE_KEYCODE(CAMERA),
DEFINE_KEYCODE(CLEAR),
DEFINE_KEYCODE(A),
DEFINE_KEYCODE(B),
DEFINE_KEYCODE(C),
DEFINE_KEYCODE(D),
DEFINE_KEYCODE(E),
DEFINE_KEYCODE(F),
DEFINE_KEYCODE(G),
DEFINE_KEYCODE(H),
DEFINE_KEYCODE(I),
DEFINE_KEYCODE(J),
DEFINE_KEYCODE(K),
DEFINE_KEYCODE(L),
DEFINE_KEYCODE(M),
DEFINE_KEYCODE(N),
DEFINE_KEYCODE(O),
DEFINE_KEYCODE(P),
DEFINE_KEYCODE(Q),
DEFINE_KEYCODE(R),
DEFINE_KEYCODE(S),
DEFINE_KEYCODE(T),
DEFINE_KEYCODE(U),
DEFINE_KEYCODE(V),
DEFINE_KEYCODE(W),
DEFINE_KEYCODE(X),
DEFINE_KEYCODE(Y),
DEFINE_KEYCODE(Z),
DEFINE_KEYCODE(COMMA),
DEFINE_KEYCODE(PERIOD),
DEFINE_KEYCODE(ALT_LEFT),
DEFINE_KEYCODE(ALT_RIGHT),
DEFINE_KEYCODE(SHIFT_LEFT),
DEFINE_KEYCODE(SHIFT_RIGHT),
DEFINE_KEYCODE(TAB),
DEFINE_KEYCODE(SPACE),
DEFINE_KEYCODE(SYM),
DEFINE_KEYCODE(EXPLORER),
DEFINE_KEYCODE(ENVELOPE),
DEFINE_KEYCODE(ENTER),
DEFINE_KEYCODE(DEL),
DEFINE_KEYCODE(GRAVE),
DEFINE_KEYCODE(MINUS),
DEFINE_KEYCODE(EQUALS),
DEFINE_KEYCODE(LEFT_BRACKET),
DEFINE_KEYCODE(RIGHT_BRACKET),
DEFINE_KEYCODE(BACKSLASH),
DEFINE_KEYCODE(SEMICOLON),
DEFINE_KEYCODE(APOSTROPHE),
DEFINE_KEYCODE(SLASH),
DEFINE_KEYCODE(AT),
DEFINE_KEYCODE(NUM),
DEFINE_KEYCODE(HEADSETHOOK),
DEFINE_KEYCODE(FOCUS), // *Camera* focus
DEFINE_KEYCODE(PLUS),
DEFINE_KEYCODE(MENU),
DEFINE_KEYCODE(NOTIFICATION),
DEFINE_KEYCODE(SEARCH),
DEFINE_KEYCODE(MEDIA_PLAY_PAUSE),
DEFINE_KEYCODE(MEDIA_STOP),
DEFINE_KEYCODE(MEDIA_NEXT),
DEFINE_KEYCODE(MEDIA_PREVIOUS),
DEFINE_KEYCODE(MEDIA_REWIND),
DEFINE_KEYCODE(MEDIA_FAST_FORWARD),
DEFINE_KEYCODE(MUTE),
DEFINE_KEYCODE(PAGE_UP),
DEFINE_KEYCODE(PAGE_DOWN),
DEFINE_KEYCODE(PICTSYMBOLS),
DEFINE_KEYCODE(SWITCH_CHARSET),
DEFINE_KEYCODE(BUTTON_A),
DEFINE_KEYCODE(BUTTON_B),
DEFINE_KEYCODE(BUTTON_C),
DEFINE_KEYCODE(BUTTON_X),
DEFINE_KEYCODE(BUTTON_Y),
DEFINE_KEYCODE(BUTTON_Z),
DEFINE_KEYCODE(BUTTON_L1),
DEFINE_KEYCODE(BUTTON_R1),
DEFINE_KEYCODE(BUTTON_L2),
DEFINE_KEYCODE(BUTTON_R2),
DEFINE_KEYCODE(BUTTON_THUMBL),
DEFINE_KEYCODE(BUTTON_THUMBR),
DEFINE_KEYCODE(BUTTON_START),
DEFINE_KEYCODE(BUTTON_SELECT),
DEFINE_KEYCODE(BUTTON_MODE),
DEFINE_KEYCODE(ESCAPE),
DEFINE_KEYCODE(FORWARD_DEL),
DEFINE_KEYCODE(CTRL_LEFT),
DEFINE_KEYCODE(CTRL_RIGHT),
DEFINE_KEYCODE(CAPS_LOCK),
DEFINE_KEYCODE(SCROLL_LOCK),
DEFINE_KEYCODE(META_LEFT),
DEFINE_KEYCODE(META_RIGHT),
DEFINE_KEYCODE(FUNCTION),
DEFINE_KEYCODE(SYSRQ),
DEFINE_KEYCODE(BREAK),
DEFINE_KEYCODE(MOVE_HOME),
DEFINE_KEYCODE(MOVE_END),
DEFINE_KEYCODE(INSERT),
DEFINE_KEYCODE(FORWARD),
DEFINE_KEYCODE(MEDIA_PLAY),
DEFINE_KEYCODE(MEDIA_PAUSE),
DEFINE_KEYCODE(MEDIA_CLOSE),
DEFINE_KEYCODE(MEDIA_EJECT),
DEFINE_KEYCODE(MEDIA_RECORD),
DEFINE_KEYCODE(F1),
DEFINE_KEYCODE(F2),
DEFINE_KEYCODE(F3),
DEFINE_KEYCODE(F4),
DEFINE_KEYCODE(F5),
DEFINE_KEYCODE(F6),
DEFINE_KEYCODE(F7),
DEFINE_KEYCODE(F8),
DEFINE_KEYCODE(F9),
DEFINE_KEYCODE(F10),
DEFINE_KEYCODE(F11),
DEFINE_KEYCODE(F12),
DEFINE_KEYCODE(NUM_LOCK),
DEFINE_KEYCODE(NUMPAD_0),
DEFINE_KEYCODE(NUMPAD_1),
DEFINE_KEYCODE(NUMPAD_2),
DEFINE_KEYCODE(NUMPAD_3),
DEFINE_KEYCODE(NUMPAD_4),
DEFINE_KEYCODE(NUMPAD_5),
DEFINE_KEYCODE(NUMPAD_6),
DEFINE_KEYCODE(NUMPAD_7),
DEFINE_KEYCODE(NUMPAD_8),
DEFINE_KEYCODE(NUMPAD_9),
DEFINE_KEYCODE(NUMPAD_DIVIDE),
DEFINE_KEYCODE(NUMPAD_MULTIPLY),
DEFINE_KEYCODE(NUMPAD_SUBTRACT),
DEFINE_KEYCODE(NUMPAD_ADD),
DEFINE_KEYCODE(NUMPAD_DOT),
DEFINE_KEYCODE(NUMPAD_COMMA),
DEFINE_KEYCODE(NUMPAD_ENTER),
DEFINE_KEYCODE(NUMPAD_EQUALS),
DEFINE_KEYCODE(NUMPAD_LEFT_PAREN),
DEFINE_KEYCODE(NUMPAD_RIGHT_PAREN),
DEFINE_KEYCODE(VOLUME_MUTE),
DEFINE_KEYCODE(INFO),
DEFINE_KEYCODE(CHANNEL_UP),
DEFINE_KEYCODE(CHANNEL_DOWN),
DEFINE_KEYCODE(ZOOM_IN),
DEFINE_KEYCODE(ZOOM_OUT),
DEFINE_KEYCODE(TV),
DEFINE_KEYCODE(WINDOW),
DEFINE_KEYCODE(GUIDE),
DEFINE_KEYCODE(DVR),
DEFINE_KEYCODE(BOOKMARK),
DEFINE_KEYCODE(CAPTIONS),
DEFINE_KEYCODE(SETTINGS),
DEFINE_KEYCODE(TV_POWER),
DEFINE_KEYCODE(TV_INPUT),
DEFINE_KEYCODE(STB_POWER),
DEFINE_KEYCODE(STB_INPUT),
DEFINE_KEYCODE(AVR_POWER),
DEFINE_KEYCODE(AVR_INPUT),
DEFINE_KEYCODE(PROG_RED),
DEFINE_KEYCODE(PROG_GREEN),
DEFINE_KEYCODE(PROG_YELLOW),
DEFINE_KEYCODE(PROG_BLUE),
DEFINE_KEYCODE(APP_SWITCH),
DEFINE_KEYCODE(BUTTON_1),
DEFINE_KEYCODE(BUTTON_2),
DEFINE_KEYCODE(BUTTON_3),
DEFINE_KEYCODE(BUTTON_4),
DEFINE_KEYCODE(BUTTON_5),
DEFINE_KEYCODE(BUTTON_6),
DEFINE_KEYCODE(BUTTON_7),
DEFINE_KEYCODE(BUTTON_8),
DEFINE_KEYCODE(BUTTON_9),
DEFINE_KEYCODE(BUTTON_10),
DEFINE_KEYCODE(BUTTON_11),
DEFINE_KEYCODE(BUTTON_12),
DEFINE_KEYCODE(BUTTON_13),
DEFINE_KEYCODE(BUTTON_14),
DEFINE_KEYCODE(BUTTON_15),
DEFINE_KEYCODE(BUTTON_16),
DEFINE_KEYCODE(LANGUAGE_SWITCH),
DEFINE_KEYCODE(MANNER_MODE),
DEFINE_KEYCODE(3D_MODE),
DEFINE_KEYCODE(CONTACTS),
DEFINE_KEYCODE(CALENDAR),
DEFINE_KEYCODE(MUSIC),
DEFINE_KEYCODE(CALCULATOR),
DEFINE_KEYCODE(ZENKAKU_HANKAKU),
DEFINE_KEYCODE(EISU),
DEFINE_KEYCODE(MUHENKAN),
DEFINE_KEYCODE(HENKAN),
DEFINE_KEYCODE(KATAKANA_HIRAGANA),
DEFINE_KEYCODE(YEN),
DEFINE_KEYCODE(RO),
DEFINE_KEYCODE(KANA),
DEFINE_KEYCODE(ASSIST),
DEFINE_KEYCODE(BRIGHTNESS_DOWN),
DEFINE_KEYCODE(BRIGHTNESS_UP),
DEFINE_KEYCODE(MEDIA_AUDIO_TRACK),
DEFINE_KEYCODE(SLEEP),
DEFINE_KEYCODE(WAKEUP),
DEFINE_KEYCODE(PAIRING),
DEFINE_KEYCODE(MEDIA_TOP_MENU),
DEFINE_KEYCODE(11),
DEFINE_KEYCODE(12),
DEFINE_KEYCODE(LAST_CHANNEL),
DEFINE_KEYCODE(TV_DATA_SERVICE),
DEFINE_KEYCODE(VOICE_ASSIST),
DEFINE_KEYCODE(TV_RADIO_SERVICE),
DEFINE_KEYCODE(TV_TELETEXT),
DEFINE_KEYCODE(TV_NUMBER_ENTRY),
DEFINE_KEYCODE(TV_TERRESTRIAL_ANALOG),
DEFINE_KEYCODE(TV_TERRESTRIAL_DIGITAL),
DEFINE_KEYCODE(TV_SATELLITE),
DEFINE_KEYCODE(TV_SATELLITE_BS),
DEFINE_KEYCODE(TV_SATELLITE_CS),
DEFINE_KEYCODE(TV_SATELLITE_SERVICE),
DEFINE_KEYCODE(TV_NETWORK),
DEFINE_KEYCODE(TV_ANTENNA_CABLE),
DEFINE_KEYCODE(TV_INPUT_HDMI_1),
DEFINE_KEYCODE(TV_INPUT_HDMI_2),
DEFINE_KEYCODE(TV_INPUT_HDMI_3),
DEFINE_KEYCODE(TV_INPUT_HDMI_4),
DEFINE_KEYCODE(TV_INPUT_COMPOSITE_1),
DEFINE_KEYCODE(TV_INPUT_COMPOSITE_2),
DEFINE_KEYCODE(TV_INPUT_COMPONENT_1),
DEFINE_KEYCODE(TV_INPUT_COMPONENT_2),
DEFINE_KEYCODE(TV_INPUT_VGA_1),
DEFINE_KEYCODE(TV_AUDIO_DESCRIPTION),
DEFINE_KEYCODE(TV_AUDIO_DESCRIPTION_MIX_UP),
DEFINE_KEYCODE(TV_AUDIO_DESCRIPTION_MIX_DOWN),
DEFINE_KEYCODE(TV_ZOOM_MODE),
DEFINE_KEYCODE(TV_CONTENTS_MENU),
DEFINE_KEYCODE(TV_MEDIA_CONTEXT_MENU),
DEFINE_KEYCODE(TV_TIMER_PROGRAMMING),
DEFINE_KEYCODE(HELP),
DEFINE_KEYCODE(NAVIGATE_PREVIOUS),
DEFINE_KEYCODE(NAVIGATE_NEXT),
DEFINE_KEYCODE(NAVIGATE_IN),
DEFINE_KEYCODE(NAVIGATE_OUT),
DEFINE_KEYCODE(STEM_PRIMARY),
DEFINE_KEYCODE(STEM_1),
DEFINE_KEYCODE(STEM_2),
DEFINE_KEYCODE(STEM_3),
DEFINE_KEYCODE(MEDIA_SKIP_FORWARD),
DEFINE_KEYCODE(MEDIA_SKIP_BACKWARD),
DEFINE_KEYCODE(MEDIA_STEP_FORWARD),
DEFINE_KEYCODE(MEDIA_STEP_BACKWARD),
DEFINE_KEYCODE(SOFT_SLEEP),
{ NULL, 0 }
};
static const InputEventLabel AXES[] = {
DEFINE_AXIS(X),
DEFINE_AXIS(Y),
DEFINE_AXIS(PRESSURE),
DEFINE_AXIS(SIZE),
DEFINE_AXIS(TOUCH_MAJOR),
DEFINE_AXIS(TOUCH_MINOR),
DEFINE_AXIS(TOOL_MAJOR),
DEFINE_AXIS(TOOL_MINOR),
DEFINE_AXIS(ORIENTATION),
DEFINE_AXIS(VSCROLL),
DEFINE_AXIS(HSCROLL),
DEFINE_AXIS(Z),
DEFINE_AXIS(RX),
DEFINE_AXIS(RY),
DEFINE_AXIS(RZ),
DEFINE_AXIS(HAT_X),
DEFINE_AXIS(HAT_Y),
DEFINE_AXIS(LTRIGGER),
DEFINE_AXIS(RTRIGGER),
DEFINE_AXIS(THROTTLE),
DEFINE_AXIS(RUDDER),
DEFINE_AXIS(WHEEL),
DEFINE_AXIS(GAS),
DEFINE_AXIS(BRAKE),
DEFINE_AXIS(DISTANCE),
DEFINE_AXIS(TILT),
DEFINE_AXIS(GENERIC_1),
DEFINE_AXIS(GENERIC_2),
DEFINE_AXIS(GENERIC_3),
DEFINE_AXIS(GENERIC_4),
DEFINE_AXIS(GENERIC_5),
DEFINE_AXIS(GENERIC_6),
DEFINE_AXIS(GENERIC_7),
DEFINE_AXIS(GENERIC_8),
DEFINE_AXIS(GENERIC_9),
DEFINE_AXIS(GENERIC_10),
DEFINE_AXIS(GENERIC_11),
DEFINE_AXIS(GENERIC_12),
DEFINE_AXIS(GENERIC_13),
DEFINE_AXIS(GENERIC_14),
DEFINE_AXIS(GENERIC_15),
DEFINE_AXIS(GENERIC_16),
// NOTE: If you add a new axis here you must also add it to several other files.
// Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
{ NULL, 0 }
};
static const InputEventLabel LEDS[] = {
DEFINE_LED(NUM_LOCK),
DEFINE_LED(CAPS_LOCK),
DEFINE_LED(SCROLL_LOCK),
DEFINE_LED(COMPOSE),
DEFINE_LED(KANA),
DEFINE_LED(SLEEP),
DEFINE_LED(SUSPEND),
DEFINE_LED(MUTE),
DEFINE_LED(MISC),
DEFINE_LED(MAIL),
DEFINE_LED(CHARGING),
DEFINE_LED(CONTROLLER_1),
DEFINE_LED(CONTROLLER_2),
DEFINE_LED(CONTROLLER_3),
DEFINE_LED(CONTROLLER_4),
// NOTE: If you add new LEDs here, you must also add them to Input.h
{ NULL, 0 }
};
static const InputEventLabel FLAGS[] = {
DEFINE_FLAG(WAKE),
DEFINE_FLAG(VIRTUAL),
DEFINE_FLAG(FUNCTION),
DEFINE_FLAG(GESTURE),
{ NULL, 0 }
};
static int lookupValueByLabel(const char* literal, const InputEventLabel *list) {
while (list->literal) {
if (strcmp(literal, list->literal) == 0) {
return list->value;
}
list++;
}
return list->value;
}
static const char* lookupLabelByValue(int value, const InputEventLabel* list) {
while (list->literal) {
if (list->value == value) {
return list->literal;
}
list++;
}
return NULL;
}
static int32_t getKeyCodeByLabel(const char* label) {
return int32_t(lookupValueByLabel(label, KEYCODES));
}
static const char* getLabelByKeyCode(int32_t keyCode) {
if (keyCode >= 0 && keyCode < size(KEYCODES)) {
return KEYCODES[keyCode].literal;
}
return NULL;
}
static uint32_t getKeyFlagByLabel(const char* label) {
return uint32_t(lookupValueByLabel(label, FLAGS));
}
static int32_t getAxisByLabel(const char* label) {
return int32_t(lookupValueByLabel(label, AXES));
}
static const char* getAxisLabel(int32_t axisId) {
return lookupLabelByValue(axisId, AXES);
}
static int32_t getLedByLabel(const char* label) {
return int32_t(lookupValueByLabel(label, LEDS));
}
} // namespace android
#endif // _LIBINPUT_INPUT_EVENT_LABELS_H
@@ -0,0 +1,453 @@
/*
* 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 _LIBINPUT_INPUT_TRANSPORT_H
#define _LIBINPUT_INPUT_TRANSPORT_H
/**
* Native input transport.
*
* The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
*
* The InputPublisher and InputConsumer each handle one end-point of an input channel.
* The InputPublisher is used by the input dispatcher to send events to the application.
* The InputConsumer is used by the application to receive events from the input dispatcher.
*/
#include <input/Input.h>
#include <utils/Errors.h>
#include <utils/Timers.h>
#include <utils/RefBase.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/BitSet.h>
namespace android {
/*
* Intermediate representation used to send input events and related signals.
*
* Note that this structure is used for IPCs so its layout must be identical
* on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
*/
struct InputMessage {
enum {
TYPE_KEY = 1,
TYPE_MOTION = 2,
TYPE_FINISHED = 3,
};
struct Header {
uint32_t type;
// We don't need this field in order to align the body below but we
// leave it here because InputMessage::size() and other functions
// compute the size of this structure as sizeof(Header) + sizeof(Body).
uint32_t padding;
} header;
// Body *must* be 8 byte aligned.
union Body {
struct Key {
uint32_t seq;
nsecs_t eventTime __attribute__((aligned(8)));
int32_t deviceId;
int32_t source;
int32_t action;
int32_t flags;
int32_t keyCode;
int32_t scanCode;
int32_t metaState;
int32_t repeatCount;
nsecs_t downTime __attribute__((aligned(8)));
inline size_t size() const {
return sizeof(Key);
}
} key;
struct Motion {
uint32_t seq;
nsecs_t eventTime __attribute__((aligned(8)));
int32_t deviceId;
int32_t source;
int32_t action;
int32_t actionButton;
int32_t flags;
int32_t metaState;
int32_t buttonState;
int32_t edgeFlags;
nsecs_t downTime __attribute__((aligned(8)));
float xOffset;
float yOffset;
float xPrecision;
float yPrecision;
uint32_t pointerCount;
// Note that PointerCoords requires 8 byte alignment.
struct Pointer {
PointerProperties properties;
PointerCoords coords;
} pointers[MAX_POINTERS];
int32_t getActionId() const {
uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
>> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
return pointers[index].properties.id;
}
inline size_t size() const {
return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
+ sizeof(Pointer) * pointerCount;
}
} motion;
struct Finished {
uint32_t seq;
bool handled;
inline size_t size() const {
return sizeof(Finished);
}
} finished;
} __attribute__((aligned(8))) body;
bool isValid(size_t actualSize) const;
size_t size() const;
};
/*
* An input channel consists of a local unix domain socket used to send and receive
* input messages across processes. Each channel has a descriptive name for debugging purposes.
*
* Each endpoint has its own InputChannel object that specifies its file descriptor.
*
* The input channel is closed when all references to it are released.
*/
class InputChannel : public RefBase {
protected:
virtual ~InputChannel();
public:
InputChannel(const String8& name, int fd);
/* Creates a pair of input channels.
*
* Returns OK on success.
*/
static status_t openInputChannelPair(const String8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
inline String8 getName() const { return mName; }
inline int getFd() const { return mFd; }
/* Sends a message to the other endpoint.
*
* If the channel is full then the message is guaranteed not to have been sent at all.
* Try again after the consumer has sent a finished signal indicating that it has
* consumed some of the pending messages from the channel.
*
* Returns OK on success.
* Returns WOULD_BLOCK if the channel is full.
* Returns DEAD_OBJECT if the channel's peer has been closed.
* Other errors probably indicate that the channel is broken.
*/
status_t sendMessage(const InputMessage* msg);
/* Receives a message sent by the other endpoint.
*
* If there is no message present, try again after poll() indicates that the fd
* is readable.
*
* Returns OK on success.
* Returns WOULD_BLOCK if there is no message present.
* Returns DEAD_OBJECT if the channel's peer has been closed.
* Other errors probably indicate that the channel is broken.
*/
status_t receiveMessage(InputMessage* msg);
/* Returns a new object that has a duplicate of this channel's fd. */
sp<InputChannel> dup() const;
private:
String8 mName;
int mFd;
};
/*
* Publishes input events to an input channel.
*/
class InputPublisher {
public:
/* Creates a publisher associated with an input channel. */
explicit InputPublisher(const sp<InputChannel>& channel);
/* Destroys the publisher and releases its input channel. */
~InputPublisher();
/* Gets the underlying input channel. */
inline sp<InputChannel> getChannel() { return mChannel; }
/* Publishes a key event to the input channel.
*
* Returns OK on success.
* Returns WOULD_BLOCK if the channel is full.
* Returns DEAD_OBJECT if the channel's peer has been closed.
* Returns BAD_VALUE if seq is 0.
* Other errors probably indicate that the channel is broken.
*/
status_t publishKeyEvent(
uint32_t seq,
int32_t deviceId,
int32_t source,
int32_t action,
int32_t flags,
int32_t keyCode,
int32_t scanCode,
int32_t metaState,
int32_t repeatCount,
nsecs_t downTime,
nsecs_t eventTime);
/* Publishes a motion event to the input channel.
*
* Returns OK on success.
* Returns WOULD_BLOCK if the channel is full.
* Returns DEAD_OBJECT if the channel's peer has been closed.
* Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
* Other errors probably indicate that the channel is broken.
*/
status_t publishMotionEvent(
uint32_t seq,
int32_t deviceId,
int32_t source,
int32_t action,
int32_t actionButton,
int32_t flags,
int32_t edgeFlags,
int32_t metaState,
int32_t buttonState,
float xOffset,
float yOffset,
float xPrecision,
float yPrecision,
nsecs_t downTime,
nsecs_t eventTime,
uint32_t pointerCount,
const PointerProperties* pointerProperties,
const PointerCoords* pointerCoords);
/* Receives the finished signal from the consumer in reply to the original dispatch signal.
* If a signal was received, returns the message sequence number,
* and whether the consumer handled the message.
*
* The returned sequence number is never 0 unless the operation failed.
*
* Returns OK on success.
* Returns WOULD_BLOCK if there is no signal present.
* Returns DEAD_OBJECT if the channel's peer has been closed.
* Other errors probably indicate that the channel is broken.
*/
status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
private:
sp<InputChannel> mChannel;
};
/*
* Consumes input events from an input channel.
*/
class InputConsumer {
public:
/* Creates a consumer associated with an input channel. */
explicit InputConsumer(const sp<InputChannel>& channel);
/* Destroys the consumer and releases its input channel. */
~InputConsumer();
/* Gets the underlying input channel. */
inline sp<InputChannel> getChannel() { return mChannel; }
/* Consumes an input event from the input channel and copies its contents into
* an InputEvent object created using the specified factory.
*
* Tries to combine a series of move events into larger batches whenever possible.
*
* If consumeBatches is false, then defers consuming pending batched events if it
* is possible for additional samples to be added to them later. Call hasPendingBatch()
* to determine whether a pending batch is available to be consumed.
*
* If consumeBatches is true, then events are still batched but they are consumed
* immediately as soon as the input channel is exhausted.
*
* The frameTime parameter specifies the time when the current display frame started
* rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
*
* The returned sequence number is never 0 unless the operation failed.
*
* Returns OK on success.
* Returns WOULD_BLOCK if there is no event present.
* Returns DEAD_OBJECT if the channel's peer has been closed.
* Returns NO_MEMORY if the event could not be created.
* Other errors probably indicate that the channel is broken.
*/
status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
/* Sends a finished signal to the publisher to inform it that the message
* with the specified sequence number has finished being process and whether
* the message was handled by the consumer.
*
* Returns OK on success.
* Returns BAD_VALUE if seq is 0.
* Other errors probably indicate that the channel is broken.
*/
status_t sendFinishedSignal(uint32_t seq, bool handled);
/* Returns true if there is a deferred event waiting.
*
* Should be called after calling consume() to determine whether the consumer
* has a deferred event to be processed. Deferred events are somewhat special in
* that they have already been removed from the input channel. If the input channel
* becomes empty, the client may need to do extra work to ensure that it processes
* the deferred event despite the fact that the input channel's file descriptor
* is not readable.
*
* One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
* This guarantees that all deferred events will be processed.
*
* Alternately, the caller can call hasDeferredEvent() to determine whether there is
* a deferred event waiting and then ensure that its event loop wakes up at least
* one more time to consume the deferred event.
*/
bool hasDeferredEvent() const;
/* Returns true if there is a pending batch.
*
* Should be called after calling consume() with consumeBatches == false to determine
* whether consume() should be called again later on with consumeBatches == true.
*/
bool hasPendingBatch() const;
private:
// True if touch resampling is enabled.
const bool mResampleTouch;
// The input channel.
sp<InputChannel> mChannel;
// The current input message.
InputMessage mMsg;
// True if mMsg contains a valid input message that was deferred from the previous
// call to consume and that still needs to be handled.
bool mMsgDeferred;
// Batched motion events per device and source.
struct Batch {
Vector<InputMessage> samples;
};
Vector<Batch> mBatches;
// Touch state per device and source, only for sources of class pointer.
struct History {
nsecs_t eventTime;
BitSet32 idBits;
int32_t idToIndex[MAX_POINTER_ID + 1];
PointerCoords pointers[MAX_POINTERS];
void initializeFrom(const InputMessage* msg) {
eventTime = msg->body.motion.eventTime;
idBits.clear();
for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) {
uint32_t id = msg->body.motion.pointers[i].properties.id;
idBits.markBit(id);
idToIndex[id] = i;
pointers[i].copyFrom(msg->body.motion.pointers[i].coords);
}
}
const PointerCoords& getPointerById(uint32_t id) const {
return pointers[idToIndex[id]];
}
};
struct TouchState {
int32_t deviceId;
int32_t source;
size_t historyCurrent;
size_t historySize;
History history[2];
History lastResample;
void initialize(int32_t deviceId, int32_t source) {
this->deviceId = deviceId;
this->source = source;
historyCurrent = 0;
historySize = 0;
lastResample.eventTime = 0;
lastResample.idBits.clear();
}
void addHistory(const InputMessage* msg) {
historyCurrent ^= 1;
if (historySize < 2) {
historySize += 1;
}
history[historyCurrent].initializeFrom(msg);
}
const History* getHistory(size_t index) const {
return &history[(historyCurrent + index) & 1];
}
};
Vector<TouchState> mTouchStates;
// Chain of batched sequence numbers. When multiple input messages are combined into
// a batch, we append a record here that associates the last sequence number in the
// batch with the previous one. When the finished signal is sent, we traverse the
// chain to individually finish all input messages that were part of the batch.
struct SeqChain {
uint32_t seq; // sequence number of batched input message
uint32_t chain; // sequence number of previous batched input message
};
Vector<SeqChain> mSeqChains;
status_t consumeBatch(InputEventFactoryInterface* factory,
nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
status_t consumeSamples(InputEventFactoryInterface* factory,
Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
void updateTouchState(InputMessage* msg);
void rewriteMessage(const TouchState& state, InputMessage* msg);
void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
const InputMessage *next);
ssize_t findBatch(int32_t deviceId, int32_t source) const;
ssize_t findTouchState(int32_t deviceId, int32_t source) const;
status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
static void addSample(MotionEvent* event, const InputMessage* msg);
static bool canAddSample(const Batch& batch, const InputMessage* msg);
static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
static bool shouldResampleTool(int32_t toolType);
static bool isTouchResamplingEnabled();
};
} // namespace android
#endif // _LIBINPUT_INPUT_TRANSPORT_H
@@ -0,0 +1,265 @@
/*
* 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 _LIBINPUT_KEY_CHARACTER_MAP_H
#define _LIBINPUT_KEY_CHARACTER_MAP_H
#include <stdint.h>
#if HAVE_ANDROID_OS
#include <binder/IBinder.h>
#endif
#include <input/Input.h>
#include <utils/Errors.h>
#include <utils/KeyedVector.h>
#include <utils/Tokenizer.h>
#include <utils/String8.h>
#include <utils/Unicode.h>
#include <utils/RefBase.h>
namespace android {
/**
* Describes a mapping from Android key codes to characters.
* Also specifies other functions of the keyboard such as the keyboard type
* and key modifier semantics.
*
* This object is immutable after it has been loaded.
*/
class KeyCharacterMap : public RefBase {
public:
enum KeyboardType {
KEYBOARD_TYPE_UNKNOWN = 0,
KEYBOARD_TYPE_NUMERIC = 1,
KEYBOARD_TYPE_PREDICTIVE = 2,
KEYBOARD_TYPE_ALPHA = 3,
KEYBOARD_TYPE_FULL = 4,
KEYBOARD_TYPE_SPECIAL_FUNCTION = 5,
KEYBOARD_TYPE_OVERLAY = 6,
};
enum Format {
// Base keyboard layout, may contain device-specific options, such as "type" declaration.
FORMAT_BASE = 0,
// Overlay keyboard layout, more restrictive, may be published by applications,
// cannot override device-specific options.
FORMAT_OVERLAY = 1,
// Either base or overlay layout ok.
FORMAT_ANY = 2,
};
// Substitute key code and meta state for fallback action.
struct FallbackAction {
int32_t keyCode;
int32_t metaState;
};
/* Loads a key character map from a file. */
static status_t load(const String8& filename, Format format, sp<KeyCharacterMap>* outMap);
/* Loads a key character map from its string contents. */
static status_t loadContents(const String8& filename,
const char* contents, Format format, sp<KeyCharacterMap>* outMap);
/* Combines a base key character map and an overlay. */
static sp<KeyCharacterMap> combine(const sp<KeyCharacterMap>& base,
const sp<KeyCharacterMap>& overlay);
/* Returns an empty key character map. */
static sp<KeyCharacterMap> empty();
/* Gets the keyboard type. */
int32_t getKeyboardType() const;
/* Gets the primary character for this key as in the label physically printed on it.
* Returns 0 if none (eg. for non-printing keys). */
char16_t getDisplayLabel(int32_t keyCode) const;
/* Gets the Unicode character for the number or symbol generated by the key
* when the keyboard is used as a dialing pad.
* Returns 0 if no number or symbol is generated.
*/
char16_t getNumber(int32_t keyCode) const;
/* Gets the Unicode character generated by the key and meta key modifiers.
* Returns 0 if no character is generated.
*/
char16_t getCharacter(int32_t keyCode, int32_t metaState) const;
/* Gets the fallback action to use by default if the application does not
* handle the specified key.
* Returns true if an action was available, false if none.
*/
bool getFallbackAction(int32_t keyCode, int32_t metaState,
FallbackAction* outFallbackAction) const;
/* Gets the first matching Unicode character that can be generated by the key,
* preferring the one with the specified meta key modifiers.
* Returns 0 if no matching character is generated.
*/
char16_t getMatch(int32_t keyCode, const char16_t* chars,
size_t numChars, int32_t metaState) const;
/* Gets a sequence of key events that could plausibly generate the specified
* character sequence. Returns false if some of the characters cannot be generated.
*/
bool getEvents(int32_t deviceId, const char16_t* chars, size_t numChars,
Vector<KeyEvent>& outEvents) const;
/* Maps a scan code and usage code to a key code, in case this key map overrides
* the mapping in some way. */
status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode) const;
/* Tries to find a replacement key code for a given key code and meta state
* in character map. */
void tryRemapKey(int32_t scanCode, int32_t metaState,
int32_t* outKeyCode, int32_t* outMetaState) const;
#if HAVE_ANDROID_OS
/* Reads a key map from a parcel. */
static sp<KeyCharacterMap> readFromParcel(Parcel* parcel);
/* Writes a key map to a parcel. */
void writeToParcel(Parcel* parcel) const;
#endif
protected:
virtual ~KeyCharacterMap();
private:
struct Behavior {
Behavior();
Behavior(const Behavior& other);
/* The next behavior in the list, or NULL if none. */
Behavior* next;
/* The meta key modifiers for this behavior. */
int32_t metaState;
/* The character to insert. */
char16_t character;
/* The fallback keycode if the key is not handled. */
int32_t fallbackKeyCode;
/* The replacement keycode if the key has to be replaced outright. */
int32_t replacementKeyCode;
};
struct Key {
Key();
Key(const Key& other);
~Key();
/* The single character label printed on the key, or 0 if none. */
char16_t label;
/* The number or symbol character generated by the key, or 0 if none. */
char16_t number;
/* The list of key behaviors sorted from most specific to least specific
* meta key binding. */
Behavior* firstBehavior;
};
class Parser {
enum State {
STATE_TOP = 0,
STATE_KEY = 1,
};
enum {
PROPERTY_LABEL = 1,
PROPERTY_NUMBER = 2,
PROPERTY_META = 3,
};
struct Property {
inline Property(int32_t property = 0, int32_t metaState = 0) :
property(property), metaState(metaState) { }
int32_t property;
int32_t metaState;
};
KeyCharacterMap* mMap;
Tokenizer* mTokenizer;
Format mFormat;
State mState;
int32_t mKeyCode;
public:
Parser(KeyCharacterMap* map, Tokenizer* tokenizer, Format format);
~Parser();
status_t parse();
private:
status_t parseType();
status_t parseMap();
status_t parseMapKey();
status_t parseKey();
status_t parseKeyProperty();
status_t finishKey(Key* key);
status_t parseModifier(const String8& token, int32_t* outMetaState);
status_t parseCharacterLiteral(char16_t* outCharacter);
};
static sp<KeyCharacterMap> sEmpty;
KeyedVector<int32_t, Key*> mKeys;
int mType;
KeyedVector<int32_t, int32_t> mKeysByScanCode;
KeyedVector<int32_t, int32_t> mKeysByUsageCode;
KeyCharacterMap();
KeyCharacterMap(const KeyCharacterMap& other);
bool getKey(int32_t keyCode, const Key** outKey) const;
bool getKeyBehavior(int32_t keyCode, int32_t metaState,
const Key** outKey, const Behavior** outBehavior) const;
static bool matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState);
bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const;
static status_t load(Tokenizer* tokenizer, Format format, sp<KeyCharacterMap>* outMap);
static void addKey(Vector<KeyEvent>& outEvents,
int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time);
static void addMetaKeys(Vector<KeyEvent>& outEvents,
int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
int32_t* currentMetaState);
static bool addSingleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
int32_t keyCode, int32_t keyMetaState,
int32_t* currentMetaState);
static void addDoubleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
int32_t leftKeyCode, int32_t leftKeyMetaState,
int32_t rightKeyCode, int32_t rightKeyMetaState,
int32_t eitherKeyMetaState,
int32_t* currentMetaState);
static void addLockedMetaKey(Vector<KeyEvent>& outEvents,
int32_t deviceId, int32_t metaState, nsecs_t time,
int32_t keyCode, int32_t keyMetaState,
int32_t* currentMetaState);
};
} // namespace android
#endif // _LIBINPUT_KEY_CHARACTER_MAP_H
@@ -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 _LIBINPUT_KEY_LAYOUT_MAP_H
#define _LIBINPUT_KEY_LAYOUT_MAP_H
#include <stdint.h>
#include <utils/Errors.h>
#include <utils/KeyedVector.h>
#include <utils/Tokenizer.h>
#include <utils/RefBase.h>
namespace android {
struct AxisInfo {
enum Mode {
// Axis value is reported directly.
MODE_NORMAL = 0,
// Axis value should be inverted before reporting.
MODE_INVERT = 1,
// Axis value should be split into two axes
MODE_SPLIT = 2,
};
// Axis mode.
Mode mode;
// Axis id.
// When split, this is the axis used for values smaller than the split position.
int32_t axis;
// When split, this is the axis used for values after higher than the split position.
int32_t highAxis;
// The split value, or 0 if not split.
int32_t splitValue;
// The flat value, or -1 if none.
int32_t flatOverride;
AxisInfo() : mode(MODE_NORMAL), axis(-1), highAxis(-1), splitValue(0), flatOverride(-1) {
}
};
/**
* Describes a mapping from keyboard scan codes and joystick axes to Android key codes and axes.
*
* This object is immutable after it has been loaded.
*/
class KeyLayoutMap : public RefBase {
public:
static status_t load(const String8& filename, sp<KeyLayoutMap>* outMap);
status_t mapKey(int32_t scanCode, int32_t usageCode,
int32_t* outKeyCode, uint32_t* outFlags) const;
status_t findScanCodesForKey(int32_t keyCode, Vector<int32_t>* outScanCodes) const;
status_t findScanCodeForLed(int32_t ledCode, int32_t* outScanCode) const;
status_t findUsageCodeForLed(int32_t ledCode, int32_t* outUsageCode) const;
status_t mapAxis(int32_t scanCode, AxisInfo* outAxisInfo) const;
protected:
virtual ~KeyLayoutMap();
private:
struct Key {
int32_t keyCode;
uint32_t flags;
};
struct Led {
int32_t ledCode;
};
KeyedVector<int32_t, Key> mKeysByScanCode;
KeyedVector<int32_t, Key> mKeysByUsageCode;
KeyedVector<int32_t, AxisInfo> mAxes;
KeyedVector<int32_t, Led> mLedsByScanCode;
KeyedVector<int32_t, Led> mLedsByUsageCode;
KeyLayoutMap();
const Key* getKey(int32_t scanCode, int32_t usageCode) const;
class Parser {
KeyLayoutMap* mMap;
Tokenizer* mTokenizer;
public:
Parser(KeyLayoutMap* map, Tokenizer* tokenizer);
~Parser();
status_t parse();
private:
status_t parseKey();
status_t parseAxis();
status_t parseLed();
};
};
} // namespace android
#endif // _LIBINPUT_KEY_LAYOUT_MAP_H
@@ -0,0 +1,104 @@
/*
* 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 _LIBINPUT_KEYBOARD_H
#define _LIBINPUT_KEYBOARD_H
#include <input/Input.h>
#include <input/InputDevice.h>
#include <input/InputEventLabels.h>
#include <utils/Errors.h>
#include <utils/String8.h>
#include <utils/PropertyMap.h>
namespace android {
enum {
/* Device id of the built in keyboard. */
DEVICE_ID_BUILT_IN_KEYBOARD = 0,
/* Device id of a generic virtual keyboard with a full layout that can be used
* to synthesize key events. */
DEVICE_ID_VIRTUAL_KEYBOARD = -1,
};
class KeyLayoutMap;
class KeyCharacterMap;
/**
* Loads the key layout map and key character map for a keyboard device.
*/
class KeyMap {
public:
String8 keyLayoutFile;
sp<KeyLayoutMap> keyLayoutMap;
String8 keyCharacterMapFile;
sp<KeyCharacterMap> keyCharacterMap;
KeyMap();
~KeyMap();
status_t load(const InputDeviceIdentifier& deviceIdenfier,
const PropertyMap* deviceConfiguration);
inline bool haveKeyLayout() const {
return !keyLayoutFile.isEmpty();
}
inline bool haveKeyCharacterMap() const {
return !keyCharacterMapFile.isEmpty();
}
inline bool isComplete() const {
return haveKeyLayout() && haveKeyCharacterMap();
}
private:
bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
status_t loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier,
const String8& name);
String8 getPath(const InputDeviceIdentifier& deviceIdentifier,
const String8& name, InputDeviceConfigurationFileType type);
};
/**
* Returns true if the keyboard is eligible for use as a built-in keyboard.
*/
extern bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier,
const PropertyMap* deviceConfiguration, const KeyMap* keyMap);
/**
* Updates a meta state field when a key is pressed or released.
*/
extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState);
/**
* Normalizes the meta state such that if either the left or right modifier
* meta state bits are set then the result will also include the universal
* bit for that modifier.
*/
extern int32_t normalizeMetaState(int32_t oldMetaState);
/**
* Returns true if a key is a meta key like ALT or CAPS_LOCK.
*/
extern bool isMetaKey(int32_t keyCode);
} // namespace android
#endif // _LIBINPUT_KEYBOARD_H
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2012 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 _LIBINPUT_VELOCITY_CONTROL_H
#define _LIBINPUT_VELOCITY_CONTROL_H
#include <input/Input.h>
#include <input/VelocityTracker.h>
#include <utils/Timers.h>
namespace android {
/*
* Specifies parameters that govern pointer or wheel acceleration.
*/
struct VelocityControlParameters {
// A scale factor that is multiplied with the raw velocity deltas
// prior to applying any other velocity control factors. The scale
// factor should be used to adapt the input device resolution
// (eg. counts per inch) to the output device resolution (eg. pixels per inch).
//
// Must be a positive value.
// Default is 1.0 (no scaling).
float scale;
// The scaled speed at which acceleration begins to be applied.
// This value establishes the upper bound of a low speed regime for
// small precise motions that are performed without any acceleration.
//
// Must be a non-negative value.
// Default is 0.0 (no low threshold).
float lowThreshold;
// The scaled speed at which maximum acceleration is applied.
// The difference between highThreshold and lowThreshold controls
// the range of speeds over which the acceleration factor is interpolated.
// The wider the range, the smoother the acceleration.
//
// Must be a non-negative value greater than or equal to lowThreshold.
// Default is 0.0 (no high threshold).
float highThreshold;
// The acceleration factor.
// When the speed is above the low speed threshold, the velocity will scaled
// by an interpolated value between 1.0 and this amount.
//
// Must be a positive greater than or equal to 1.0.
// Default is 1.0 (no acceleration).
float acceleration;
VelocityControlParameters() :
scale(1.0f), lowThreshold(0.0f), highThreshold(0.0f), acceleration(1.0f) {
}
VelocityControlParameters(float scale, float lowThreshold,
float highThreshold, float acceleration) :
scale(scale), lowThreshold(lowThreshold),
highThreshold(highThreshold), acceleration(acceleration) {
}
};
/*
* Implements mouse pointer and wheel speed control and acceleration.
*/
class VelocityControl {
public:
VelocityControl();
/* Sets the various parameters. */
void setParameters(const VelocityControlParameters& parameters);
/* Resets the current movement counters to zero.
* This has the effect of nullifying any acceleration. */
void reset();
/* Translates a raw movement delta into an appropriately
* scaled / accelerated delta based on the current velocity. */
void move(nsecs_t eventTime, float* deltaX, float* deltaY);
private:
// If no movements are received within this amount of time,
// we assume the movement has stopped and reset the movement counters.
static const nsecs_t STOP_TIME = 500 * 1000000; // 500 ms
VelocityControlParameters mParameters;
nsecs_t mLastMovementTime;
VelocityTracker::Position mRawPosition;
VelocityTracker mVelocityTracker;
};
} // namespace android
#endif // _LIBINPUT_VELOCITY_CONTROL_H
@@ -0,0 +1,269 @@
/*
* Copyright (C) 2012 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 _LIBINPUT_VELOCITY_TRACKER_H
#define _LIBINPUT_VELOCITY_TRACKER_H
#include <input/Input.h>
#include <utils/Timers.h>
#include <utils/BitSet.h>
namespace android {
class VelocityTrackerStrategy;
/*
* Calculates the velocity of pointer movements over time.
*/
class VelocityTracker {
public:
struct Position {
float x, y;
};
struct Estimator {
static const size_t MAX_DEGREE = 4;
// Estimator time base.
nsecs_t time;
// Polynomial coefficients describing motion in X and Y.
float xCoeff[MAX_DEGREE + 1], yCoeff[MAX_DEGREE + 1];
// Polynomial degree (number of coefficients), or zero if no information is
// available.
uint32_t degree;
// Confidence (coefficient of determination), between 0 (no fit) and 1 (perfect fit).
float confidence;
inline void clear() {
time = 0;
degree = 0;
confidence = 0;
for (size_t i = 0; i <= MAX_DEGREE; i++) {
xCoeff[i] = 0;
yCoeff[i] = 0;
}
}
};
// Creates a velocity tracker using the specified strategy.
// If strategy is NULL, uses the default strategy for the platform.
VelocityTracker(const char* strategy = NULL);
~VelocityTracker();
// Resets the velocity tracker state.
void clear();
// Resets the velocity tracker state for specific pointers.
// Call this method when some pointers have changed and may be reusing
// an id that was assigned to a different pointer earlier.
void clearPointers(BitSet32 idBits);
// Adds movement information for a set of pointers.
// The idBits bitfield specifies the pointer ids of the pointers whose positions
// are included in the movement.
// The positions array contains position information for each pointer in order by
// increasing id. Its size should be equal to the number of one bits in idBits.
void addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions);
// Adds movement information for all pointers in a MotionEvent, including historical samples.
void addMovement(const MotionEvent* event);
// Gets the velocity of the specified pointer id in position units per second.
// Returns false and sets the velocity components to zero if there is
// insufficient movement information for the pointer.
bool getVelocity(uint32_t id, float* outVx, float* outVy) const;
// Gets an estimator for the recent movements of the specified pointer id.
// Returns false and clears the estimator if there is no information available
// about the pointer.
bool getEstimator(uint32_t id, Estimator* outEstimator) const;
// Gets the active pointer id, or -1 if none.
inline int32_t getActivePointerId() const { return mActivePointerId; }
// Gets a bitset containing all pointer ids from the most recent movement.
inline BitSet32 getCurrentPointerIdBits() const { return mCurrentPointerIdBits; }
private:
static const char* DEFAULT_STRATEGY;
nsecs_t mLastEventTime;
BitSet32 mCurrentPointerIdBits;
int32_t mActivePointerId;
VelocityTrackerStrategy* mStrategy;
bool configureStrategy(const char* strategy);
static VelocityTrackerStrategy* createStrategy(const char* strategy);
};
/*
* Implements a particular velocity tracker algorithm.
*/
class VelocityTrackerStrategy {
protected:
VelocityTrackerStrategy() { }
public:
virtual ~VelocityTrackerStrategy() { }
virtual void clear() = 0;
virtual void clearPointers(BitSet32 idBits) = 0;
virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
const VelocityTracker::Position* positions) = 0;
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0;
};
/*
* Velocity tracker algorithm based on least-squares linear regression.
*/
class LeastSquaresVelocityTrackerStrategy : public VelocityTrackerStrategy {
public:
enum Weighting {
// No weights applied. All data points are equally reliable.
WEIGHTING_NONE,
// Weight by time delta. Data points clustered together are weighted less.
WEIGHTING_DELTA,
// Weight such that points within a certain horizon are weighed more than those
// outside of that horizon.
WEIGHTING_CENTRAL,
// Weight such that points older than a certain amount are weighed less.
WEIGHTING_RECENT,
};
// Degree must be no greater than Estimator::MAX_DEGREE.
LeastSquaresVelocityTrackerStrategy(uint32_t degree, Weighting weighting = WEIGHTING_NONE);
virtual ~LeastSquaresVelocityTrackerStrategy();
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
const VelocityTracker::Position* positions);
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
// Sample horizon.
// We don't use too much history by default since we want to react to quick
// changes in direction.
static const nsecs_t HORIZON = 100 * 1000000; // 100 ms
// Number of samples to keep.
static const uint32_t HISTORY_SIZE = 20;
struct Movement {
nsecs_t eventTime;
BitSet32 idBits;
VelocityTracker::Position positions[MAX_POINTERS];
inline const VelocityTracker::Position& getPosition(uint32_t id) const {
return positions[idBits.getIndexOfBit(id)];
}
};
float chooseWeight(uint32_t index) const;
const uint32_t mDegree;
const Weighting mWeighting;
uint32_t mIndex;
Movement mMovements[HISTORY_SIZE];
};
/*
* Velocity tracker algorithm that uses an IIR filter.
*/
class IntegratingVelocityTrackerStrategy : public VelocityTrackerStrategy {
public:
// Degree must be 1 or 2.
IntegratingVelocityTrackerStrategy(uint32_t degree);
~IntegratingVelocityTrackerStrategy();
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
const VelocityTracker::Position* positions);
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
// Current state estimate for a particular pointer.
struct State {
nsecs_t updateTime;
uint32_t degree;
float xpos, xvel, xaccel;
float ypos, yvel, yaccel;
};
const uint32_t mDegree;
BitSet32 mPointerIdBits;
State mPointerState[MAX_POINTER_ID + 1];
void initState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
void updateState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const;
};
/*
* Velocity tracker strategy used prior to ICS.
*/
class LegacyVelocityTrackerStrategy : public VelocityTrackerStrategy {
public:
LegacyVelocityTrackerStrategy();
virtual ~LegacyVelocityTrackerStrategy();
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
const VelocityTracker::Position* positions);
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
// Oldest sample to consider when calculating the velocity.
static const nsecs_t HORIZON = 200 * 1000000; // 100 ms
// Number of samples to keep.
static const uint32_t HISTORY_SIZE = 20;
// The minimum duration between samples when estimating velocity.
static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms
struct Movement {
nsecs_t eventTime;
BitSet32 idBits;
VelocityTracker::Position positions[MAX_POINTERS];
inline const VelocityTracker::Position& getPosition(uint32_t id) const {
return positions[idBits.getIndexOfBit(id)];
}
};
uint32_t mIndex;
Movement mMovements[HISTORY_SIZE];
};
} // namespace android
#endif // _LIBINPUT_VELOCITY_TRACKER_H
@@ -0,0 +1,81 @@
/*
* 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 _LIBINPUT_VIRTUAL_KEY_MAP_H
#define _LIBINPUT_VIRTUAL_KEY_MAP_H
#include <stdint.h>
#include <input/Input.h>
#include <utils/Errors.h>
#include <utils/KeyedVector.h>
#include <utils/Tokenizer.h>
#include <utils/String8.h>
#include <utils/Unicode.h>
namespace android {
/* Describes a virtual key. */
struct VirtualKeyDefinition {
int32_t scanCode;
// configured position data, specified in display coords
int32_t centerX;
int32_t centerY;
int32_t width;
int32_t height;
};
/**
* Describes a collection of virtual keys on a touch screen in terms of
* virtual scan codes and hit rectangles.
*
* This object is immutable after it has been loaded.
*/
class VirtualKeyMap {
public:
~VirtualKeyMap();
static status_t load(const String8& filename, VirtualKeyMap** outMap);
inline const Vector<VirtualKeyDefinition>& getVirtualKeys() const {
return mVirtualKeys;
}
private:
class Parser {
VirtualKeyMap* mMap;
Tokenizer* mTokenizer;
public:
Parser(VirtualKeyMap* map, Tokenizer* tokenizer);
~Parser();
status_t parse();
private:
bool consumeFieldDelimiterAndSkipWhitespace();
bool parseNextIntField(int32_t* outValue);
};
Vector<VirtualKeyDefinition> mVirtualKeys;
VirtualKeyMap();
};
} // namespace android
#endif // _LIBINPUT_KEY_CHARACTER_MAP_H
@@ -0,0 +1,419 @@
/*
* Copyright (C) 2013 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 DRM_API_H_
#define DRM_API_H_
#include <utils/List.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
#include <utils/Mutex.h>
#include <media/stagefright/foundation/ABase.h>
// Loadable DrmEngine shared libraries should define the entry points
// createDrmFactory and createCryptoFactory as shown below:
//
// extern "C" {
// extern android::DrmFactory *createDrmFactory();
// extern android::CryptoFactory *createCryptoFactory();
// }
namespace android {
class DrmPlugin;
class DrmPluginListener;
// DRMs are implemented in DrmEngine plugins, which are dynamically
// loadable shared libraries that implement the entry points
// createDrmFactory and createCryptoFactory. createDrmFactory
// constructs and returns an instance of a DrmFactory object. Similarly,
// createCryptoFactory creates an instance of a CryptoFactory object.
// When a MediaCrypto or MediaDrm object needs to be constructed, all
// available DrmEngines present in the plugins directory on the device
// are scanned for a matching DrmEngine that can support the crypto
// scheme. When a match is found, the DrmEngine's createCryptoPlugin and
// createDrmPlugin methods are used to create CryptoPlugin or
// DrmPlugin instances to support that DRM scheme.
class DrmFactory {
public:
DrmFactory() {}
virtual ~DrmFactory() {}
// DrmFactory::isCryptoSchemeSupported can be called to determine
// if the plugin factory is able to construct plugins that support a
// given crypto scheme, which is specified by a UUID.
virtual bool isCryptoSchemeSupported(const uint8_t uuid[16]) = 0;
// DrmFactory::isContentTypeSupported can be called to determine
// if the plugin factory is able to construct plugins that support a
// given media container format specified by mimeType
virtual bool isContentTypeSupported(const String8 &mimeType) = 0;
// Construct a DrmPlugin for the crypto scheme specified by UUID.
virtual status_t createDrmPlugin(
const uint8_t uuid[16], DrmPlugin **plugin) = 0;
private:
DrmFactory(const DrmFactory &);
DrmFactory &operator=(const DrmFactory &);
};
class DrmPlugin {
public:
enum EventType {
kDrmPluginEventProvisionRequired = 1,
kDrmPluginEventKeyNeeded,
kDrmPluginEventKeyExpired,
kDrmPluginEventVendorDefined,
kDrmPluginEventSessionReclaimed,
kDrmPluginEventExpirationUpdate,
kDrmPluginEventKeysChange,
};
// Drm keys can be for offline content or for online streaming.
// Offline keys are persisted on the device and may be used when the device
// is disconnected from the network. The Release type is used to request
// that offline keys be no longer restricted to offline use.
enum KeyType {
kKeyType_Offline,
kKeyType_Streaming,
kKeyType_Release
};
// Enumerate KeyRequestTypes to allow an app to determine the
// type of a key request returned from getKeyRequest.
enum KeyRequestType {
kKeyRequestType_Unknown,
kKeyRequestType_Initial,
kKeyRequestType_Renewal,
kKeyRequestType_Release
};
// Enumerate KeyStatusTypes which indicate the state of a key
enum KeyStatusType
{
kKeyStatusType_Usable,
kKeyStatusType_Expired,
kKeyStatusType_OutputNotAllowed,
kKeyStatusType_StatusPending,
kKeyStatusType_InternalError
};
// Used by sendKeysChange to report the usability status of each
// key to the app.
struct KeyStatus
{
Vector<uint8_t> mKeyId;
KeyStatusType mType;
};
DrmPlugin() {}
virtual ~DrmPlugin() {}
// Open a new session with the DrmPlugin object. A session ID is returned
// in the sessionId parameter.
virtual status_t openSession(Vector<uint8_t> &sessionId) = 0;
// Close a session on the DrmPlugin object.
virtual status_t closeSession(Vector<uint8_t> const &sessionId) = 0;
// A key request/response exchange occurs between the app and a License
// Server to obtain the keys required to decrypt the content. getKeyRequest()
// is used to obtain an opaque key request blob that is delivered to the
// license server.
//
// The scope parameter may be a sessionId or a keySetId, depending on the
// specified keyType. When the keyType is kKeyType_Offline or
// kKeyType_Streaming, scope should be set to the sessionId the keys will be
// provided to. When the keyType is kKeyType_Release, scope should be set to
// the keySetId of the keys being released. Releasing keys from a device
// invalidates them for all sessions.
//
// The init data passed to getKeyRequest is container-specific and its
// meaning is interpreted based on the mime type provided in the mimeType
// parameter to getKeyRequest. It could contain, for example, the content
// ID, key ID or other data obtained from the content metadata that is required
// in generating the key request. Init may be null when keyType is
// kKeyType_Release.
//
// mimeType identifies the mime type of the content
//
// keyType specifies if the keys are to be used for streaming or offline content
//
// optionalParameters are included in the key request message to allow a
// client application to provide additional message parameters to the server.
//
// If successful, the opaque key request blob is returned to the caller.
virtual status_t
getKeyRequest(Vector<uint8_t> const &scope,
Vector<uint8_t> const &initData,
String8 const &mimeType, KeyType keyType,
KeyedVector<String8, String8> const &optionalParameters,
Vector<uint8_t> &request, String8 &defaultUrl,
KeyRequestType *keyRequestType) = 0;
//
// After a key response is received by the app, it is provided to the
// Drm plugin using provideKeyResponse.
//
// scope may be a sessionId or a keySetId depending on the type of the
// response. Scope should be set to the sessionId when the response is
// for either streaming or offline key requests. Scope should be set to the
// keySetId when the response is for a release request.
//
// When the response is for an offline key request, a keySetId is returned
// in the keySetId vector parameter that can be used to later restore the
// keys to a new session with the method restoreKeys. When the response is
// for a streaming or release request, no keySetId is returned.
//
virtual status_t provideKeyResponse(Vector<uint8_t> const &scope,
Vector<uint8_t> const &response,
Vector<uint8_t> &keySetId) = 0;
// Remove the current keys from a session
virtual status_t removeKeys(Vector<uint8_t> const &sessionId) = 0;
// Restore persisted offline keys into a new session. keySetId identifies
// the keys to load, obtained from a prior call to provideKeyResponse().
virtual status_t restoreKeys(Vector<uint8_t> const &sessionId,
Vector<uint8_t> const &keySetId) = 0;
// Request an informative description of the license for the session. The status
// is in the form of {name, value} pairs. Since DRM license policies vary by
// vendor, the specific status field names are determined by each DRM vendor.
// Refer to your DRM provider documentation for definitions of the field names
// for a particular DrmEngine.
virtual status_t
queryKeyStatus(Vector<uint8_t> const &sessionId,
KeyedVector<String8, String8> &infoMap) const = 0;
// A provision request/response exchange occurs between the app and a
// provisioning server to retrieve a device certificate. getProvisionRequest
// is used to obtain an opaque key request blob that is delivered to the
// provisioning server.
//
// If successful, the opaque provision request blob is returned to the caller.
virtual status_t getProvisionRequest(String8 const &cert_type,
String8 const &cert_authority,
Vector<uint8_t> &request,
String8 &defaultUrl) = 0;
// After a provision response is received by the app, it is provided to the
// Drm plugin using provideProvisionResponse.
virtual status_t provideProvisionResponse(Vector<uint8_t> const &response,
Vector<uint8_t> &certificate,
Vector<uint8_t> &wrapped_key) = 0;
// Remove device provisioning.
virtual status_t unprovisionDevice() = 0;
// A means of enforcing the contractual requirement for a concurrent stream
// limit per subscriber across devices is provided via SecureStop. SecureStop
// is a means of securely monitoring the lifetime of sessions. Since playback
// on a device can be interrupted due to reboot, power failure, etc. a means
// of persisting the lifetime information on the device is needed.
//
// A signed version of the sessionID is written to persistent storage on the
// device when each MediaCrypto object is created. The sessionID is signed by
// the device private key to prevent tampering.
//
// In the normal case, playback will be completed, the session destroyed and
// the Secure Stops will be queried. The App queries secure stops and forwards
// the secure stop message to the server which verifies the signature and
// notifies the server side database that the session destruction has been
// confirmed. The persisted record on the client is only removed after positive
// confirmation that the server received the message using releaseSecureStops().
virtual status_t getSecureStops(List<Vector<uint8_t> > &secureStops) = 0;
virtual status_t getSecureStop(Vector<uint8_t> const &ssid, Vector<uint8_t> &secureStop) = 0;
virtual status_t releaseSecureStops(Vector<uint8_t> const &ssRelease) = 0;
virtual status_t releaseAllSecureStops() = 0;
// Read a property value given the device property string. There are a few forms
// of property access methods, depending on the data type returned.
// Since DRM plugin properties may vary, additional field names may be defined
// by each DRM vendor. Refer to your DRM provider documentation for definitions
// of its additional field names.
//
// Standard values are:
// "vendor" [string] identifies the maker of the plugin
// "version" [string] identifies the version of the plugin
// "description" [string] describes the plugin
// 'deviceUniqueId' [byte array] The device unique identifier is established
// during device provisioning and provides a means of uniquely identifying
// each device.
virtual status_t getPropertyString(String8 const &name, String8 &value ) const = 0;
virtual status_t getPropertyByteArray(String8 const &name,
Vector<uint8_t> &value ) const = 0;
// Write a property value given the device property string. There are a few forms
// of property setting methods, depending on the data type.
// Since DRM plugin properties may vary, additional field names may be defined
// by each DRM vendor. Refer to your DRM provider documentation for definitions
// of its field names.
virtual status_t setPropertyString(String8 const &name,
String8 const &value ) = 0;
virtual status_t setPropertyByteArray(String8 const &name,
Vector<uint8_t> const &value ) = 0;
// The following methods implement operations on a CryptoSession to support
// encrypt, decrypt, sign verify operations on operator-provided
// session keys.
//
// The algorithm string conforms to JCA Standard Names for Cipher
// Transforms and is case insensitive. For example "AES/CBC/PKCS5Padding".
//
// Return OK if the algorithm is supported, otherwise return BAD_VALUE
//
virtual status_t setCipherAlgorithm(Vector<uint8_t> const &sessionId,
String8 const &algorithm) = 0;
//
// The algorithm string conforms to JCA Standard Names for Mac
// Algorithms and is case insensitive. For example "HmacSHA256".
//
// Return OK if the algorithm is supported, otherwise return BAD_VALUE
//
virtual status_t setMacAlgorithm(Vector<uint8_t> const &sessionId,
String8 const &algorithm) = 0;
// Encrypt the provided input buffer with the cipher algorithm
// specified by setCipherAlgorithm and the key selected by keyId,
// and return the encrypted data.
virtual status_t encrypt(Vector<uint8_t> const &sessionId,
Vector<uint8_t> const &keyId,
Vector<uint8_t> const &input,
Vector<uint8_t> const &iv,
Vector<uint8_t> &output) = 0;
// Decrypt the provided input buffer with the cipher algorithm
// specified by setCipherAlgorithm and the key selected by keyId,
// and return the decrypted data.
virtual status_t decrypt(Vector<uint8_t> const &sessionId,
Vector<uint8_t> const &keyId,
Vector<uint8_t> const &input,
Vector<uint8_t> const &iv,
Vector<uint8_t> &output) = 0;
// Compute a signature on the provided message using the mac algorithm
// specified by setMacAlgorithm and the key selected by keyId,
// and return the signature.
virtual status_t sign(Vector<uint8_t> const &sessionId,
Vector<uint8_t> const &keyId,
Vector<uint8_t> const &message,
Vector<uint8_t> &signature) = 0;
// Compute a signature on the provided message using the mac algorithm
// specified by setMacAlgorithm and the key selected by keyId,
// and compare with the expected result. Set result to true or
// false depending on the outcome.
virtual status_t verify(Vector<uint8_t> const &sessionId,
Vector<uint8_t> const &keyId,
Vector<uint8_t> const &message,
Vector<uint8_t> const &signature,
bool &match) = 0;
// Compute an RSA signature on the provided message using the algorithm
// specified by algorithm.
virtual status_t signRSA(Vector<uint8_t> const &sessionId,
String8 const &algorithm,
Vector<uint8_t> const &message,
Vector<uint8_t> const &wrapped_key,
Vector<uint8_t> &signature) = 0;
status_t setListener(const sp<DrmPluginListener>& listener) {
Mutex::Autolock lock(mEventLock);
mListener = listener;
return OK;
}
protected:
// Plugins call these methods to deliver events to the java app
void sendEvent(EventType eventType, int extra,
Vector<uint8_t> const *sessionId,
Vector<uint8_t> const *data);
void sendExpirationUpdate(Vector<uint8_t> const *sessionId,
int64_t expiryTimeInMS);
void sendKeysChange(Vector<uint8_t> const *sessionId,
Vector<DrmPlugin::KeyStatus> const *keyStatusList,
bool hasNewUsableKey);
private:
Mutex mEventLock;
sp<DrmPluginListener> mListener;
DISALLOW_EVIL_CONSTRUCTORS(DrmPlugin);
};
class DrmPluginListener: virtual public RefBase
{
public:
virtual void sendEvent(DrmPlugin::EventType eventType, int extra,
Vector<uint8_t> const *sessionId,
Vector<uint8_t> const *data) = 0;
virtual void sendExpirationUpdate(Vector<uint8_t> const *sessionId,
int64_t expiryTimeInMS) = 0;
virtual void sendKeysChange(Vector<uint8_t> const *sessionId,
Vector<DrmPlugin::KeyStatus> const *keyStatusList,
bool hasNewUsableKey) = 0;
};
inline void DrmPlugin::sendEvent(EventType eventType, int extra,
Vector<uint8_t> const *sessionId,
Vector<uint8_t> const *data) {
mEventLock.lock();
sp<DrmPluginListener> listener = mListener;
mEventLock.unlock();
if (listener != NULL) {
listener->sendEvent(eventType, extra, sessionId, data);
}
}
inline void DrmPlugin::sendExpirationUpdate(Vector<uint8_t> const *sessionId,
int64_t expiryTimeInMS) {
mEventLock.lock();
sp<DrmPluginListener> listener = mListener;
mEventLock.unlock();
if (listener != NULL) {
listener->sendExpirationUpdate(sessionId, expiryTimeInMS);
}
}
inline void DrmPlugin::sendKeysChange(Vector<uint8_t> const *sessionId,
Vector<DrmPlugin::KeyStatus> const *keyStatusList,
bool hasNewUsableKey) {
mEventLock.lock();
sp<DrmPluginListener> listener = mListener;
mEventLock.unlock();
if (listener != NULL) {
listener->sendKeysChange(sessionId, keyStatusList, hasNewUsableKey);
}
}
} // namespace android
#endif // DRM_API_H_
@@ -0,0 +1,126 @@
/*
* Copyright (C) 2011 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 II420_COLOR_CONVERTER_H
#define II420_COLOR_CONVERTER_H
#include <stdint.h>
#include <android/rect.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct II420ColorConverter {
/*
* getDecoderOutputFormat
* Returns the color format (OMX_COLOR_FORMATTYPE) of the decoder output.
* If it is I420 (OMX_COLOR_FormatYUV420Planar), no conversion is needed,
* and convertDecoderOutputToI420() can be a no-op.
*/
int (*getDecoderOutputFormat)();
/*
* convertDecoderOutputToI420
* @Desc Converts from the decoder output format to I420 format.
* @note Caller (e.g. VideoEditor) owns the buffers
* @param decoderBits (IN) Pointer to the buffer contains decoder output
* @param decoderWidth (IN) Buffer width, as reported by the decoder
* metadata (kKeyWidth)
* @param decoderHeight (IN) Buffer height, as reported by the decoder
* metadata (kKeyHeight)
* @param decoderRect (IN) The rectangle of the actual frame, as
* reported by decoder metadata (kKeyCropRect)
* @param dstBits (OUT) Pointer to the output I420 buffer
* @return -1 Any error
* @return 0 No Error
*/
int (*convertDecoderOutputToI420)(
void* decoderBits, int decoderWidth, int decoderHeight,
ARect decoderRect, void* dstBits);
/*
* getEncoderIntputFormat
* Returns the color format (OMX_COLOR_FORMATTYPE) of the encoder input.
* If it is I420 (OMX_COLOR_FormatYUV420Planar), no conversion is needed,
* and convertI420ToEncoderInput() and getEncoderInputBufferInfo() can
* be no-ops.
*/
int (*getEncoderInputFormat)();
/* convertI420ToEncoderInput
* @Desc This function converts from I420 to the encoder input format
* @note Caller (e.g. VideoEditor) owns the buffers
* @param srcBits (IN) Pointer to the input I420 buffer
* @param srcWidth (IN) Width of the I420 frame
* @param srcHeight (IN) Height of the I420 frame
* @param encoderWidth (IN) Encoder buffer width, as calculated by
* getEncoderBufferInfo()
* @param encoderHeight (IN) Encoder buffer height, as calculated by
* getEncoderBufferInfo()
* @param encoderRect (IN) Rect coordinates of the actual frame inside
* the encoder buffer, as calculated by
* getEncoderBufferInfo().
* @param encoderBits (OUT) Pointer to the output buffer. The size of
* this buffer is calculated by
* getEncoderBufferInfo()
* @return -1 Any error
* @return 0 No Error
*/
int (*convertI420ToEncoderInput)(
void* srcBits, int srcWidth, int srcHeight,
int encoderWidth, int encoderHeight, ARect encoderRect,
void* encoderBits);
/* getEncoderInputBufferInfo
* @Desc This function returns metadata for the encoder input buffer
* based on the actual I420 frame width and height.
* @note This API should be be used to obtain the necessary information
* before calling convertI420ToEncoderInput().
* VideoEditor knows only the width and height of the I420 buffer,
* but it also needs know the width, height, and size of the
* encoder input buffer. The encoder input buffer width and height
* are used to set the metadata for the encoder.
* @param srcWidth (IN) Width of the I420 frame
* @param srcHeight (IN) Height of the I420 frame
* @param encoderWidth (OUT) Encoder buffer width needed
* @param encoderHeight (OUT) Encoder buffer height needed
* @param encoderRect (OUT) Rect coordinates of the actual frame inside
* the encoder buffer
* @param encoderBufferSize (OUT) The size of the buffer that need to be
* allocated by the caller before invoking
* convertI420ToEncoderInput().
* @return -1 Any error
* @return 0 No Error
*/
int (*getEncoderInputBufferInfo)(
int srcWidth, int srcHeight,
int* encoderWidth, int* encoderHeight,
ARect* encoderRect, int* encoderBufferSize);
} II420ColorConverter;
/* The only function that the shared library needs to expose: It fills the
function pointers in II420ColorConverter */
void getI420ColorConverter(II420ColorConverter *converter);
#if defined(__cplusplus)
}
#endif
#endif // II420_COLOR_CONVERTER_H
@@ -0,0 +1,115 @@
/*
* Copyright (C) 2012 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.
*/
#include <media/stagefright/MediaErrors.h>
#include <utils/Errors.h>
#include <utils/Vector.h>
#ifndef CRYPTO_API_H_
#define CRYPTO_API_H_
namespace android {
struct AString;
struct CryptoPlugin;
struct CryptoFactory {
CryptoFactory() {}
virtual ~CryptoFactory() {}
virtual bool isCryptoSchemeSupported(const uint8_t uuid[16]) const = 0;
virtual status_t createPlugin(
const uint8_t uuid[16], const void *data, size_t size,
CryptoPlugin **plugin) = 0;
private:
CryptoFactory(const CryptoFactory &);
CryptoFactory &operator=(const CryptoFactory &);
};
struct CryptoPlugin {
enum Mode {
kMode_Unencrypted = 0,
kMode_AES_CTR = 1,
// Neither key nor iv are being used in this mode.
// Each subsample is encrypted w/ an iv of all zeroes.
kMode_AES_WV = 2, // FIX constant
};
struct SubSample {
uint32_t mNumBytesOfClearData;
uint32_t mNumBytesOfEncryptedData;
};
CryptoPlugin() {}
virtual ~CryptoPlugin() {}
// If this method returns false, a non-secure decoder will be used to
// decode the data after decryption. The decrypt API below will have
// to support insecure decryption of the data (secure = false) for
// media data of the given mime type.
virtual bool requiresSecureDecoderComponent(const char *mime) const = 0;
// To implement resolution constraints, the crypto plugin needs to know
// the resolution of the video being decrypted. The media player should
// call this method when the resolution is determined and any time it
// is subsequently changed.
virtual void notifyResolution(uint32_t /* width */, uint32_t /* height */) {}
// A MediaDrm session may be associated with a MediaCrypto session. The
// associated MediaDrm session is used to load decryption keys
// into the crypto/drm plugin. The keys are then referenced by key-id
// in the 'key' parameter to the decrypt() method.
// Should return NO_ERROR on success, ERROR_DRM_SESSION_NOT_OPENED if
// the session is not opened and a code from MediaErrors.h otherwise.
virtual status_t setMediaDrmSession(const Vector<uint8_t> & /*sessionId */) {
return ERROR_UNSUPPORTED;
}
// If the error returned falls into the range
// ERROR_DRM_VENDOR_MIN..ERROR_DRM_VENDOR_MAX, errorDetailMsg should be
// filled in with an appropriate string.
// At the java level these special errors will then trigger a
// MediaCodec.CryptoException that gives clients access to both
// the error code and the errorDetailMsg.
// Returns a non-negative result to indicate the number of bytes written
// to the dstPtr, or a negative result to indicate an error.
virtual ssize_t decrypt(
bool secure,
const uint8_t key[16],
const uint8_t iv[16],
Mode mode,
const void *srcPtr,
const SubSample *subSamples, size_t numSubSamples,
void *dstPtr,
AString *errorDetailMsg) = 0;
private:
CryptoPlugin(const CryptoPlugin &);
CryptoPlugin &operator=(const CryptoPlugin &);
};
} // namespace android
extern "C" {
extern android::CryptoFactory *createCryptoFactory();
}
#endif // CRYPTO_API_H_
@@ -0,0 +1,164 @@
/*
* Copyright (C) 2012 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 HDCP_API_H_
#define HDCP_API_H_
#include <utils/Errors.h>
#include <system/window.h>
namespace android {
// Two different kinds of modules are covered under the same HDCPModule
// structure below, a module either implements decryption or encryption.
struct HDCPModule {
typedef void (*ObserverFunc)(void *cookie, int msg, int ext1, int ext2);
// The msg argument in calls to the observer notification function.
enum {
// Sent in response to a call to "HDCPModule::initAsync" once
// initialization has either been successfully completed,
// i.e. the HDCP session is now fully setup (AKE, Locality Check,
// SKE and any authentication with repeaters completed) or failed.
// ext1 should be a suitable error code (status_t), ext2 is
// unused for ENCRYPTION and in the case of HDCP_INITIALIZATION_COMPLETE
// holds the local TCP port the module is listening on.
HDCP_INITIALIZATION_COMPLETE,
HDCP_INITIALIZATION_FAILED,
// Sent upon completion of a call to "HDCPModule::shutdownAsync".
// ext1 should be a suitable error code, ext2 is unused.
HDCP_SHUTDOWN_COMPLETE,
HDCP_SHUTDOWN_FAILED,
HDCP_UNAUTHENTICATED_CONNECTION,
HDCP_UNAUTHORIZED_CONNECTION,
HDCP_REVOKED_CONNECTION,
HDCP_TOPOLOGY_EXECEEDED,
HDCP_UNKNOWN_ERROR,
// DECRYPTION only: Indicates that a client has successfully connected,
// a secure session established and the module is ready to accept
// future calls to "decrypt".
HDCP_SESSION_ESTABLISHED,
};
// HDCPModule capability bit masks
enum {
// HDCP_CAPS_ENCRYPT: mandatory, meaning the HDCP module can encrypt
// from an input byte-array buffer to an output byte-array buffer
HDCP_CAPS_ENCRYPT = (1 << 0),
// HDCP_CAPS_ENCRYPT_NATIVE: the HDCP module supports encryption from
// a native buffer to an output byte-array buffer. The format of the
// input native buffer is specific to vendor's encoder implementation.
// It is the same format as that used by the encoder when
// "storeMetaDataInBuffers" extension is enabled on its output port.
HDCP_CAPS_ENCRYPT_NATIVE = (1 << 1),
};
// Module can call the notification function to signal completion/failure
// of asynchronous operations (such as initialization) or out of band
// events.
HDCPModule(void *cookie, ObserverFunc observerNotify) {};
virtual ~HDCPModule() {};
// ENCRYPTION: Request to setup an HDCP session with the host specified
// by addr and listening on the specified port.
// DECRYPTION: Request to setup an HDCP session, addr is the interface
// address the module should bind its socket to. port will be 0.
// The module will pick the port to listen on itself and report its choice
// in the "ext2" argument of the HDCP_INITIALIZATION_COMPLETE callback.
virtual status_t initAsync(const char *addr, unsigned port) = 0;
// Request to shutdown the active HDCP session.
virtual status_t shutdownAsync() = 0;
// Returns the capability bitmask of this HDCP session.
virtual uint32_t getCaps() {
return HDCP_CAPS_ENCRYPT;
}
// ENCRYPTION only:
// Encrypt data according to the HDCP spec. "size" bytes of data are
// available at "inData" (virtual address), "size" may not be a multiple
// of 128 bits (16 bytes). An equal number of encrypted bytes should be
// written to the buffer at "outData" (virtual address).
// This operation is to be synchronous, i.e. this call does not return
// until outData contains size bytes of encrypted data.
// streamCTR will be assigned by the caller (to 0 for the first PES stream,
// 1 for the second and so on)
// inputCTR _will_be_maintained_by_the_callee_ for each PES stream.
virtual status_t encrypt(
const void *inData, size_t size, uint32_t streamCTR,
uint64_t *outInputCTR, void *outData) {
return INVALID_OPERATION;
}
// Encrypt data according to the HDCP spec. "size" bytes of data starting
// at location "offset" are available in "buffer" (buffer handle). "size"
// may not be a multiple of 128 bits (16 bytes). An equal number of
// encrypted bytes should be written to the buffer at "outData" (virtual
// address). This operation is to be synchronous, i.e. this call does not
// return until outData contains size bytes of encrypted data.
// streamCTR will be assigned by the caller (to 0 for the first PES stream,
// 1 for the second and so on)
// inputCTR _will_be_maintained_by_the_callee_ for each PES stream.
virtual status_t encryptNative(
buffer_handle_t buffer, size_t offset, size_t size,
uint32_t streamCTR, uint64_t *outInputCTR, void *outData) {
return INVALID_OPERATION;
}
// DECRYPTION only:
// Decrypt data according to the HDCP spec.
// "size" bytes of encrypted data are available at "inData"
// (virtual address), "size" may not be a multiple of 128 bits (16 bytes).
// An equal number of decrypted bytes should be written to the buffer
// at "outData" (virtual address).
// This operation is to be synchronous, i.e. this call does not return
// until outData contains size bytes of decrypted data.
// Both streamCTR and inputCTR will be provided by the caller.
virtual status_t decrypt(
const void *inData, size_t size,
uint32_t streamCTR, uint64_t inputCTR,
void *outData) {
return INVALID_OPERATION;
}
private:
HDCPModule(const HDCPModule &);
HDCPModule &operator=(const HDCPModule &);
};
} // namespace android
// A shared library exporting the following methods should be included to
// support HDCP functionality. The shared library must be called
// "libstagefright_hdcp.so", it will be dynamically loaded into the
// mediaserver process.
extern "C" {
// Create a module for ENCRYPTION.
extern android::HDCPModule *createHDCPModule(
void *cookie, android::HDCPModule::ObserverFunc);
// Create a module for DECRYPTION.
extern android::HDCPModule *createHDCPModuleForDecryption(
void *cookie, android::HDCPModule::ObserverFunc);
}
#endif // HDCP_API_H_
@@ -0,0 +1,288 @@
/*
* 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/hardware/OMXPluginBase.h>
#include <media/hardware/MetadataBufferType.h>
#include <system/window.h>
#include <utils/RefBase.h>
#include <OMX_Component.h>
namespace android {
// A pointer to this struct is passed to the OMX_SetParameter when the extension
// index for the 'OMX.google.android.index.enableAndroidNativeBuffers' extension
// is given.
//
// When Android native buffer use is disabled for a port (the default state),
// the OMX node should operate as normal, and expect UseBuffer calls to set its
// buffers. This is the mode that will be used when CPU access to the buffer is
// required.
//
// When Android native buffer use has been enabled for a given port, the video
// color format for the port is to be interpreted as an Android pixel format
// rather than an OMX color format. Enabling Android native buffers may also
// change how the component receives the native buffers. If store-metadata-mode
// is enabled on the port, the component will receive the buffers as specified
// in the section below. Otherwise, unless the node supports the
// 'OMX.google.android.index.useAndroidNativeBuffer2' extension, it should
// expect to receive UseAndroidNativeBuffer calls (via OMX_SetParameter) rather
// than UseBuffer calls for that port.
struct EnableAndroidNativeBuffersParams {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_U32 nPortIndex;
OMX_BOOL enable;
};
// A pointer to this struct is passed to OMX_SetParameter() when the extension index
// "OMX.google.android.index.storeMetaDataInBuffers" or
// "OMX.google.android.index.storeANWBufferInMetadata" is given.
//
// When meta data is stored in the video buffers passed between OMX clients
// and OMX components, interpretation of the buffer data is up to the
// buffer receiver, and the data may or may not be the actual video data, but
// some information helpful for the receiver to locate the actual data.
// The buffer receiver thus needs to know how to interpret what is stored
// in these buffers, with mechanisms pre-determined externally. How to
// interpret the meta data is outside of the scope of this parameter.
//
// Currently, this is used to pass meta data from video source (camera component, for instance) to
// video encoder to avoid memcpying of input video frame data, as well as to pass dynamic output
// buffer to video decoder. To do this, bStoreMetaData is set to OMX_TRUE.
//
// If bStoreMetaData is set to false, real YUV frame data will be stored in input buffers, and
// the output buffers contain either real YUV frame data, or are themselves native handles as
// directed by enable/use-android-native-buffer parameter settings.
// In addition, if no OMX_SetParameter() call is made on a port with the corresponding extension
// index, the component should not assume that the client is not using metadata mode for the port.
//
// If the component supports this using the "OMX.google.android.index.storeANWBufferInMetadata"
// extension and bStoreMetaData is set to OMX_TRUE, data is passed using the VideoNativeMetadata
// layout as defined below. Each buffer will be accompanied by a fence. The fence must signal
// before the buffer can be used (e.g. read from or written into). When returning such buffer to
// the client, component must provide a new fence that must signal before the returned buffer can
// be used (e.g. read from or written into). The component owns the incoming fenceFd, and must close
// it when fence has signaled. The client will own and close the returned fence file descriptor.
//
// If the component supports this using the "OMX.google.android.index.storeMetaDataInBuffers"
// extension and bStoreMetaData is set to OMX_TRUE, data is passed using VideoGrallocMetadata
// (the layout of which is the VideoGrallocMetadata defined below). Camera input can be also passed
// as "CameraSource", the layout of which is vendor dependent.
//
// Metadata buffers are registered with the component using UseBuffer calls, or can be allocated
// by the component for encoder-metadata-output buffers.
struct StoreMetaDataInBuffersParams {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_U32 nPortIndex;
OMX_BOOL bStoreMetaData;
};
// Meta data buffer layout used to transport output frames to the decoder for
// dynamic buffer handling.
struct VideoGrallocMetadata {
MetadataBufferType eType; // must be kMetadataBufferTypeGrallocSource
#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS
OMX_PTR pHandle;
#else
buffer_handle_t pHandle;
#endif
};
// Legacy name for VideoGrallocMetadata struct.
struct VideoDecoderOutputMetaData : public VideoGrallocMetadata {};
struct VideoNativeMetadata {
MetadataBufferType eType; // must be kMetadataBufferTypeANWBuffer
#ifdef OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS
OMX_PTR pBuffer;
#else
struct ANativeWindowBuffer* pBuffer;
#endif
int nFenceFd; // -1 if unused
};
// A pointer to this struct is passed to OMX_SetParameter() when the extension
// index "OMX.google.android.index.prepareForAdaptivePlayback" is given.
//
// This method is used to signal a video decoder, that the user has requested
// seamless resolution change support (if bEnable is set to OMX_TRUE).
// nMaxFrameWidth and nMaxFrameHeight are the dimensions of the largest
// anticipated frames in the video. If bEnable is OMX_FALSE, no resolution
// change is expected, and the nMaxFrameWidth/Height fields are unused.
//
// If the decoder supports dynamic output buffers, it may ignore this
// request. Otherwise, it shall request resources in such a way so that it
// avoids full port-reconfiguration (due to output port-definition change)
// during resolution changes.
//
// DO NOT USE THIS STRUCTURE AS IT WILL BE REMOVED. INSTEAD, IMPLEMENT
// METADATA SUPPORT FOR VIDEO DECODERS.
struct PrepareForAdaptivePlaybackParams {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_U32 nPortIndex;
OMX_BOOL bEnable;
OMX_U32 nMaxFrameWidth;
OMX_U32 nMaxFrameHeight;
};
// A pointer to this struct is passed to OMX_SetParameter when the extension
// index for the 'OMX.google.android.index.useAndroidNativeBuffer' extension is
// given. This call will only be performed if a prior call was made with the
// 'OMX.google.android.index.enableAndroidNativeBuffers' extension index,
// enabling use of Android native buffers.
struct UseAndroidNativeBufferParams {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_U32 nPortIndex;
OMX_PTR pAppPrivate;
OMX_BUFFERHEADERTYPE **bufferHeader;
const sp<ANativeWindowBuffer>& nativeBuffer;
};
// A pointer to this struct is passed to OMX_GetParameter when the extension
// index for the 'OMX.google.android.index.getAndroidNativeBufferUsage'
// extension is given. The usage bits returned from this query will be used to
// allocate the Gralloc buffers that get passed to the useAndroidNativeBuffer
// command.
struct GetAndroidNativeBufferUsageParams {
OMX_U32 nSize; // IN
OMX_VERSIONTYPE nVersion; // IN
OMX_U32 nPortIndex; // IN
OMX_U32 nUsage; // OUT
};
// An enum OMX_COLOR_FormatAndroidOpaque to indicate an opaque colorformat
// is declared in media/stagefright/openmax/OMX_IVCommon.h
// This will inform the encoder that the actual
// colorformat will be relayed by the GRalloc Buffers.
// OMX_COLOR_FormatAndroidOpaque = 0x7F000001,
// A pointer to this struct is passed to OMX_SetParameter when the extension
// index for the 'OMX.google.android.index.prependSPSPPSToIDRFrames' extension
// is given.
// A successful result indicates that future IDR frames will be prefixed by
// SPS/PPS.
struct PrependSPSPPSToIDRFramesParams {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_BOOL bEnable;
};
// Structure describing a media image (frame)
// Currently only supporting YUV
struct MediaImage {
enum Type {
MEDIA_IMAGE_TYPE_UNKNOWN = 0,
MEDIA_IMAGE_TYPE_YUV,
};
enum PlaneIndex {
Y = 0,
U,
V,
MAX_NUM_PLANES
};
Type mType;
uint32_t mNumPlanes; // number of planes
uint32_t mWidth; // width of largest plane (unpadded, as in nFrameWidth)
uint32_t mHeight; // height of largest plane (unpadded, as in nFrameHeight)
uint32_t mBitDepth; // useable bit depth
struct PlaneInfo {
uint32_t mOffset; // offset of first pixel of the plane in bytes
// from buffer offset
uint32_t mColInc; // column increment in bytes
uint32_t mRowInc; // row increment in bytes
uint32_t mHorizSubsampling; // subsampling compared to the largest plane
uint32_t mVertSubsampling; // subsampling compared to the largest plane
};
PlaneInfo mPlane[MAX_NUM_PLANES];
};
// A pointer to this struct is passed to OMX_GetParameter when the extension
// index for the 'OMX.google.android.index.describeColorFormat'
// extension is given. This method can be called from any component state
// other than invalid. The color-format, frame width/height, and stride/
// slice-height parameters are ones that are associated with a raw video
// port (input or output), but the stride/slice height parameters may be
// incorrect. bUsingNativeBuffers is OMX_TRUE if native android buffers will
// be used (while specifying this color format).
//
// The component shall fill out the MediaImage structure that
// corresponds to the described raw video format, and the potentially corrected
// stride and slice-height info.
//
// The behavior is slightly different if bUsingNativeBuffers is OMX_TRUE,
// though most implementations can ignore this difference. When using native buffers,
// the component may change the configured color format to an optimized format.
// Additionally, when allocating these buffers for flexible usecase, the framework
// will set the SW_READ/WRITE_OFTEN usage flags. In this case (if bUsingNativeBuffers
// is OMX_TRUE), the component shall fill out the MediaImage information for the
// scenario when these SW-readable/writable buffers are locked using gralloc_lock.
// Note, that these buffers may also be locked using gralloc_lock_ycbcr, which must
// be supported for vendor-specific formats.
//
// For non-YUV packed planar/semiplanar image formats, or if bUsingNativeBuffers
// is OMX_TRUE and the component does not support this color format with native
// buffers, the component shall set mNumPlanes to 0, and mType to MEDIA_IMAGE_TYPE_UNKNOWN.
struct DescribeColorFormatParams {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
// input: parameters from OMX_VIDEO_PORTDEFINITIONTYPE
OMX_COLOR_FORMATTYPE eColorFormat;
OMX_U32 nFrameWidth;
OMX_U32 nFrameHeight;
OMX_U32 nStride;
OMX_U32 nSliceHeight;
OMX_BOOL bUsingNativeBuffers;
// output: fill out the MediaImage fields
MediaImage sMediaImage;
};
// A pointer to this struct is passed to OMX_SetParameter or OMX_GetParameter
// when the extension index for the
// 'OMX.google.android.index.configureVideoTunnelMode' extension is given.
// If the extension is supported then tunneled playback mode should be supported
// by the codec. If bTunneled is set to OMX_TRUE then the video decoder should
// operate in "tunneled" mode and output its decoded frames directly to the
// sink. In this case nAudioHwSync is the HW SYNC ID of the audio HAL Output
// stream to sync the video with. If bTunneled is set to OMX_FALSE, "tunneled"
// mode should be disabled and nAudioHwSync should be ignored.
// OMX_GetParameter is used to query tunneling configuration. bTunneled should
// return whether decoder is operating in tunneled mode, and if it is,
// pSidebandWindow should contain the codec allocated sideband window handle.
struct ConfigureVideoTunnelModeParams {
OMX_U32 nSize; // IN
OMX_VERSIONTYPE nVersion; // IN
OMX_U32 nPortIndex; // IN
OMX_BOOL bTunneled; // IN/OUT
OMX_U32 nAudioHwSync; // IN
OMX_PTR pSidebandWindow; // OUT
};
} // namespace android
extern android::OMXPluginBase *createOMXPlugin();
#endif // HARDWARE_API_H_
@@ -0,0 +1,127 @@
/*
* Copyright (C) 2011 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 METADATA_BUFFER_TYPE_H
#define METADATA_BUFFER_TYPE_H
#ifdef __cplusplus
extern "C" {
namespace android {
#endif
/*
* MetadataBufferType defines the type of the metadata buffers that
* can be passed to video encoder component for encoding, via Stagefright
* media recording framework. To see how to work with the metadata buffers
* in media recording framework, please consult HardwareAPI.h
*
* The creator of metadata buffers and video encoder share common knowledge
* on what is actually being stored in these metadata buffers, and
* how the information can be used by the video encoder component
* to locate the actual pixel data as the source input for video
* encoder, plus whatever other information that is necessary. Stagefright
* media recording framework does not need to know anything specific about the
* metadata buffers, except for receving each individual metadata buffer
* as the source input, making a copy of the metadata buffer, and passing the
* copy via OpenMAX API to the video encoder component.
*
* The creator of the metadata buffers must ensure that the first
* 4 bytes in every metadata buffer indicates its buffer type,
* and the rest of the metadata buffer contains the
* actual metadata information. When a video encoder component receives
* a metadata buffer, it uses the first 4 bytes in that buffer to find
* out the type of the metadata buffer, and takes action appropriate
* to that type of metadata buffers (for instance, locate the actual
* pixel data input and then encoding the input data to produce a
* compressed output buffer).
*
* The following shows the layout of a metadata buffer,
* where buffer type is a 4-byte field of MetadataBufferType,
* and the payload is the metadata information.
*
* --------------------------------------------------------------
* | buffer type | payload |
* --------------------------------------------------------------
*
*/
typedef enum {
/*
* kMetadataBufferTypeCameraSource is used to indicate that
* the source of the metadata buffer is the camera component.
*/
kMetadataBufferTypeCameraSource = 0,
/*
* kMetadataBufferTypeGrallocSource is used to indicate that
* the payload of the metadata buffers can be interpreted as
* a buffer_handle_t.
* So in this case,the metadata that the encoder receives
* will have a byte stream that consists of two parts:
* 1. First, there is an integer indicating that it is a GRAlloc
* source (kMetadataBufferTypeGrallocSource)
* 2. This is followed by the buffer_handle_t that is a handle to the
* GRalloc buffer. The encoder needs to interpret this GRalloc handle
* and encode the frames.
* --------------------------------------------------------------
* | kMetadataBufferTypeGrallocSource | buffer_handle_t buffer |
* --------------------------------------------------------------
*
* See the VideoGrallocMetadata structure.
*/
kMetadataBufferTypeGrallocSource = 1,
/*
* kMetadataBufferTypeGraphicBuffer is used to indicate that
* the payload of the metadata buffers can be interpreted as
* an ANativeWindowBuffer, and that a fence is provided.
*
* In this case, the metadata will have a byte stream that consists of three parts:
* 1. First, there is an integer indicating that the metadata
* contains an ANativeWindowBuffer (kMetadataBufferTypeANWBuffer)
* 2. This is followed by the pointer to the ANativeWindowBuffer.
* Codec must not free this buffer as it does not actually own this buffer.
* 3. Finally, there is an integer containing a fence file descriptor.
* The codec must wait on the fence before encoding or decoding into this
* buffer. When the buffer is returned, codec must replace this file descriptor
* with a new fence, that will be waited on before the buffer is replaced
* (encoder) or read (decoder).
* ---------------------------------
* | kMetadataBufferTypeANWBuffer |
* ---------------------------------
* | ANativeWindowBuffer *buffer |
* ---------------------------------
* | int fenceFd |
* ---------------------------------
*
* See the VideoNativeMetadata structure.
*/
kMetadataBufferTypeANWBuffer = 2,
/* This value is used by framework, but is never used inside a metadata buffer */
kMetadataBufferTypeInvalid = -1,
// Add more here...
} MetadataBufferType;
#ifdef __cplusplus
} // namespace android
}
#endif
#endif // METADATA_BUFFER_TYPE_H
@@ -0,0 +1,59 @@
/*
* 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 OMX_PLUGIN_BASE_H_
#define OMX_PLUGIN_BASE_H_
#include <sys/types.h>
#include <OMX_Component.h>
#include <utils/String8.h>
#include <utils/Vector.h>
namespace android {
struct OMXPluginBase {
OMXPluginBase() {}
virtual ~OMXPluginBase() {}
virtual OMX_ERRORTYPE makeComponentInstance(
const char *name,
const OMX_CALLBACKTYPE *callbacks,
OMX_PTR appData,
OMX_COMPONENTTYPE **component) = 0;
virtual OMX_ERRORTYPE destroyComponentInstance(
OMX_COMPONENTTYPE *component) = 0;
virtual OMX_ERRORTYPE enumerateComponents(
OMX_STRING name,
size_t size,
OMX_U32 index) = 0;
virtual OMX_ERRORTYPE getRolesOfComponent(
const char *name,
Vector<String8> *roles) = 0;
private:
OMXPluginBase(const OMXPluginBase &);
OMXPluginBase &operator=(const OMXPluginBase &);
};
} // namespace android
#endif // OMX_PLUGIN_BASE_H_
@@ -0,0 +1,947 @@
/*
* Copyright 2014 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.
*/
/* NOTE: This file contains several sections for individual OMX include files.
Each section has its own include guard. This file should be included AFTER
the OMX include files. */
#ifdef OMX_Audio_h
/* asString definitions if media/openmax/OMX_Audio.h was included */
#ifndef AS_STRING_FOR_OMX_AUDIO_H
#define AS_STRING_FOR_OMX_AUDIO_H
inline static const char *asString(OMX_AUDIO_CODINGTYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_CodingUnused: return "Unused"; // unused
case OMX_AUDIO_CodingAutoDetect: return "AutoDetect"; // unused
case OMX_AUDIO_CodingPCM: return "PCM";
case OMX_AUDIO_CodingADPCM: return "ADPCM"; // unused
case OMX_AUDIO_CodingAMR: return "AMR";
case OMX_AUDIO_CodingGSMFR: return "GSMFR";
case OMX_AUDIO_CodingGSMEFR: return "GSMEFR"; // unused
case OMX_AUDIO_CodingGSMHR: return "GSMHR"; // unused
case OMX_AUDIO_CodingPDCFR: return "PDCFR"; // unused
case OMX_AUDIO_CodingPDCEFR: return "PDCEFR"; // unused
case OMX_AUDIO_CodingPDCHR: return "PDCHR"; // unused
case OMX_AUDIO_CodingTDMAFR: return "TDMAFR"; // unused
case OMX_AUDIO_CodingTDMAEFR: return "TDMAEFR"; // unused
case OMX_AUDIO_CodingQCELP8: return "QCELP8"; // unused
case OMX_AUDIO_CodingQCELP13: return "QCELP13"; // unused
case OMX_AUDIO_CodingEVRC: return "EVRC"; // unused
case OMX_AUDIO_CodingSMV: return "SMV"; // unused
case OMX_AUDIO_CodingG711: return "G711";
case OMX_AUDIO_CodingG723: return "G723"; // unused
case OMX_AUDIO_CodingG726: return "G726"; // unused
case OMX_AUDIO_CodingG729: return "G729"; // unused
case OMX_AUDIO_CodingAAC: return "AAC";
case OMX_AUDIO_CodingMP3: return "MP3";
case OMX_AUDIO_CodingSBC: return "SBC"; // unused
case OMX_AUDIO_CodingVORBIS: return "VORBIS";
case OMX_AUDIO_CodingWMA: return "WMA"; // unused
case OMX_AUDIO_CodingRA: return "RA"; // unused
case OMX_AUDIO_CodingMIDI: return "MIDI"; // unused
case OMX_AUDIO_CodingFLAC: return "FLAC";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_PCMMODETYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_PCMModeLinear: return "Linear";
case OMX_AUDIO_PCMModeALaw: return "ALaw";
case OMX_AUDIO_PCMModeMULaw: return "MULaw";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_CHANNELTYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_ChannelNone: return "None"; // unused
case OMX_AUDIO_ChannelLF: return "LF";
case OMX_AUDIO_ChannelRF: return "RF";
case OMX_AUDIO_ChannelCF: return "CF";
case OMX_AUDIO_ChannelLS: return "LS";
case OMX_AUDIO_ChannelRS: return "RS";
case OMX_AUDIO_ChannelLFE: return "LFE";
case OMX_AUDIO_ChannelCS: return "CS";
case OMX_AUDIO_ChannelLR: return "LR";
case OMX_AUDIO_ChannelRR: return "RR";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_CHANNELMODETYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_ChannelModeStereo: return "Stereo";
// case OMX_AUDIO_ChannelModeJointStereo: return "JointStereo";
// case OMX_AUDIO_ChannelModeDual: return "Dual";
case OMX_AUDIO_ChannelModeMono: return "Mono";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_AACSTREAMFORMATTYPE i, const char *def = "??") {
switch (i) {
// case OMX_AUDIO_AACStreamFormatMP2ADTS: return "MP2ADTS";
case OMX_AUDIO_AACStreamFormatMP4ADTS: return "MP4ADTS";
// case OMX_AUDIO_AACStreamFormatMP4LOAS: return "MP4LOAS";
// case OMX_AUDIO_AACStreamFormatMP4LATM: return "MP4LATM";
// case OMX_AUDIO_AACStreamFormatADIF: return "ADIF";
case OMX_AUDIO_AACStreamFormatMP4FF: return "MP4FF";
// case OMX_AUDIO_AACStreamFormatRAW: return "RAW";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_AMRFRAMEFORMATTYPE i, const char *def = "??") {
switch (i) {
// case OMX_AUDIO_AMRFrameFormatConformance: return "Conformance";
// case OMX_AUDIO_AMRFrameFormatIF1: return "IF1";
// case OMX_AUDIO_AMRFrameFormatIF2: return "IF2";
case OMX_AUDIO_AMRFrameFormatFSF: return "FSF";
// case OMX_AUDIO_AMRFrameFormatRTPPayload: return "RTPPayload";
// case OMX_AUDIO_AMRFrameFormatITU: return "ITU";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_AMRBANDMODETYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_AMRBandModeUnused: return "Unused";
case OMX_AUDIO_AMRBandModeNB0: return "NB0";
case OMX_AUDIO_AMRBandModeNB1: return "NB1";
case OMX_AUDIO_AMRBandModeNB2: return "NB2";
case OMX_AUDIO_AMRBandModeNB3: return "NB3";
case OMX_AUDIO_AMRBandModeNB4: return "NB4";
case OMX_AUDIO_AMRBandModeNB5: return "NB5";
case OMX_AUDIO_AMRBandModeNB6: return "NB6";
case OMX_AUDIO_AMRBandModeNB7: return "NB7";
case OMX_AUDIO_AMRBandModeWB0: return "WB0";
case OMX_AUDIO_AMRBandModeWB1: return "WB1";
case OMX_AUDIO_AMRBandModeWB2: return "WB2";
case OMX_AUDIO_AMRBandModeWB3: return "WB3";
case OMX_AUDIO_AMRBandModeWB4: return "WB4";
case OMX_AUDIO_AMRBandModeWB5: return "WB5";
case OMX_AUDIO_AMRBandModeWB6: return "WB6";
case OMX_AUDIO_AMRBandModeWB7: return "WB7";
case OMX_AUDIO_AMRBandModeWB8: return "WB8";
default: return def;
}
}
inline static const char *asString(OMX_AUDIO_AMRDTXMODETYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_AMRDTXModeOff: return "ModeOff";
// case OMX_AUDIO_AMRDTXModeOnVAD1: return "ModeOnVAD1";
// case OMX_AUDIO_AMRDTXModeOnVAD2: return "ModeOnVAD2";
// case OMX_AUDIO_AMRDTXModeOnAuto: return "ModeOnAuto";
// case OMX_AUDIO_AMRDTXasEFR: return "asEFR";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_AUDIO_H
#endif // OMX_Audio_h
#ifdef OMX_AudioExt_h
/* asString definitions if media/openmax/OMX_AudioExt.h was included */
#ifndef AS_STRING_FOR_OMX_AUDIOEXT_H
#define AS_STRING_FOR_OMX_AUDIOEXT_H
inline static const char *asString(OMX_AUDIO_CODINGEXTTYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_CodingAndroidAC3: return "AndroidAC3";
case OMX_AUDIO_CodingAndroidOPUS: return "AndroidOPUS";
default: return asString((OMX_AUDIO_CODINGTYPE)i, def);
}
}
#endif // AS_STRING_FOR_OMX_AUDIOEXT_H
#endif // OMX_AudioExt_h
#ifdef OMX_Component_h
/* asString definitions if media/openmax/OMX_Component.h was included */
#ifndef AS_STRING_FOR_OMX_COMPONENT_H
#define AS_STRING_FOR_OMX_COMPONENT_H
inline static const char *asString(OMX_PORTDOMAINTYPE i, const char *def = "??") {
switch (i) {
case OMX_PortDomainAudio: return "Audio";
case OMX_PortDomainVideo: return "Video";
case OMX_PortDomainImage: return "Image";
// case OMX_PortDomainOther: return "Other";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_COMPONENT_H
#endif // OMX_Component_h
#ifdef OMX_Core_h
/* asString definitions if media/openmax/OMX_Core.h was included */
#ifndef AS_STRING_FOR_OMX_CORE_H
#define AS_STRING_FOR_OMX_CORE_H
inline static const char *asString(OMX_COMMANDTYPE i, const char *def = "??") {
switch (i) {
case OMX_CommandStateSet: return "StateSet";
case OMX_CommandFlush: return "Flush";
case OMX_CommandPortDisable: return "PortDisable";
case OMX_CommandPortEnable: return "PortEnable";
// case OMX_CommandMarkBuffer: return "MarkBuffer";
default: return def;
}
}
inline static const char *asString(OMX_STATETYPE i, const char *def = "??") {
switch (i) {
case OMX_StateInvalid: return "Invalid";
case OMX_StateLoaded: return "Loaded";
case OMX_StateIdle: return "Idle";
case OMX_StateExecuting: return "Executing";
// case OMX_StatePause: return "Pause";
// case OMX_StateWaitForResources: return "WaitForResources";
default: return def;
}
}
inline static const char *asString(OMX_ERRORTYPE i, const char *def = "??") {
switch (i) {
case OMX_ErrorNone: return "None";
case OMX_ErrorInsufficientResources: return "InsufficientResources";
case OMX_ErrorUndefined: return "Undefined";
case OMX_ErrorInvalidComponentName: return "InvalidComponentName";
case OMX_ErrorComponentNotFound: return "ComponentNotFound";
case OMX_ErrorInvalidComponent: return "InvalidComponent"; // unused
case OMX_ErrorBadParameter: return "BadParameter";
case OMX_ErrorNotImplemented: return "NotImplemented";
case OMX_ErrorUnderflow: return "Underflow"; // unused
case OMX_ErrorOverflow: return "Overflow"; // unused
case OMX_ErrorHardware: return "Hardware"; // unused
case OMX_ErrorInvalidState: return "InvalidState";
case OMX_ErrorStreamCorrupt: return "StreamCorrupt";
case OMX_ErrorPortsNotCompatible: return "PortsNotCompatible"; // unused
case OMX_ErrorResourcesLost: return "ResourcesLost";
case OMX_ErrorNoMore: return "NoMore";
case OMX_ErrorVersionMismatch: return "VersionMismatch"; // unused
case OMX_ErrorNotReady: return "NotReady"; // unused
case OMX_ErrorTimeout: return "Timeout"; // unused
case OMX_ErrorSameState: return "SameState"; // unused
case OMX_ErrorResourcesPreempted: return "ResourcesPreempted"; // unused
case OMX_ErrorPortUnresponsiveDuringAllocation:
return "PortUnresponsiveDuringAllocation"; // unused
case OMX_ErrorPortUnresponsiveDuringDeallocation:
return "PortUnresponsiveDuringDeallocation"; // unused
case OMX_ErrorPortUnresponsiveDuringStop:
return "PortUnresponsiveDuringStop"; // unused
case OMX_ErrorIncorrectStateTransition:
return "IncorrectStateTransition"; // unused
case OMX_ErrorIncorrectStateOperation:
return "IncorrectStateOperation"; // unused
case OMX_ErrorUnsupportedSetting: return "UnsupportedSetting";
case OMX_ErrorUnsupportedIndex: return "UnsupportedIndex";
case OMX_ErrorBadPortIndex: return "BadPortIndex";
case OMX_ErrorPortUnpopulated: return "PortUnpopulated"; // unused
case OMX_ErrorComponentSuspended: return "ComponentSuspended"; // unused
case OMX_ErrorDynamicResourcesUnavailable:
return "DynamicResourcesUnavailable"; // unused
case OMX_ErrorMbErrorsInFrame: return "MbErrorsInFrame"; // unused
case OMX_ErrorFormatNotDetected: return "FormatNotDetected"; // unused
case OMX_ErrorContentPipeOpenFailed: return "ContentPipeOpenFailed"; // unused
case OMX_ErrorContentPipeCreationFailed:
return "ContentPipeCreationFailed"; // unused
case OMX_ErrorSeperateTablesUsed: return "SeperateTablesUsed"; // unused
case OMX_ErrorTunnelingUnsupported: return "TunnelingUnsupported"; // unused
default: return def;
}
}
inline static const char *asString(OMX_EVENTTYPE i, const char *def = "??") {
switch (i) {
case OMX_EventCmdComplete: return "CmdComplete";
case OMX_EventError: return "Error";
// case OMX_EventMark: return "Mark";
case OMX_EventPortSettingsChanged: return "PortSettingsChanged";
case OMX_EventBufferFlag: return "BufferFlag";
// case OMX_EventResourcesAcquired: return "ResourcesAcquired";
// case OMX_EventComponentResumed: return "ComponentResumed";
// case OMX_EventDynamicResourcesAvailable: return "DynamicResourcesAvailable";
// case OMX_EventPortFormatDetected: return "PortFormatDetected";
case OMX_EventOutputRendered: return "OutputRendered";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_CORE_H
#endif // OMX_Core_h
#ifdef OMX_Image_h
/* asString definitions if media/openmax/OMX_Image.h was included */
#ifndef AS_STRING_FOR_OMX_IMAGE_H
#define AS_STRING_FOR_OMX_IMAGE_H
inline static const char *asString(OMX_IMAGE_CODINGTYPE i, const char *def = "??") {
switch (i) {
case OMX_IMAGE_CodingUnused: return "Unused";
case OMX_IMAGE_CodingAutoDetect: return "AutoDetect"; // unused
case OMX_IMAGE_CodingJPEG: return "JPEG";
case OMX_IMAGE_CodingJPEG2K: return "JPEG2K"; // unused
case OMX_IMAGE_CodingEXIF: return "EXIF"; // unused
case OMX_IMAGE_CodingTIFF: return "TIFF"; // unused
case OMX_IMAGE_CodingGIF: return "GIF"; // unused
case OMX_IMAGE_CodingPNG: return "PNG"; // unused
case OMX_IMAGE_CodingLZW: return "LZW"; // unused
case OMX_IMAGE_CodingBMP: return "BMP"; // unused
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_IMAGE_H
#endif // OMX_Image_h
#ifdef OMX_Index_h
/* asString definitions if media/openmax/OMX_Index.h was included */
#ifndef AS_STRING_FOR_OMX_INDEX_H
#define AS_STRING_FOR_OMX_INDEX_H
inline static const char *asString(OMX_INDEXTYPE i, const char *def = "??") {
switch (i) {
// case OMX_IndexParamPriorityMgmt: return "ParamPriorityMgmt";
// case OMX_IndexParamAudioInit: return "ParamAudioInit";
// case OMX_IndexParamImageInit: return "ParamImageInit";
// case OMX_IndexParamVideoInit: return "ParamVideoInit";
// case OMX_IndexParamOtherInit: return "ParamOtherInit";
// case OMX_IndexParamNumAvailableStreams: return "ParamNumAvailableStreams";
// case OMX_IndexParamActiveStream: return "ParamActiveStream";
// case OMX_IndexParamSuspensionPolicy: return "ParamSuspensionPolicy";
// case OMX_IndexParamComponentSuspended: return "ParamComponentSuspended";
// case OMX_IndexConfigCapturing: return "ConfigCapturing";
// case OMX_IndexConfigCaptureMode: return "ConfigCaptureMode";
// case OMX_IndexAutoPauseAfterCapture: return "AutoPauseAfterCapture";
// case OMX_IndexParamContentURI: return "ParamContentURI";
// case OMX_IndexParamCustomContentPipe: return "ParamCustomContentPipe";
// case OMX_IndexParamDisableResourceConcealment:
// return "ParamDisableResourceConcealment";
// case OMX_IndexConfigMetadataItemCount: return "ConfigMetadataItemCount";
// case OMX_IndexConfigContainerNodeCount: return "ConfigContainerNodeCount";
// case OMX_IndexConfigMetadataItem: return "ConfigMetadataItem";
// case OMX_IndexConfigCounterNodeID: return "ConfigCounterNodeID";
// case OMX_IndexParamMetadataFilterType: return "ParamMetadataFilterType";
// case OMX_IndexParamMetadataKeyFilter: return "ParamMetadataKeyFilter";
// case OMX_IndexConfigPriorityMgmt: return "ConfigPriorityMgmt";
case OMX_IndexParamStandardComponentRole: return "ParamStandardComponentRole";
case OMX_IndexParamPortDefinition: return "ParamPortDefinition";
// case OMX_IndexParamCompBufferSupplier: return "ParamCompBufferSupplier";
case OMX_IndexParamAudioPortFormat: return "ParamAudioPortFormat";
case OMX_IndexParamAudioPcm: return "ParamAudioPcm";
case OMX_IndexParamAudioAac: return "ParamAudioAac";
// case OMX_IndexParamAudioRa: return "ParamAudioRa";
case OMX_IndexParamAudioMp3: return "ParamAudioMp3";
// case OMX_IndexParamAudioAdpcm: return "ParamAudioAdpcm";
// case OMX_IndexParamAudioG723: return "ParamAudioG723";
// case OMX_IndexParamAudioG729: return "ParamAudioG729";
case OMX_IndexParamAudioAmr: return "ParamAudioAmr";
// case OMX_IndexParamAudioWma: return "ParamAudioWma";
// case OMX_IndexParamAudioSbc: return "ParamAudioSbc";
// case OMX_IndexParamAudioMidi: return "ParamAudioMidi";
// case OMX_IndexParamAudioGsm_FR: return "ParamAudioGsm_FR";
// case OMX_IndexParamAudioMidiLoadUserSound: return "ParamAudioMidiLoadUserSound";
// case OMX_IndexParamAudioG726: return "ParamAudioG726";
// case OMX_IndexParamAudioGsm_EFR: return "ParamAudioGsm_EFR";
// case OMX_IndexParamAudioGsm_HR: return "ParamAudioGsm_HR";
// case OMX_IndexParamAudioPdc_FR: return "ParamAudioPdc_FR";
// case OMX_IndexParamAudioPdc_EFR: return "ParamAudioPdc_EFR";
// case OMX_IndexParamAudioPdc_HR: return "ParamAudioPdc_HR";
// case OMX_IndexParamAudioTdma_FR: return "ParamAudioTdma_FR";
// case OMX_IndexParamAudioTdma_EFR: return "ParamAudioTdma_EFR";
// case OMX_IndexParamAudioQcelp8: return "ParamAudioQcelp8";
// case OMX_IndexParamAudioQcelp13: return "ParamAudioQcelp13";
// case OMX_IndexParamAudioEvrc: return "ParamAudioEvrc";
// case OMX_IndexParamAudioSmv: return "ParamAudioSmv";
case OMX_IndexParamAudioVorbis: return "ParamAudioVorbis";
case OMX_IndexParamAudioFlac: return "ParamAudioFlac";
// case OMX_IndexConfigAudioMidiImmediateEvent: return "ConfigAudioMidiImmediateEvent";
// case OMX_IndexConfigAudioMidiControl: return "ConfigAudioMidiControl";
// case OMX_IndexConfigAudioMidiSoundBankProgram:
// return "ConfigAudioMidiSoundBankProgram";
// case OMX_IndexConfigAudioMidiStatus: return "ConfigAudioMidiStatus";
// case OMX_IndexConfigAudioMidiMetaEvent: return "ConfigAudioMidiMetaEvent";
// case OMX_IndexConfigAudioMidiMetaEventData: return "ConfigAudioMidiMetaEventData";
// case OMX_IndexConfigAudioVolume: return "ConfigAudioVolume";
// case OMX_IndexConfigAudioBalance: return "ConfigAudioBalance";
// case OMX_IndexConfigAudioChannelMute: return "ConfigAudioChannelMute";
// case OMX_IndexConfigAudioMute: return "ConfigAudioMute";
// case OMX_IndexConfigAudioLoudness: return "ConfigAudioLoudness";
// case OMX_IndexConfigAudioEchoCancelation: return "ConfigAudioEchoCancelation";
// case OMX_IndexConfigAudioNoiseReduction: return "ConfigAudioNoiseReduction";
// case OMX_IndexConfigAudioBass: return "ConfigAudioBass";
// case OMX_IndexConfigAudioTreble: return "ConfigAudioTreble";
// case OMX_IndexConfigAudioStereoWidening: return "ConfigAudioStereoWidening";
// case OMX_IndexConfigAudioChorus: return "ConfigAudioChorus";
// case OMX_IndexConfigAudioEqualizer: return "ConfigAudioEqualizer";
// case OMX_IndexConfigAudioReverberation: return "ConfigAudioReverberation";
// case OMX_IndexConfigAudioChannelVolume: return "ConfigAudioChannelVolume";
// case OMX_IndexParamImagePortFormat: return "ParamImagePortFormat";
// case OMX_IndexParamFlashControl: return "ParamFlashControl";
// case OMX_IndexConfigFocusControl: return "ConfigFocusControl";
// case OMX_IndexParamQFactor: return "ParamQFactor";
// case OMX_IndexParamQuantizationTable: return "ParamQuantizationTable";
// case OMX_IndexParamHuffmanTable: return "ParamHuffmanTable";
// case OMX_IndexConfigFlashControl: return "ConfigFlashControl";
case OMX_IndexParamVideoPortFormat: return "ParamVideoPortFormat";
// case OMX_IndexParamVideoQuantization: return "ParamVideoQuantization";
// case OMX_IndexParamVideoFastUpdate: return "ParamVideoFastUpdate";
case OMX_IndexParamVideoBitrate: return "ParamVideoBitrate";
// case OMX_IndexParamVideoMotionVector: return "ParamVideoMotionVector";
case OMX_IndexParamVideoIntraRefresh: return "ParamVideoIntraRefresh";
case OMX_IndexParamVideoErrorCorrection: return "ParamVideoErrorCorrection";
// case OMX_IndexParamVideoVBSMC: return "ParamVideoVBSMC";
// case OMX_IndexParamVideoMpeg2: return "ParamVideoMpeg2";
case OMX_IndexParamVideoMpeg4: return "ParamVideoMpeg4";
// case OMX_IndexParamVideoWmv: return "ParamVideoWmv";
// case OMX_IndexParamVideoRv: return "ParamVideoRv";
case OMX_IndexParamVideoAvc: return "ParamVideoAvc";
case OMX_IndexParamVideoH263: return "ParamVideoH263";
case OMX_IndexParamVideoProfileLevelQuerySupported:
return "ParamVideoProfileLevelQuerySupported";
case OMX_IndexParamVideoProfileLevelCurrent: return "ParamVideoProfileLevelCurrent";
case OMX_IndexConfigVideoBitrate: return "ConfigVideoBitrate";
// case OMX_IndexConfigVideoFramerate: return "ConfigVideoFramerate";
case OMX_IndexConfigVideoIntraVOPRefresh: return "ConfigVideoIntraVOPRefresh";
// case OMX_IndexConfigVideoIntraMBRefresh: return "ConfigVideoIntraMBRefresh";
// case OMX_IndexConfigVideoMBErrorReporting: return "ConfigVideoMBErrorReporting";
// case OMX_IndexParamVideoMacroblocksPerFrame: return "ParamVideoMacroblocksPerFrame";
// case OMX_IndexConfigVideoMacroBlockErrorMap: return "ConfigVideoMacroBlockErrorMap";
// case OMX_IndexParamVideoSliceFMO: return "ParamVideoSliceFMO";
// case OMX_IndexConfigVideoAVCIntraPeriod: return "ConfigVideoAVCIntraPeriod";
// case OMX_IndexConfigVideoNalSize: return "ConfigVideoNalSize";
// case OMX_IndexParamCommonDeblocking: return "ParamCommonDeblocking";
// case OMX_IndexParamCommonSensorMode: return "ParamCommonSensorMode";
// case OMX_IndexParamCommonInterleave: return "ParamCommonInterleave";
// case OMX_IndexConfigCommonColorFormatConversion:
// return "ConfigCommonColorFormatConversion";
case OMX_IndexConfigCommonScale: return "ConfigCommonScale";
// case OMX_IndexConfigCommonImageFilter: return "ConfigCommonImageFilter";
// case OMX_IndexConfigCommonColorEnhancement: return "ConfigCommonColorEnhancement";
// case OMX_IndexConfigCommonColorKey: return "ConfigCommonColorKey";
// case OMX_IndexConfigCommonColorBlend: return "ConfigCommonColorBlend";
// case OMX_IndexConfigCommonFrameStabilisation: return "ConfigCommonFrameStabilisation";
// case OMX_IndexConfigCommonRotate: return "ConfigCommonRotate";
// case OMX_IndexConfigCommonMirror: return "ConfigCommonMirror";
// case OMX_IndexConfigCommonOutputPosition: return "ConfigCommonOutputPosition";
case OMX_IndexConfigCommonInputCrop: return "ConfigCommonInputCrop";
case OMX_IndexConfigCommonOutputCrop: return "ConfigCommonOutputCrop";
// case OMX_IndexConfigCommonDigitalZoom: return "ConfigCommonDigitalZoom";
// case OMX_IndexConfigCommonOpticalZoom: return "ConfigCommonOpticalZoom";
// case OMX_IndexConfigCommonWhiteBalance: return "ConfigCommonWhiteBalance";
// case OMX_IndexConfigCommonExposure: return "ConfigCommonExposure";
// case OMX_IndexConfigCommonContrast: return "ConfigCommonContrast";
// case OMX_IndexConfigCommonBrightness: return "ConfigCommonBrightness";
// case OMX_IndexConfigCommonBacklight: return "ConfigCommonBacklight";
// case OMX_IndexConfigCommonGamma: return "ConfigCommonGamma";
// case OMX_IndexConfigCommonSaturation: return "ConfigCommonSaturation";
// case OMX_IndexConfigCommonLightness: return "ConfigCommonLightness";
// case OMX_IndexConfigCommonExclusionRect: return "ConfigCommonExclusionRect";
// case OMX_IndexConfigCommonDithering: return "ConfigCommonDithering";
// case OMX_IndexConfigCommonPlaneBlend: return "ConfigCommonPlaneBlend";
// case OMX_IndexConfigCommonExposureValue: return "ConfigCommonExposureValue";
// case OMX_IndexConfigCommonOutputSize: return "ConfigCommonOutputSize";
// case OMX_IndexParamCommonExtraQuantData: return "ParamCommonExtraQuantData";
// case OMX_IndexConfigCommonFocusRegion: return "ConfigCommonFocusRegion";
// case OMX_IndexConfigCommonFocusStatus: return "ConfigCommonFocusStatus";
// case OMX_IndexConfigCommonTransitionEffect: return "ConfigCommonTransitionEffect";
// case OMX_IndexParamOtherPortFormat: return "ParamOtherPortFormat";
// case OMX_IndexConfigOtherPower: return "ConfigOtherPower";
// case OMX_IndexConfigOtherStats: return "ConfigOtherStats";
// case OMX_IndexConfigTimeScale: return "ConfigTimeScale";
// case OMX_IndexConfigTimeClockState: return "ConfigTimeClockState";
// case OMX_IndexConfigTimeActiveRefClock: return "ConfigTimeActiveRefClock";
// case OMX_IndexConfigTimeCurrentMediaTime: return "ConfigTimeCurrentMediaTime";
// case OMX_IndexConfigTimeCurrentWallTime: return "ConfigTimeCurrentWallTime";
// case OMX_IndexConfigTimeCurrentAudioReference:
// return "ConfigTimeCurrentAudioReference";
// case OMX_IndexConfigTimeCurrentVideoReference:
// return "ConfigTimeCurrentVideoReference";
// case OMX_IndexConfigTimeMediaTimeRequest: return "ConfigTimeMediaTimeRequest";
// case OMX_IndexConfigTimeClientStartTime: return "ConfigTimeClientStartTime";
// case OMX_IndexConfigTimePosition: return "ConfigTimePosition";
// case OMX_IndexConfigTimeSeekMode: return "ConfigTimeSeekMode";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_INDEX_H
#endif // OMX_Index_h
#ifdef OMX_IndexExt_h
/* asString definitions if media/openmax/OMX_IndexExt.h was included */
#ifndef AS_STRING_FOR_OMX_INDEXEXT_H
#define AS_STRING_FOR_OMX_INDEXEXT_H
inline static const char *asString(OMX_INDEXEXTTYPE i, const char *def = "??") {
switch (i) {
// case OMX_IndexConfigCallbackRequest: return "ConfigCallbackRequest";
// case OMX_IndexConfigCommitMode: return "ConfigCommitMode";
// case OMX_IndexConfigCommit: return "ConfigCommit";
case OMX_IndexParamAudioAndroidAc3: return "ParamAudioAndroidAc3";
case OMX_IndexParamAudioAndroidOpus: return "ParamAudioAndroidOpus";
case OMX_IndexParamAudioAndroidAacPresentation: return "ParamAudioAndroidAacPresentation";
// case OMX_IndexParamNalStreamFormatSupported: return "ParamNalStreamFormatSupported";
// case OMX_IndexParamNalStreamFormat: return "ParamNalStreamFormat";
// case OMX_IndexParamNalStreamFormatSelect: return "ParamNalStreamFormatSelect";
case OMX_IndexParamVideoVp8: return "ParamVideoVp8";
// case OMX_IndexConfigVideoVp8ReferenceFrame: return "ConfigVideoVp8ReferenceFrame";
// case OMX_IndexConfigVideoVp8ReferenceFrameType: return "ConfigVideoVp8ReferenceFrameType";
case OMX_IndexParamVideoAndroidVp8Encoder: return "ParamVideoAndroidVp8Encoder";
case OMX_IndexParamVideoHevc: return "ParamVideoHevc";
// case OMX_IndexParamSliceSegments: return "ParamSliceSegments";
case OMX_IndexConfigAutoFramerateConversion: return "ConfigAutoFramerateConversion";
case OMX_IndexConfigPriority: return "ConfigPriority";
case OMX_IndexConfigOperatingRate: return "ConfigOperatingRate";
case OMX_IndexParamConsumerUsageBits: return "ParamConsumerUsageBits";
default: return asString((OMX_INDEXTYPE)i, def);
}
}
#endif // AS_STRING_FOR_OMX_INDEXEXT_H
#endif // OMX_IndexExt_h
#ifdef OMX_IVCommon_h
/* asString definitions if media/openmax/OMX_IVCommon.h was included */
#ifndef AS_STRING_FOR_OMX_IVCOMMON_H
#define AS_STRING_FOR_OMX_IVCOMMON_H
inline static const char *asString(OMX_COLOR_FORMATTYPE i, const char *def = "??") {
switch (i) {
case OMX_COLOR_FormatUnused:
return "COLOR_FormatUnused";
case OMX_COLOR_FormatMonochrome:
return "COLOR_FormatMonochrome";
case OMX_COLOR_Format8bitRGB332:
return "COLOR_Format8bitRGB332";
case OMX_COLOR_Format12bitRGB444:
return "COLOR_Format12bitRGB444";
case OMX_COLOR_Format16bitARGB4444:
return "COLOR_Format16bitARGB4444";
case OMX_COLOR_Format16bitARGB1555:
return "COLOR_Format16bitARGB1555";
case OMX_COLOR_Format16bitRGB565:
return "COLOR_Format16bitRGB565";
case OMX_COLOR_Format16bitBGR565:
return "COLOR_Format16bitBGR565";
case OMX_COLOR_Format18bitRGB666:
return "COLOR_Format18bitRGB666";
case OMX_COLOR_Format18bitARGB1665:
return "COLOR_Format18bitARGB1665";
case OMX_COLOR_Format19bitARGB1666:
return "COLOR_Format19bitARGB1666";
case OMX_COLOR_Format24bitRGB888:
return "COLOR_Format24bitRGB888";
case OMX_COLOR_Format24bitBGR888:
return "COLOR_Format24bitBGR888";
case OMX_COLOR_Format24bitARGB1887:
return "COLOR_Format24bitARGB1887";
case OMX_COLOR_Format25bitARGB1888:
return "COLOR_Format25bitARGB1888";
case OMX_COLOR_Format32bitBGRA8888:
return "COLOR_Format32bitBGRA8888";
case OMX_COLOR_Format32bitARGB8888:
return "COLOR_Format32bitARGB8888";
case OMX_COLOR_FormatYUV411Planar:
return "COLOR_FormatYUV411Planar";
case OMX_COLOR_FormatYUV411PackedPlanar:
return "COLOR_FormatYUV411PackedPlanar";
case OMX_COLOR_FormatYUV420Planar:
return "COLOR_FormatYUV420Planar";
case OMX_COLOR_FormatYUV420PackedPlanar:
return "COLOR_FormatYUV420PackedPlanar";
case OMX_COLOR_FormatYUV420SemiPlanar:
return "COLOR_FormatYUV420SemiPlanar";
case OMX_COLOR_FormatYUV422Planar:
return "COLOR_FormatYUV422Planar";
case OMX_COLOR_FormatYUV422PackedPlanar:
return "COLOR_FormatYUV422PackedPlanar";
case OMX_COLOR_FormatYUV422SemiPlanar:
return "COLOR_FormatYUV422SemiPlanar";
case OMX_COLOR_FormatYCbYCr:
return "COLOR_FormatYCbYCr";
case OMX_COLOR_FormatYCrYCb:
return "COLOR_FormatYCrYCb";
case OMX_COLOR_FormatCbYCrY:
return "COLOR_FormatCbYCrY";
case OMX_COLOR_FormatCrYCbY:
return "COLOR_FormatCrYCbY";
case OMX_COLOR_FormatYUV444Interleaved:
return "COLOR_FormatYUV444Interleaved";
case OMX_COLOR_FormatRawBayer8bit:
return "COLOR_FormatRawBayer8bit";
case OMX_COLOR_FormatRawBayer10bit:
return "COLOR_FormatRawBayer10bit";
case OMX_COLOR_FormatRawBayer8bitcompressed:
return "COLOR_FormatRawBayer8bitcompressed";
case OMX_COLOR_FormatL2:
return "COLOR_FormatL2";
case OMX_COLOR_FormatL4:
return "COLOR_FormatL4";
case OMX_COLOR_FormatL8:
return "COLOR_FormatL8";
case OMX_COLOR_FormatL16:
return "COLOR_FormatL16";
case OMX_COLOR_FormatL24:
return "COLOR_FormatL24";
case OMX_COLOR_FormatL32:
return "COLOR_FormatL32";
case OMX_COLOR_FormatYUV420PackedSemiPlanar:
return "COLOR_FormatYUV420PackedSemiPlanar";
case OMX_COLOR_FormatYUV422PackedSemiPlanar:
return "COLOR_FormatYUV422PackedSemiPlanar";
case OMX_COLOR_Format18BitBGR666:
return "COLOR_Format18BitBGR666";
case OMX_COLOR_Format24BitARGB6666:
return "COLOR_Format24BitARGB6666";
case OMX_COLOR_Format24BitABGR6666:
return "COLOR_Format24BitABGR6666";
case OMX_COLOR_FormatAndroidOpaque:
return "COLOR_FormatAndroidOpaque";
case OMX_COLOR_FormatYUV420Flexible:
return "COLOR_FormatYUV420Flexible";
case OMX_TI_COLOR_FormatYUV420PackedSemiPlanar:
return "TI_COLOR_FormatYUV420PackedSemiPlanar";
case OMX_QCOM_COLOR_FormatYVU420SemiPlanar:
return "QCOM_COLOR_FormatYVU420SemiPlanar";
// case OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka:
// return "QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka";
// case OMX_SEC_COLOR_FormatNV12Tiled:
// return "SEC_COLOR_FormatNV12Tiled";
// case OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m:
// return "QCOM_COLOR_FormatYUV420PackedSemiPlanar32m";
default:
return def;
}
}
#endif // AS_STRING_FOR_OMX_IVCOMMON_H
#endif // OMX_IVCommon_h
#ifdef OMX_Types_h
/* asString definitions if media/openmax/OMX_Types.h was included */
#ifndef AS_STRING_FOR_OMX_TYPES_H
#define AS_STRING_FOR_OMX_TYPES_H
inline static const char *asString(OMX_BOOL i, const char *def = "??") {
switch (i) {
case OMX_FALSE: return "FALSE";
case OMX_TRUE: return "TRUE";
default: return def;
}
}
inline static const char *asString(OMX_DIRTYPE i, const char *def = "??") {
switch (i) {
case OMX_DirInput: return "Input";
case OMX_DirOutput: return "Output";
default: return def;
}
}
inline static const char *asString(OMX_ENDIANTYPE i, const char *def = "??") {
switch (i) {
case OMX_EndianBig: return "Big";
// case OMX_EndianLittle: return "Little";
default: return def;
}
}
inline static const char *asString(OMX_NUMERICALDATATYPE i, const char *def = "??") {
switch (i) {
case OMX_NumericalDataSigned: return "Signed";
// case OMX_NumericalDataUnsigned: return "Unsigned";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_TYPES_H
#endif // OMX_Types_h
#ifdef OMX_Video_h
/* asString definitions if media/openmax/OMX_Video.h was included */
#ifndef AS_STRING_FOR_OMX_VIDEO_H
#define AS_STRING_FOR_OMX_VIDEO_H
inline static const char *asString(OMX_VIDEO_CODINGTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_CodingUnused: return "Unused";
case OMX_VIDEO_CodingAutoDetect: return "AutoDetect"; // unused
case OMX_VIDEO_CodingMPEG2: return "MPEG2";
case OMX_VIDEO_CodingH263: return "H263";
case OMX_VIDEO_CodingMPEG4: return "MPEG4";
case OMX_VIDEO_CodingWMV: return "WMV"; // unused
case OMX_VIDEO_CodingRV: return "RV"; // unused
case OMX_VIDEO_CodingAVC: return "AVC";
case OMX_VIDEO_CodingMJPEG: return "MJPEG"; // unused
case OMX_VIDEO_CodingVP8: return "VP8";
case OMX_VIDEO_CodingVP9: return "VP9";
case OMX_VIDEO_CodingHEVC: return "HEVC";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_CONTROLRATETYPE i, const char *def = "??") {
switch (i) {
// case OMX_Video_ControlRateDisable: return "Disable";
case OMX_Video_ControlRateVariable: return "Variable";
case OMX_Video_ControlRateConstant: return "Constant";
// case OMX_Video_ControlRateVariableSkipFrames: return "VariableSkipFrames";
// case OMX_Video_ControlRateConstantSkipFrames: return "ConstantSkipFrames";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_INTRAREFRESHTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_IntraRefreshCyclic: return "Cyclic";
case OMX_VIDEO_IntraRefreshAdaptive: return "Adaptive";
case OMX_VIDEO_IntraRefreshBoth: return "Both";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_H263PROFILETYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_H263ProfileBaseline: return "Baseline";
case OMX_VIDEO_H263ProfileH320Coding: return "H320Coding";
case OMX_VIDEO_H263ProfileBackwardCompatible: return "BackwardCompatible";
case OMX_VIDEO_H263ProfileISWV2: return "ISWV2";
case OMX_VIDEO_H263ProfileISWV3: return "ISWV3";
case OMX_VIDEO_H263ProfileHighCompression: return "HighCompression";
case OMX_VIDEO_H263ProfileInternet: return "Internet";
case OMX_VIDEO_H263ProfileInterlace: return "Interlace";
case OMX_VIDEO_H263ProfileHighLatency: return "HighLatency";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_H263LEVELTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_H263Level10: return "Level10";
case OMX_VIDEO_H263Level20: return "Level20";
case OMX_VIDEO_H263Level30: return "Level30";
case OMX_VIDEO_H263Level40: return "Level40";
case OMX_VIDEO_H263Level45: return "Level45";
case OMX_VIDEO_H263Level50: return "Level50";
case OMX_VIDEO_H263Level60: return "Level60";
case OMX_VIDEO_H263Level70: return "Level70";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_PICTURETYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_PictureTypeI: return "I";
case OMX_VIDEO_PictureTypeP: return "P";
case OMX_VIDEO_PictureTypeB: return "B";
// case OMX_VIDEO_PictureTypeSI: return "SI";
// case OMX_VIDEO_PictureTypeSP: return "SP";
// case OMX_VIDEO_PictureTypeEI: return "EI";
// case OMX_VIDEO_PictureTypeEP: return "EP";
// case OMX_VIDEO_PictureTypeS: return "S";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_MPEG4PROFILETYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_MPEG4ProfileSimple: return "Simple";
case OMX_VIDEO_MPEG4ProfileSimpleScalable: return "SimpleScalable";
case OMX_VIDEO_MPEG4ProfileCore: return "Core";
case OMX_VIDEO_MPEG4ProfileMain: return "Main";
case OMX_VIDEO_MPEG4ProfileNbit: return "Nbit";
case OMX_VIDEO_MPEG4ProfileScalableTexture: return "ScalableTexture";
case OMX_VIDEO_MPEG4ProfileSimpleFace: return "SimpleFace";
case OMX_VIDEO_MPEG4ProfileSimpleFBA: return "SimpleFBA";
case OMX_VIDEO_MPEG4ProfileBasicAnimated: return "BasicAnimated";
case OMX_VIDEO_MPEG4ProfileHybrid: return "Hybrid";
case OMX_VIDEO_MPEG4ProfileAdvancedRealTime: return "AdvancedRealTime";
case OMX_VIDEO_MPEG4ProfileCoreScalable: return "CoreScalable";
case OMX_VIDEO_MPEG4ProfileAdvancedCoding: return "AdvancedCoding";
case OMX_VIDEO_MPEG4ProfileAdvancedCore: return "AdvancedCore";
case OMX_VIDEO_MPEG4ProfileAdvancedScalable: return "AdvancedScalable";
case OMX_VIDEO_MPEG4ProfileAdvancedSimple: return "AdvancedSimple";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_MPEG4LEVELTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_MPEG4Level0: return "Level0";
case OMX_VIDEO_MPEG4Level0b: return "Level0b";
case OMX_VIDEO_MPEG4Level1: return "Level1";
case OMX_VIDEO_MPEG4Level2: return "Level2";
case OMX_VIDEO_MPEG4Level3: return "Level3";
case OMX_VIDEO_MPEG4Level4: return "Level4";
case OMX_VIDEO_MPEG4Level4a: return "Level4a";
case OMX_VIDEO_MPEG4Level5: return "Level5";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_AVCPROFILETYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_AVCProfileBaseline: return "Baseline";
case OMX_VIDEO_AVCProfileMain: return "Main";
case OMX_VIDEO_AVCProfileExtended: return "Extended";
case OMX_VIDEO_AVCProfileHigh: return "High";
case OMX_VIDEO_AVCProfileHigh10: return "High10";
case OMX_VIDEO_AVCProfileHigh422: return "High422";
case OMX_VIDEO_AVCProfileHigh444: return "High444";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_AVCLEVELTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_AVCLevel1: return "Level1";
case OMX_VIDEO_AVCLevel1b: return "Level1b";
case OMX_VIDEO_AVCLevel11: return "Level11";
case OMX_VIDEO_AVCLevel12: return "Level12";
case OMX_VIDEO_AVCLevel13: return "Level13";
case OMX_VIDEO_AVCLevel2: return "Level2";
case OMX_VIDEO_AVCLevel21: return "Level21";
case OMX_VIDEO_AVCLevel22: return "Level22";
case OMX_VIDEO_AVCLevel3: return "Level3";
case OMX_VIDEO_AVCLevel31: return "Level31";
case OMX_VIDEO_AVCLevel32: return "Level32";
case OMX_VIDEO_AVCLevel4: return "Level4";
case OMX_VIDEO_AVCLevel41: return "Level41";
case OMX_VIDEO_AVCLevel42: return "Level42";
case OMX_VIDEO_AVCLevel5: return "Level5";
case OMX_VIDEO_AVCLevel51: return "Level51";
case OMX_VIDEO_AVCLevel52: return "Level52";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_AVCLOOPFILTERTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_AVCLoopFilterEnable: return "Enable";
// case OMX_VIDEO_AVCLoopFilterDisable: return "Disable";
// case OMX_VIDEO_AVCLoopFilterDisableSliceBoundary: return "DisableSliceBoundary";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_VIDEO_H
#endif // OMX_Video_h
#ifdef OMX_VideoExt_h
/* asString definitions if media/openmax/OMX_VideoExt.h was included */
#ifndef AS_STRING_FOR_OMX_VIDEOEXT_H
#define AS_STRING_FOR_OMX_VIDEOEXT_H
inline static const char *asString(OMX_VIDEO_VP8PROFILETYPE i, const char *def = "!!") {
switch (i) {
case OMX_VIDEO_VP8ProfileMain: return "Main";
case OMX_VIDEO_VP8ProfileUnknown: return "Unknown"; // unused
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_VP8LEVELTYPE i, const char *def = "!!") {
switch (i) {
case OMX_VIDEO_VP8Level_Version0: return "_Version0";
case OMX_VIDEO_VP8Level_Version1: return "_Version1";
case OMX_VIDEO_VP8Level_Version2: return "_Version2";
case OMX_VIDEO_VP8Level_Version3: return "_Version3";
case OMX_VIDEO_VP8LevelUnknown: return "Unknown"; // unused
default: return def;
}
}
inline static const char *asString(
OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE i, const char *def = "??") {
switch (i) {
case OMX_VIDEO_VPXTemporalLayerPatternNone: return "VPXTemporalLayerPatternNone";
case OMX_VIDEO_VPXTemporalLayerPatternWebRTC: return "VPXTemporalLayerPatternWebRTC";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_HEVCPROFILETYPE i, const char *def = "!!") {
switch (i) {
case OMX_VIDEO_HEVCProfileUnknown: return "Unknown"; // unused
case OMX_VIDEO_HEVCProfileMain: return "Main";
case OMX_VIDEO_HEVCProfileMain10: return "Main10";
default: return def;
}
}
inline static const char *asString(OMX_VIDEO_HEVCLEVELTYPE i, const char *def = "!!") {
switch (i) {
case OMX_VIDEO_HEVCLevelUnknown: return "LevelUnknown"; // unused
case OMX_VIDEO_HEVCMainTierLevel1: return "MainTierLevel1";
case OMX_VIDEO_HEVCHighTierLevel1: return "HighTierLevel1";
case OMX_VIDEO_HEVCMainTierLevel2: return "MainTierLevel2";
case OMX_VIDEO_HEVCHighTierLevel2: return "HighTierLevel2";
case OMX_VIDEO_HEVCMainTierLevel21: return "MainTierLevel21";
case OMX_VIDEO_HEVCHighTierLevel21: return "HighTierLevel21";
case OMX_VIDEO_HEVCMainTierLevel3: return "MainTierLevel3";
case OMX_VIDEO_HEVCHighTierLevel3: return "HighTierLevel3";
case OMX_VIDEO_HEVCMainTierLevel31: return "MainTierLevel31";
case OMX_VIDEO_HEVCHighTierLevel31: return "HighTierLevel31";
case OMX_VIDEO_HEVCMainTierLevel4: return "MainTierLevel4";
case OMX_VIDEO_HEVCHighTierLevel4: return "HighTierLevel4";
case OMX_VIDEO_HEVCMainTierLevel41: return "MainTierLevel41";
case OMX_VIDEO_HEVCHighTierLevel41: return "HighTierLevel41";
case OMX_VIDEO_HEVCMainTierLevel5: return "MainTierLevel5";
case OMX_VIDEO_HEVCHighTierLevel5: return "HighTierLevel5";
case OMX_VIDEO_HEVCMainTierLevel51: return "MainTierLevel51";
case OMX_VIDEO_HEVCHighTierLevel51: return "HighTierLevel51";
case OMX_VIDEO_HEVCMainTierLevel52: return "MainTierLevel52";
case OMX_VIDEO_HEVCHighTierLevel52: return "HighTierLevel52";
case OMX_VIDEO_HEVCMainTierLevel6: return "MainTierLevel6";
case OMX_VIDEO_HEVCHighTierLevel6: return "HighTierLevel6";
case OMX_VIDEO_HEVCMainTierLevel61: return "MainTierLevel61";
case OMX_VIDEO_HEVCHighTierLevel61: return "HighTierLevel61";
case OMX_VIDEO_HEVCMainTierLevel62: return "MainTierLevel62";
case OMX_VIDEO_HEVCHighTierLevel62: return "HighTierLevel62";
default: return def;
}
}
#endif // AS_STRING_FOR_OMX_VIDEOEXT_H
#endif // OMX_VideoExt_h
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,102 @@
/*
* Copyright (c) 2010 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/** OMX_AudioExt.h - OpenMax IL version 1.1.2
* The OMX_AudioExt header file contains extensions to the
* definitions used by both the application and the component to
* access video items.
*/
#ifndef OMX_AudioExt_h
#define OMX_AudioExt_h
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Each OMX header shall include all required header files to allow the
* header to compile without errors. The includes below are required
* for this header file to compile successfully
*/
#include <OMX_Core.h>
#define OMX_AUDIO_AACToolAndroidSSBR (OMX_AUDIO_AACToolVendor << 0) /**< SSBR: MPEG-4 Single-rate (downsampled) Spectral Band Replication tool allowed or active */
#define OMX_AUDIO_AACToolAndroidDSBR (OMX_AUDIO_AACToolVendor << 1) /**< DSBR: MPEG-4 Dual-rate Spectral Band Replication tool allowed or active */
typedef enum OMX_AUDIO_CODINGEXTTYPE {
OMX_AUDIO_CodingAndroidUnused = OMX_AUDIO_CodingKhronosExtensions + 0x00100000,
OMX_AUDIO_CodingAndroidAC3, /**< AC3 encoded data */
OMX_AUDIO_CodingAndroidOPUS, /**< OPUS encoded data */
OMX_AUDIO_CodingAndroidEAC3, /**< EAC3 encoded data */
} OMX_AUDIO_CODINGEXTTYPE;
typedef struct OMX_AUDIO_PARAM_ANDROID_AC3TYPE {
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U32 nPortIndex; /**< port that this structure applies to */
OMX_U32 nChannels; /**< Number of channels */
OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for
variable or unknown sampling rate. */
} OMX_AUDIO_PARAM_ANDROID_AC3TYPE;
typedef struct OMX_AUDIO_PARAM_ANDROID_EAC3TYPE {
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U32 nPortIndex; /**< port that this structure applies to */
OMX_U32 nChannels; /**< Number of channels */
OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for
variable or unknown sampling rate. */
} OMX_AUDIO_PARAM_ANDROID_EAC3TYPE;
typedef struct OMX_AUDIO_PARAM_ANDROID_OPUSTYPE {
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U32 nPortIndex; /**< port that this structure applies to */
OMX_U32 nChannels; /**< Number of channels */
OMX_U32 nBitRate; /**< Bit rate of the encoded data data. Use 0 for variable
rate or unknown bit rates. Encoding is set to the
bitrate closest to specified value (in bps) */
OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for
variable or unknown sampling rate. */
OMX_U32 nAudioBandWidth; /**< Audio band width (in Hz) to which an encoder should
limit the audio signal. Use 0 to let encoder decide */
} OMX_AUDIO_PARAM_ANDROID_OPUSTYPE;
typedef struct OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE {
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_S32 nMaxOutputChannels; /**< Maximum channel count to be output, -1 if unspecified, 0 if downmixing disabled */
OMX_S32 nDrcCut; /**< The DRC attenuation factor, between 0 and 127, -1 if unspecified */
OMX_S32 nDrcBoost; /**< The DRC amplification factor, between 0 and 127, -1 if unspecified */
OMX_S32 nHeavyCompression; /**< 0 for light compression, 1 for heavy compression, -1 if unspecified */
OMX_S32 nTargetReferenceLevel; /**< Target reference level, between 0 and 127, -1 if unspecified */
OMX_S32 nEncodedTargetLevel; /**< Target reference level assumed at the encoder, between 0 and 127, -1 if unspecified */
OMX_S32 nPCMLimiterEnable; /**< Signal level limiting, 0 for disable, 1 for enable, -1 if unspecified */
} OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* OMX_AudioExt_h */
/* File EOF */
@@ -0,0 +1,596 @@
/* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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) 2008 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/** OMX_Component.h - OpenMax IL version 1.1.2
* The OMX_Component header file contains the definitions used to define
* the public interface of a component. This header file is intended to
* be used by both the application and the component.
*/
#ifndef OMX_Component_h
#define OMX_Component_h
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Each OMX header must include all required header files to allow the
* header to compile without errors. The includes below are required
* for this header file to compile successfully
*/
#include <OMX_Audio.h>
#include <OMX_Video.h>
#include <OMX_Image.h>
#include <OMX_Other.h>
/** @ingroup comp */
typedef enum OMX_PORTDOMAINTYPE {
OMX_PortDomainAudio,
OMX_PortDomainVideo,
OMX_PortDomainImage,
OMX_PortDomainOther,
OMX_PortDomainKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
OMX_PortDomainVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
OMX_PortDomainMax = 0x7ffffff
} OMX_PORTDOMAINTYPE;
/** @ingroup comp */
typedef struct OMX_PARAM_PORTDEFINITIONTYPE {
OMX_U32 nSize; /**< Size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U32 nPortIndex; /**< Port number the structure applies to */
OMX_DIRTYPE eDir; /**< Direction (input or output) of this port */
OMX_U32 nBufferCountActual; /**< The actual number of buffers allocated on this port */
OMX_U32 nBufferCountMin; /**< The minimum number of buffers this port requires */
OMX_U32 nBufferSize; /**< Size, in bytes, for buffers to be used for this channel */
OMX_BOOL bEnabled; /**< Ports default to enabled and are enabled/disabled by
OMX_CommandPortEnable/OMX_CommandPortDisable.
When disabled a port is unpopulated. A disabled port
is not populated with buffers on a transition to IDLE. */
OMX_BOOL bPopulated; /**< Port is populated with all of its buffers as indicated by
nBufferCountActual. A disabled port is always unpopulated.
An enabled port is populated on a transition to OMX_StateIdle
and unpopulated on a transition to loaded. */
OMX_PORTDOMAINTYPE eDomain; /**< Domain of the port. Determines the contents of metadata below. */
union {
OMX_AUDIO_PORTDEFINITIONTYPE audio;
OMX_VIDEO_PORTDEFINITIONTYPE video;
OMX_IMAGE_PORTDEFINITIONTYPE image;
OMX_OTHER_PORTDEFINITIONTYPE other;
} format;
OMX_BOOL bBuffersContiguous;
OMX_U32 nBufferAlignment;
} OMX_PARAM_PORTDEFINITIONTYPE;
/** @ingroup comp */
typedef struct OMX_PARAM_U32TYPE {
OMX_U32 nSize; /**< Size of this structure, in Bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U32 nPortIndex; /**< port that this structure applies to */
OMX_U32 nU32; /**< U32 value */
} OMX_PARAM_U32TYPE;
/** @ingroup rpm */
typedef enum OMX_SUSPENSIONPOLICYTYPE {
OMX_SuspensionDisabled, /**< No suspension; v1.0 behavior */
OMX_SuspensionEnabled, /**< Suspension allowed */
OMX_SuspensionPolicyKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
OMX_SuspensionPolicyStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
OMX_SuspensionPolicyMax = 0x7fffffff
} OMX_SUSPENSIONPOLICYTYPE;
/** @ingroup rpm */
typedef struct OMX_PARAM_SUSPENSIONPOLICYTYPE {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_SUSPENSIONPOLICYTYPE ePolicy;
} OMX_PARAM_SUSPENSIONPOLICYTYPE;
/** @ingroup rpm */
typedef enum OMX_SUSPENSIONTYPE {
OMX_NotSuspended, /**< component is not suspended */
OMX_Suspended, /**< component is suspended */
OMX_SuspensionKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
OMX_SuspensionVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
OMX_SuspendMax = 0x7FFFFFFF
} OMX_SUSPENSIONTYPE;
/** @ingroup rpm */
typedef struct OMX_PARAM_SUSPENSIONTYPE {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_SUSPENSIONTYPE eType;
} OMX_PARAM_SUSPENSIONTYPE ;
typedef struct OMX_CONFIG_BOOLEANTYPE {
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_BOOL bEnabled;
} OMX_CONFIG_BOOLEANTYPE;
/* Parameter specifying the content uri to use. */
/** @ingroup cp */
typedef struct OMX_PARAM_CONTENTURITYPE
{
OMX_U32 nSize; /**< size of the structure in bytes, including
actual URI name */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U8 contentURI[1]; /**< The URI name */
} OMX_PARAM_CONTENTURITYPE;
/* Parameter specifying the pipe to use. */
/** @ingroup cp */
typedef struct OMX_PARAM_CONTENTPIPETYPE
{
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_HANDLETYPE hPipe; /**< The pipe handle*/
} OMX_PARAM_CONTENTPIPETYPE;
/** @ingroup rpm */
typedef struct OMX_RESOURCECONCEALMENTTYPE {
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_BOOL bResourceConcealmentForbidden; /**< disallow the use of resource concealment
methods (like degrading algorithm quality to
lower resource consumption or functional bypass)
on a component as a resolution to resource conflicts. */
} OMX_RESOURCECONCEALMENTTYPE;
/** @ingroup metadata */
typedef enum OMX_METADATACHARSETTYPE {
OMX_MetadataCharsetUnknown = 0,
OMX_MetadataCharsetASCII,
OMX_MetadataCharsetBinary,
OMX_MetadataCharsetCodePage1252,
OMX_MetadataCharsetUTF8,
OMX_MetadataCharsetJavaConformantUTF8,
OMX_MetadataCharsetUTF7,
OMX_MetadataCharsetImapUTF7,
OMX_MetadataCharsetUTF16LE,
OMX_MetadataCharsetUTF16BE,
OMX_MetadataCharsetGB12345,
OMX_MetadataCharsetHZGB2312,
OMX_MetadataCharsetGB2312,
OMX_MetadataCharsetGB18030,
OMX_MetadataCharsetGBK,
OMX_MetadataCharsetBig5,
OMX_MetadataCharsetISO88591,
OMX_MetadataCharsetISO88592,
OMX_MetadataCharsetISO88593,
OMX_MetadataCharsetISO88594,
OMX_MetadataCharsetISO88595,
OMX_MetadataCharsetISO88596,
OMX_MetadataCharsetISO88597,
OMX_MetadataCharsetISO88598,
OMX_MetadataCharsetISO88599,
OMX_MetadataCharsetISO885910,
OMX_MetadataCharsetISO885913,
OMX_MetadataCharsetISO885914,
OMX_MetadataCharsetISO885915,
OMX_MetadataCharsetShiftJIS,
OMX_MetadataCharsetISO2022JP,
OMX_MetadataCharsetISO2022JP1,
OMX_MetadataCharsetISOEUCJP,
OMX_MetadataCharsetSMS7Bit,
OMX_MetadataCharsetKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
OMX_MetadataCharsetVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
OMX_MetadataCharsetTypeMax= 0x7FFFFFFF
} OMX_METADATACHARSETTYPE;
/** @ingroup metadata */
typedef enum OMX_METADATASCOPETYPE
{
OMX_MetadataScopeAllLevels,
OMX_MetadataScopeTopLevel,
OMX_MetadataScopePortLevel,
OMX_MetadataScopeNodeLevel,
OMX_MetadataScopeKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
OMX_MetadataScopeVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
OMX_MetadataScopeTypeMax = 0x7fffffff
} OMX_METADATASCOPETYPE;
/** @ingroup metadata */
typedef enum OMX_METADATASEARCHMODETYPE
{
OMX_MetadataSearchValueSizeByIndex,
OMX_MetadataSearchItemByIndex,
OMX_MetadataSearchNextItemByKey,
OMX_MetadataSearchKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */
OMX_MetadataSearchVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
OMX_MetadataSearchTypeMax = 0x7fffffff
} OMX_METADATASEARCHMODETYPE;
/** @ingroup metadata */
typedef struct OMX_CONFIG_METADATAITEMCOUNTTYPE
{
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_METADATASCOPETYPE eScopeMode;
OMX_U32 nScopeSpecifier;
OMX_U32 nMetadataItemCount;
} OMX_CONFIG_METADATAITEMCOUNTTYPE;
/** @ingroup metadata */
typedef struct OMX_CONFIG_METADATAITEMTYPE
{
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_METADATASCOPETYPE eScopeMode;
OMX_U32 nScopeSpecifier;
OMX_U32 nMetadataItemIndex;
OMX_METADATASEARCHMODETYPE eSearchMode;
OMX_METADATACHARSETTYPE eKeyCharset;
OMX_U8 nKeySizeUsed;
OMX_U8 nKey[128];
OMX_METADATACHARSETTYPE eValueCharset;
OMX_STRING sLanguageCountry;
OMX_U32 nValueMaxSize;
OMX_U32 nValueSizeUsed;
OMX_U8 nValue[1];
} OMX_CONFIG_METADATAITEMTYPE;
/* @ingroup metadata */
typedef struct OMX_CONFIG_CONTAINERNODECOUNTTYPE
{
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_BOOL bAllKeys;
OMX_U32 nParentNodeID;
OMX_U32 nNumNodes;
} OMX_CONFIG_CONTAINERNODECOUNTTYPE;
/** @ingroup metadata */
typedef struct OMX_CONFIG_CONTAINERNODEIDTYPE
{
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_BOOL bAllKeys;
OMX_U32 nParentNodeID;
OMX_U32 nNodeIndex;
OMX_U32 nNodeID;
OMX_STRING cNodeName;
OMX_BOOL bIsLeafType;
} OMX_CONFIG_CONTAINERNODEIDTYPE;
/** @ingroup metadata */
typedef struct OMX_PARAM_METADATAFILTERTYPE
{
OMX_U32 nSize;
OMX_VERSIONTYPE nVersion;
OMX_BOOL bAllKeys; /* if true then this structure refers to all keys and
* the three key fields below are ignored */
OMX_METADATACHARSETTYPE eKeyCharset;
OMX_U32 nKeySizeUsed;
OMX_U8 nKey [128];
OMX_U32 nLanguageCountrySizeUsed;
OMX_U8 nLanguageCountry[128];
OMX_BOOL bEnabled; /* if true then key is part of filter (e.g.
* retained for query later). If false then
* key is not part of filter */
} OMX_PARAM_METADATAFILTERTYPE;
/** The OMX_HANDLETYPE structure defines the component handle. The component
* handle is used to access all of the component's public methods and also
* contains pointers to the component's private data area. The component
* handle is initialized by the OMX core (with help from the component)
* during the process of loading the component. After the component is
* successfully loaded, the application can safely access any of the
* component's public functions (although some may return an error because
* the state is inappropriate for the access).
*
* @ingroup comp
*/
typedef struct OMX_COMPONENTTYPE
{
/** The size of this structure, in bytes. It is the responsibility
of the allocator of this structure to fill in this value. Since
this structure is allocated by the GetHandle function, this
function will fill in this value. */
OMX_U32 nSize;
/** nVersion is the version of the OMX specification that the structure
is built against. It is the responsibility of the creator of this
structure to initialize this value and every user of this structure
should verify that it knows how to use the exact version of
this structure found herein. */
OMX_VERSIONTYPE nVersion;
/** pComponentPrivate is a pointer to the component private data area.
This member is allocated and initialized by the component when the
component is first loaded. The application should not access this
data area. */
OMX_PTR pComponentPrivate;
/** pApplicationPrivate is a pointer that is a parameter to the
OMX_GetHandle method, and contains an application private value
provided by the IL client. This application private data is
returned to the IL Client by OMX in all callbacks */
OMX_PTR pApplicationPrivate;
/** refer to OMX_GetComponentVersion in OMX_core.h or the OMX IL
specification for details on the GetComponentVersion method.
*/
OMX_ERRORTYPE (*GetComponentVersion)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_OUT OMX_STRING pComponentName,
OMX_OUT OMX_VERSIONTYPE* pComponentVersion,
OMX_OUT OMX_VERSIONTYPE* pSpecVersion,
OMX_OUT OMX_UUIDTYPE* pComponentUUID);
/** refer to OMX_SendCommand in OMX_core.h or the OMX IL
specification for details on the SendCommand method.
*/
OMX_ERRORTYPE (*SendCommand)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_COMMANDTYPE Cmd,
OMX_IN OMX_U32 nParam1,
OMX_IN OMX_PTR pCmdData);
/** refer to OMX_GetParameter in OMX_core.h or the OMX IL
specification for details on the GetParameter method.
*/
OMX_ERRORTYPE (*GetParameter)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_INDEXTYPE nParamIndex,
OMX_INOUT OMX_PTR pComponentParameterStructure);
/** refer to OMX_SetParameter in OMX_core.h or the OMX IL
specification for details on the SetParameter method.
*/
OMX_ERRORTYPE (*SetParameter)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_INDEXTYPE nIndex,
OMX_IN OMX_PTR pComponentParameterStructure);
/** refer to OMX_GetConfig in OMX_core.h or the OMX IL
specification for details on the GetConfig method.
*/
OMX_ERRORTYPE (*GetConfig)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_INDEXTYPE nIndex,
OMX_INOUT OMX_PTR pComponentConfigStructure);
/** refer to OMX_SetConfig in OMX_core.h or the OMX IL
specification for details on the SetConfig method.
*/
OMX_ERRORTYPE (*SetConfig)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_INDEXTYPE nIndex,
OMX_IN OMX_PTR pComponentConfigStructure);
/** refer to OMX_GetExtensionIndex in OMX_core.h or the OMX IL
specification for details on the GetExtensionIndex method.
*/
OMX_ERRORTYPE (*GetExtensionIndex)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_STRING cParameterName,
OMX_OUT OMX_INDEXTYPE* pIndexType);
/** refer to OMX_GetState in OMX_core.h or the OMX IL
specification for details on the GetState method.
*/
OMX_ERRORTYPE (*GetState)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_OUT OMX_STATETYPE* pState);
/** The ComponentTunnelRequest method will interact with another OMX
component to determine if tunneling is possible and to setup the
tunneling. The return codes for this method can be used to
determine if tunneling is not possible, or if tunneling is not
supported.
Base profile components (i.e. non-interop) do not support this
method and should return OMX_ErrorNotImplemented
The interop profile component MUST support tunneling to another
interop profile component with a compatible port parameters.
A component may also support proprietary communication.
If proprietary communication is supported the negotiation of
proprietary communication is done outside of OMX in a vendor
specific way. It is only required that the proper result be
returned and the details of how the setup is done is left
to the component implementation.
When this method is invoked when nPort in an output port, the
component will:
1. Populate the pTunnelSetup structure with the output port's
requirements and constraints for the tunnel.
When this method is invoked when nPort in an input port, the
component will:
1. Query the necessary parameters from the output port to
determine if the ports are compatible for tunneling
2. If the ports are compatible, the component should store
the tunnel step provided by the output port
3. Determine which port (either input or output) is the buffer
supplier, and call OMX_SetParameter on the output port to
indicate this selection.
The component will return from this call within 5 msec.
@param [in] hComp
Handle of the component to be accessed. This is the component
handle returned by the call to the OMX_GetHandle method.
@param [in] nPort
nPort is used to select the port on the component to be used
for tunneling.
@param [in] hTunneledComp
Handle of the component to tunnel with. This is the component
handle returned by the call to the OMX_GetHandle method. When
this parameter is 0x0 the component should setup the port for
communication with the application / IL Client.
@param [in] nPortOutput
nPortOutput is used indicate the port the component should
tunnel with.
@param [in] pTunnelSetup
Pointer to the tunnel setup structure. When nPort is an output port
the component should populate the fields of this structure. When
When nPort is an input port the component should review the setup
provided by the component with the output port.
@return OMX_ERRORTYPE
If the command successfully executes, the return code will be
OMX_ErrorNone. Otherwise the appropriate OMX error will be returned.
@ingroup tun
*/
OMX_ERRORTYPE (*ComponentTunnelRequest)(
OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_U32 nPort,
OMX_IN OMX_HANDLETYPE hTunneledComp,
OMX_IN OMX_U32 nTunneledPort,
OMX_INOUT OMX_TUNNELSETUPTYPE* pTunnelSetup);
/** refer to OMX_UseBuffer in OMX_core.h or the OMX IL
specification for details on the UseBuffer method.
@ingroup buf
*/
OMX_ERRORTYPE (*UseBuffer)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr,
OMX_IN OMX_U32 nPortIndex,
OMX_IN OMX_PTR pAppPrivate,
OMX_IN OMX_U32 nSizeBytes,
OMX_IN OMX_U8* pBuffer);
/** refer to OMX_AllocateBuffer in OMX_core.h or the OMX IL
specification for details on the AllocateBuffer method.
@ingroup buf
*/
OMX_ERRORTYPE (*AllocateBuffer)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_INOUT OMX_BUFFERHEADERTYPE** ppBuffer,
OMX_IN OMX_U32 nPortIndex,
OMX_IN OMX_PTR pAppPrivate,
OMX_IN OMX_U32 nSizeBytes);
/** refer to OMX_FreeBuffer in OMX_core.h or the OMX IL
specification for details on the FreeBuffer method.
@ingroup buf
*/
OMX_ERRORTYPE (*FreeBuffer)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_U32 nPortIndex,
OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
/** refer to OMX_EmptyThisBuffer in OMX_core.h or the OMX IL
specification for details on the EmptyThisBuffer method.
@ingroup buf
*/
OMX_ERRORTYPE (*EmptyThisBuffer)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
/** refer to OMX_FillThisBuffer in OMX_core.h or the OMX IL
specification for details on the FillThisBuffer method.
@ingroup buf
*/
OMX_ERRORTYPE (*FillThisBuffer)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
/** The SetCallbacks method is used by the core to specify the callback
structure from the application to the component. This is a blocking
call. The component will return from this call within 5 msec.
@param [in] hComponent
Handle of the component to be accessed. This is the component
handle returned by the call to the GetHandle function.
@param [in] pCallbacks
pointer to an OMX_CALLBACKTYPE structure used to provide the
callback information to the component
@param [in] pAppData
pointer to an application defined value. It is anticipated that
the application will pass a pointer to a data structure or a "this
pointer" in this area to allow the callback (in the application)
to determine the context of the call
@return OMX_ERRORTYPE
If the command successfully executes, the return code will be
OMX_ErrorNone. Otherwise the appropriate OMX error will be returned.
*/
OMX_ERRORTYPE (*SetCallbacks)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_IN OMX_CALLBACKTYPE* pCallbacks,
OMX_IN OMX_PTR pAppData);
/** ComponentDeInit method is used to deinitialize the component
providing a means to free any resources allocated at component
initialization. NOTE: After this call the component handle is
not valid for further use.
@param [in] hComponent
Handle of the component to be accessed. This is the component
handle returned by the call to the GetHandle function.
@return OMX_ERRORTYPE
If the command successfully executes, the return code will be
OMX_ErrorNone. Otherwise the appropriate OMX error will be returned.
*/
OMX_ERRORTYPE (*ComponentDeInit)(
OMX_IN OMX_HANDLETYPE hComponent);
/** @ingroup buf */
OMX_ERRORTYPE (*UseEGLImage)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr,
OMX_IN OMX_U32 nPortIndex,
OMX_IN OMX_PTR pAppPrivate,
OMX_IN void* eglImage);
OMX_ERRORTYPE (*ComponentRoleEnum)(
OMX_IN OMX_HANDLETYPE hComponent,
OMX_OUT OMX_U8 *cRole,
OMX_IN OMX_U32 nIndex);
} OMX_COMPONENTTYPE;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
/* File EOF */

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