openpilot v0.6 release

pull/718/head
Vehicle Researcher 2019-06-28 21:11:30 +00:00
parent ae44a57565
commit 8a9ed94f5f
977 changed files with 90130 additions and 100834 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
venv/
.DS_Store
.tags
.ipynb_checkpoints

View File

@ -4,32 +4,44 @@ ENV PYTHONUNBUFFERED 1
RUN apt-get update && apt-get install -y \
autoconf \
build-essential \
clang \
wget \
bzip2 \
clang \
git \
libglib2.0-0 \
libtool \
python-pip \
libzmq5-dev \
libarchive-dev \
libavcodec-dev \
libavdevice-dev \
libavfilter-dev \
libavresample-dev \
libavutil-dev \
libffi-dev \
libusb-1.0-0 \
libglib2.0-0 \
libssl-dev \
libswscale-dev \
libtool \
libusb-1.0-0 \
libzmq5-dev \
ocl-icd-libopencl1 \
ocl-icd-opencl-dev \
opencl-headers
opencl-headers \
pkg-config \
python-pip \
wget
COPY phonelibs/install_capnp.sh /tmp/install_capnp.sh
RUN /tmp/install_capnp.sh
RUN pip install --upgrade pip==18.0
RUN pip install numpy==1.11.2 scipy==0.18.1 matplotlib==2.1.2
RUN pip install pipenv==2018.11.26
COPY requirements_openpilot.txt /tmp/
RUN pip install -r /tmp/requirements_openpilot.txt
COPY Pipfile /tmp/
COPY Pipfile.lock /tmp/
RUN cd /tmp && pipenv install --deploy --system
ENV PYTHONPATH /tmp/openpilot:$PYTHONPATH
RUN git clone --branch v0.6 https://github.com/commaai/openpilot-tools.git /tmp/openpilot/tools
RUN pip install -r /tmp/openpilot/tools/requirements.txt
COPY ./.pylintrc /tmp/openpilot/.pylintrc
COPY ./common /tmp/openpilot/common
COPY ./cereal /tmp/openpilot/cereal

140
Pipfile 100644
View File

@ -0,0 +1,140 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
ipython = "<6.0"
aenum = "*"
azure-batch = "==4.1.3"
azure-common = "==1.1.16"
azure-nspkg = "==3.0.1"
azure-storage-blob = "==1.3.1"
azure-storage-common = "==1.3.0"
azure-storage-nspkg = "==3.0.0"
bincopy = "*"
bleach = "==1.5.0"
boto = "*"
"boto3" = "*"
celery = "*"
control = "*"
datadog = "*"
decorator = "*"
dlib = "*"
dominate = "*"
elasticsearch = "*"
entium = "==0.1.4"
fasteners = "*"
future = "*"
futures = "*"
gevent = "*"
pycocotools = {git = "https://github.com/cocodataset/cocoapi.git",subdirectory = "PythonAPI"}
gunicorn = "*"
"h5py" = "*"
hexdump = "*"
"html5lib" = "==0.9999999"
imageio = "*"
intervaltree = "*"
ipykernel = "<5.0"
joblib = "*"
json-logging-py = "*"
jupyter = "*"
libarchive = "*"
lru-dict = "*"
lxml = "*"
matplotlib = "==2.2.3"
"mpld3" = "*"
msgpack-python = "*"
nbstripout = "*"
nose-parameterized = "*"
numpy = "==1.14.5"
osmium = "==2.15.0"
pbr = "==5.1.3"
percache = "*"
pprofile = "*"
psutil = "*"
pycurl = "*"
git-pylint-commit-hook = "==2.5.1"
pymongo = "*"
"pynmea2" = "*"
pypolyline = "==0.1.17"
pysendfile = "*"
python-logstash = "*"
pyvcd = "*"
redis = "*"
redlock = "*"
"s2sphere" = "*"
scikit-image = "*"
"subprocess32" = "*"
supervisor = "*"
tenacity = "*"
tensorflow-gpu = "==1.13.0rc0"
"transforms3d" = "*"
utm = "*"
"v4l2" = "*"
visdom = "*"
PyJWT = "==1.4.1"
PyMySQL = "==0.9.2"
Theano = "*"
Werkzeug = "*"
"backports.lzma" = "*"
Flask-Cors = "*"
Flask-SocketIO = "*"
"GeoAlchemy2" = "*"
Keras = ">=2.1.6"
keras-maskrcnn = "*"
keras-retinanet = "*"
Pygments = "*"
PyNaCl = "*"
"PySDL2" = "*"
reverse_geocoder = "*"
Shapely = "*"
SQLAlchemy = "==1.2.7"
uWSGI = "*"
scipy = "*"
fastcluster = "==1.1.25"
backports-abc = "*"
pygame = "*"
simplejson = "*"
[packages]
overpy = {git = "https://github.com/commaai/python-overpy.git",ref = "f86529af402d4642e1faeb146671c40284007323"}
atomicwrites = "*"
cffi = "*"
crcmod = "*"
hexdump = "*"
libusb1 = "*"
numpy = "*"
psutil = "*"
pycapnp = "*"
cryptography = "*"
pyserial = "*"
python-dateutil = "*"
pyzmq = "*"
raven = "*"
requests = "*"
setproctitle = "*"
six = "*"
smbus2 = "*"
sympy = "*"
tqdm = "*"
Cython = "*"
PyYAML = "*"
websocket_client = "*"
Logentries = {git = "https://github.com/commaai/le_python.git",ref = "5eef8f5be5929d33973e1b10e686fa0cdcd6792f"}
urllib3 = "*"
chardet = "*"
idna = "*"
gunicorn = "*"
utm = "*"
json-rpc = "*"
Flask = "*"
PyJWT = "*"
"Jinja2" = "*"
nose = "*"
pyflakes = "*"
pylint = "*"
pycryptodome = "*"
[requires]
python_version = "2.7"

2810
Pipfile.lock generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
[![](https://i.imgur.com/xY2gdHv.png)](#)
[![](https://i.imgur.com/UetIFyH.jpg)](#)
Welcome to openpilot
======
@ -91,13 +91,15 @@ Supported Cars
| Kia | Optima 2019 | SCC + LKAS | Yes | Stock | 0mph | 0mph | Custom<sup>6</sup>|
| Kia | Sorento 2018 | All | Yes | Stock | 0mph | 0mph | Custom<sup>6</sup>|
| Kia | Stinger 2018 | SCC + LKAS | Yes | Stock | 0mph | 0mph | Custom<sup>6</sup>|
| Lexus | ES Hybrid 2019 | All | Yes | Yes | 0mph | 0mph | Toyota |
| Lexus | RX Hybrid 2016-19 | All | Yes | Yes<sup>2</sup>| 0mph | 0mph | Toyota |
| Subaru | Crosstrek 2018 | EyeSight | Yes | Stock | 0mph | 0mph | Custom<sup>4</sup>|
| Subaru | Impreza 2019 | EyeSight | Yes | Stock | 0mph | 0mph | Custom<sup>4</sup>|
| Toyota | Avalon 2016 | TSS-P | Yes | Yes<sup>2</sup>| 20mph<sup>1</sup>| 0mph | Toyota |
| Toyota | Camry 2018 | All | Yes | Stock | 0mph<sup>5</sup> | 0mph | Toyota |
| Toyota | C-HR 2017-18 | All | Yes | Stock | 0mph | 0mph | Toyota |
| Toyota | Corolla 2017-18 | All | Yes | Yes<sup>2</sup>| 20mph<sup>1</sup>| 0mph | Toyota |
| Toyota | Corolla 2017-19 | All | Yes | Yes<sup>2</sup>| 20mph<sup>1</sup>| 0mph | Toyota |
| Toyota | Corolla 2020 | All | Yes | Yes | 0mph | 0mph | Toyota |
| Toyota | Corolla Hatchback 2019 | All | Yes | Yes | 0mph | 0mph | Toyota |
| Toyota | Highlander 2017-18 | All | Yes | Yes<sup>2</sup>| 0mph | 0mph | Toyota |
| Toyota | Highlander Hybrid 2018 | All | Yes | Yes<sup>2</sup>| 0mph | 0mph | Toyota |

View File

@ -1,3 +1,16 @@
Version 0.6 (2019-07-01)
========================
* New model, with double the pixels and ten times the temporal context!
* Car should not take exits when in the right lane
* openpilot uses only ~65% of the CPU (down from 75%)
* Routes visible in connect/explorer after only 0.2% is uploaded (qlogs)
* loggerd and sensord are open source, every line of openpilot is now open
* Panda safety code is MISRA compliant and ships with a signed version on release2
* New NEOS is 500MB smaller and has a reproducible usr/pipenv
* Lexus ES Hybrid support thanks to wocsor!
* Improve tuning for supported Toyota with TSS2
* Various other stability improvements
Version 0.5.13 (2019-05-31)
==========================
* Reduce panda power consumption by 70%, down to 80mW, when car is off (not for GM)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -4,7 +4,7 @@ from common.basedir import BASEDIR
def get_fingerprint_list():
# read all the folders in selfdrive/car and return a dict where:
# - keys are all the car models for which we have a fingerprint
# - values are lists dicts of messages that constitute the unique
# - values are lists dicts of messages that constitute the unique
# CAN fingerprint of each car model and all its variants
fingerprints = {}
for car_folder in [x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]:

View File

@ -1,7 +1,7 @@
all: simple_kalman_impl.so
simple_kalman_impl.so: simple_kalman_impl.pyx simple_kalman_impl.pxd simple_kalman_setup.py
python simple_kalman_setup.py build_ext --inplace
python2 simple_kalman_setup.py build_ext --inplace
rm -rf build
rm simple_kalman_impl.c

View File

@ -65,6 +65,7 @@ keys = {
"IsGeofenceEnabled": [TxType.PERSISTENT],
"IsMetric": [TxType.PERSISTENT],
"IsUpdateAvailable": [TxType.PERSISTENT],
"IsUploadRawEnabled": [TxType.PERSISTENT],
"IsUploadVideoOverCellularEnabled": [TxType.PERSISTENT],
"LimitSetSpeed": [TxType.PERSISTENT],
"LiveParameters": [TxType.PERSISTENT],

View File

@ -15,6 +15,13 @@ assert monotonic_time
assert sec_since_boot
# time step for each process
DT_CTRL = 0.01 # controlsd
DT_PLAN = 0.05 # mpc
DT_MDL = 0.05 # model
DT_DMON = 0.1 # driver monitoring
ffi = FFI()
ffi.cdef("long syscall(long number, ...);")
libc = ffi.dlopen(None)

View File

@ -1,6 +1,5 @@
import numpy as np
import common.transformations.orientation as orient
import cv2
import math
FULL_FRAME_SIZE = (1164, 874)
@ -126,6 +125,8 @@ def img_from_device(pt_device):
#TODO please use generic img transform below
def rotate_img(img, eulers, crop=None, intrinsics=eon_intrinsics):
import cv2
size = img.shape[:2]
rot = orient.rot_from_euler(eulers)
quadrangle = np.array([[0, 0],
@ -162,6 +163,8 @@ def transform_img(base_img,
output_size=None,
pretransform=None,
top_hacks=True):
import cv2
size = base_img.shape[:2]
if not output_size:
output_size = size[::-1]
@ -204,10 +207,10 @@ def transform_img(base_img,
def yuv_crop(frame, output_size, center=None):
# output_size in camera coordinates so u,v
# center in array coordinates so row, column
import cv2
rgb = cv2.cvtColor(frame, cv2.COLOR_YUV2RGB_I420)
if not center:
center = (rgb.shape[0]/2, rgb.shape[1]/2)
rgb_crop = rgb[center[0] - output_size[1]/2: center[0] + output_size[1]/2,
center[1] - output_size[0]/2: center[1] + output_size[0]/2]
return cv2.cvtColor(rgb_crop, cv2.COLOR_RGB2YUV_I420)

View File

@ -0,0 +1,88 @@
CC = clang
CXX = clang++
PHONELIBS = ../../phonelibs
WARN_FLAGS = -Werror=implicit-function-declaration \
-Werror=incompatible-pointer-types \
-Werror=int-conversion \
-Werror=return-type \
-Werror=format-extra-args
CFLAGS = -std=gnu11 -g -fPIC -O2 $(WARN_FLAGS)
CXXFLAGS = -std=c++11 -g -fPIC -O2 $(WARN_FLAGS)
CURL_FLAGS = -I$(PHONELIBS)/curl/include
CURL_LIBS = $(PHONELIBS)/curl/lib/libcurl.a \
$(PHONELIBS)/zlib/lib/libz.a
BORINGSSL_FLAGS = -I$(PHONELIBS)/boringssl/include
BORINGSSL_LIBS = $(PHONELIBS)/boringssl/lib/libssl_static.a \
$(PHONELIBS)/boringssl/lib/libcrypto_static.a \
NANOVG_FLAGS = -I$(PHONELIBS)/nanovg
JSON11_FLAGS = -I$(PHONELIBS)/json11
OPENGL_LIBS = -lGLESv3
FRAMEBUFFER_LIBS = -lutils -lgui -lEGL
.PHONY: all
all: updater
OBJS = courbd.ttf.o \
../../selfdrive/common/touch.o \
../../selfdrive/common/framebuffer.o \
$(PHONELIBS)/json11/json11.o \
$(PHONELIBS)/nanovg/nanovg.o
DEPS := $(OBJS:.o=.d)
updater: updater.o $(OBJS)
@echo "[ LINK ] $@"
$(CXX) $(CPPFLAGS) -fPIC -o 'updater' $^ \
$(FRAMEBUFFER_LIBS) \
$(CURL_LIBS) \
$(BORINGSSL_LIBS) \
-L/system/vendor/lib64 \
$(OPENGL_LIBS) \
-lcutils -lm -llog
strip updater
courbd.ttf.o: ../../selfdrive/assets/courbd.ttf
@echo "[ bin2o ] $@"
cd '$(dir $<)' && ld -r -b binary '$(notdir $<)' -o '$(abspath $@)'
%.o: %.c
mkdir -p $(@D)
@echo "[ CC ] $@"
$(CC) $(CPPFLAGS) $(CFLAGS) \
-I../.. \
-I$(PHONELIBS)/android_frameworks_native/include \
-I$(PHONELIBS)/android_system_core/include \
-I$(PHONELIBS)/android_hardware_libhardware/include \
$(NANOVG_FLAGS) \
-c -o '$@' '$<'
%.o: %.cc
mkdir -p $(@D)
@echo "[ CXX ] $@"
$(CXX) $(CPPFLAGS) $(CXXFLAGS) \
-I../../selfdrive \
-I../../ \
-I$(PHONELIBS)/android_frameworks_native/include \
-I$(PHONELIBS)/android_system_core/include \
-I$(PHONELIBS)/android_hardware_libhardware/include \
$(NANOVG_FLAGS) \
$(JSON11_FLAGS) \
$(CURL_FLAGS) \
$(BORINGSSL_FLAGS) \
-c -o '$@' '$<'
.PHONY: clean
clean:
rm -f $(OBJS) $(DEPS)
-include $(DEPS)

View File

@ -0,0 +1,7 @@
{
"ota_url": "https://commadist.azureedge.net/neosupdate/ota-signed-c992abb59cbaf6588f51055db52db619061107851773fc8480acb8bb5d77a28f.zip",
"ota_hash": "c992abb59cbaf6588f51055db52db619061107851773fc8480acb8bb5d77a28f",
"recovery_url": "https://commadist.azureedge.net/neosupdate/recovery-af099a84cfd7b91266090779238ac358278948dcde2dcfa0fbca6e8397366f0a.img",
"recovery_len": 15136044,
"recovery_hash": "af099a84cfd7b91266090779238ac358278948dcde2dcfa0fbca6e8397366f0a"
}

Binary file not shown.

View File

@ -0,0 +1,675 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <string>
#include <sstream>
#include <fstream>
#include <mutex>
#include <thread>
#include <curl/curl.h>
#include <openssl/sha.h>
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "nanovg.h"
#define NANOVG_GLES3_IMPLEMENTATION
#include "nanovg_gl.h"
#include "nanovg_gl_utils.h"
#include "json11.hpp"
#include "common/framebuffer.h"
#include "common/touch.h"
#include "common/utilpp.h"
#define USER_AGENT "NEOSUpdater-0.2"
#define MANIFEST_URL_EON_STAGING "https://github.com/commaai/eon-neos/raw/master/update.staging.json"
#define MANIFEST_URL_EON_LOCAL "http://192.168.5.1:8000/neosupdate/update.local.json"
#define MANIFEST_URL_EON "https://github.com/commaai/eon-neos/raw/master/update.json"
const char *manifest_url = MANIFEST_URL_EON;
#define RECOVERY_DEV "/dev/block/bootdevice/by-name/recovery"
#define RECOVERY_COMMAND "/cache/recovery/command"
#define UPDATE_DIR "/data/neoupdate"
extern const uint8_t bin_courbd[] asm("_binary_courbd_ttf_start");
extern const uint8_t bin_courbd_end[] asm("_binary_courbd_ttf_end");
namespace {
std::string sha256_file(std::string fn, size_t limit=0) {
SHA256_CTX ctx;
SHA256_Init(&ctx);
FILE *file = fopen(fn.c_str(), "rb");
if (!file) return "";
const size_t buf_size = 8192;
std::unique_ptr<char[]> buffer( new char[ buf_size ] );
bool read_limit = (limit != 0);
while (true) {
size_t read_size = buf_size;
if (read_limit) read_size = std::min(read_size, limit);
size_t bytes_read = fread(buffer.get(), 1, read_size, file);
if (!bytes_read) break;
SHA256_Update(&ctx, buffer.get(), bytes_read);
if (read_limit) {
limit -= bytes_read;
if (limit == 0) break;
}
}
uint8_t hash[SHA256_DIGEST_LENGTH];
SHA256_Final(hash, &ctx);
fclose(file);
return util::tohex(hash, sizeof(hash));
}
size_t download_string_write(void *ptr, size_t size, size_t nmeb, void *up) {
size_t sz = size * nmeb;
((std::string*)up)->append((char*)ptr, sz);
return sz;
}
std::string download_string(CURL *curl, std::string url) {
std::string os;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
curl_easy_setopt(curl, CURLOPT_RESUME_FROM, 0);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, download_string_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &os);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
return "";
}
return os;
}
size_t download_file_write(void *ptr, size_t size, size_t nmeb, void *up) {
return fwrite(ptr, size, nmeb, (FILE*)up);
}
bool check_battery() {
std::string bat_cap_s = util::read_file("/sys/class/power_supply/battery/capacity");
int bat_cap = atoi(bat_cap_s.c_str());
std::string current_now_s = util::read_file("/sys/class/power_supply/battery/current_now");
int current_now = atoi(current_now_s.c_str());
return bat_cap > 35 || (current_now < 0 && bat_cap > 10);
}
bool check_space() {
struct statvfs stat;
if (statvfs("/data/", &stat) != 0) {
return false;
}
size_t space = stat.f_bsize * stat.f_bavail;
return space > 2000000000ULL; // 2GB
}
static void start_settings_activity(const char* name) {
char launch_cmd[1024];
snprintf(launch_cmd, sizeof(launch_cmd),
"am start -W --ez :settings:show_fragment_as_subsetting true -n 'com.android.settings/.%s'", name);
system(launch_cmd);
}
struct Updater {
bool do_exit = false;
TouchState touch;
int fb_w, fb_h;
EGLDisplay display;
EGLSurface surface;
FramebufferState *fb = NULL;
NVGcontext *vg = NULL;
int font;
std::thread update_thread_handle;
std::mutex lock;
// i hate state machines give me coroutines already
enum UpdateState {
CONFIRMATION,
RUNNING,
ERROR,
};
UpdateState state;
std::string progress_text;
float progress_frac;
std::string error_text;
// button
int b_x, b_w, b_y, b_h;
int balt_x;
CURL *curl = NULL;
Updater() {
touch_init(&touch);
fb = framebuffer_init("updater", 0x00001000, false,
&display, &surface, &fb_w, &fb_h);
assert(fb);
vg = nvgCreateGLES3(NVG_ANTIALIAS | NVG_STENCIL_STROKES | NVG_DEBUG);
assert(vg);
font = nvgCreateFontMem(vg, "courbd", (unsigned char*)bin_courbd, (bin_courbd_end - bin_courbd), 0);
assert(font >= 0);
b_w = 600;
balt_x = 200;
b_x = fb_w-b_w-200;
b_y = 700;
b_h = 250;
state = CONFIRMATION;
}
int download_file_xferinfo(curl_off_t dltotal, curl_off_t dlno,
curl_off_t ultotal, curl_off_t ulnow) {
{
std::lock_guard<std::mutex> guard(lock);
if (dltotal != 0) {
progress_frac = (float) dlno / dltotal;
}
}
// printf("info: %ld %ld %f\n", dltotal, dlno, progress_frac);
return 0;
}
bool download_file(std::string url, std::string out_fn) {
FILE *of = fopen(out_fn.c_str(), "ab");
assert(of);
CURLcode res;
long last_resume_from = 0;
fseek(of, 0, SEEK_END);
int tries = 4;
bool ret = false;
while (true) {
long resume_from = ftell(of);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
curl_easy_setopt(curl, CURLOPT_RESUME_FROM, resume_from);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, download_file_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, of);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, &Updater::download_file_xferinfo);
CURLcode res = curl_easy_perform(curl);
long response_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
// double content_length = 0.0;
// curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &content_length);
printf("download %s res %d, code %ld, resume from %ld\n", url.c_str(), res, response_code, resume_from);
if (res == CURLE_OK) {
ret = true;
break;
} else if (res == CURLE_HTTP_RETURNED_ERROR && response_code == 416) {
// failed because the file is already complete?
ret = true;
break;
} else if (resume_from == last_resume_from) {
// failed and dind't make make forward progress. only retry a couple times
tries--;
if (tries <= 0) {
break;
}
}
last_resume_from = resume_from;
}
// printf("res %d\n", res);
// printf("- %ld %f\n", response_code, content_length);
fclose(of);
return ret;
}
void set_progress(std::string text) {
std::lock_guard<std::mutex> guard(lock);
progress_text = text;
}
void set_error(std::string text) {
std::lock_guard<std::mutex> guard(lock);
error_text = text;
state = ERROR;
}
std::string stage_download(std::string url, std::string hash, std::string name) {
std::string out_fn = UPDATE_DIR "/" + util::base_name(url);
set_progress("downloading " + name + "...");
bool r = download_file(url, out_fn);
if (!r) {
set_error("failed to download " + name);
return "";
}
set_progress("verifying " + name + "...");
std::string fn_hash = sha256_file(out_fn);
printf("got %s hash: %s\n", name.c_str(), hash.c_str());
if (fn_hash != hash) {
set_error(name + " was corrupt");
unlink(out_fn.c_str());
return "";
}
return out_fn;
}
void run_stages() {
curl = curl_easy_init();
assert(curl);
if (!check_battery()) {
set_error("Please plug power in to your EON and wait for charge");
return;
}
if (!check_space()) {
set_error("2GB of free space required to update");
return;
}
mkdir(UPDATE_DIR, 0777);
const int EON = (access("/EON", F_OK) != -1);
set_progress("finding latest version...");
std::string manifest_s;
if (EON) {
manifest_s = download_string(curl, manifest_url);
} else {
// don't update NEO
exit(0);
}
printf("manifest: %s\n", manifest_s.c_str());
std::string err;
auto manifest = json11::Json::parse(manifest_s, err);
if (manifest.is_null() || !err.empty()) {
set_error("failed to load update manifest");
return;
}
std::string ota_url = manifest["ota_url"].string_value();
std::string ota_hash = manifest["ota_hash"].string_value();
std::string recovery_url = manifest["recovery_url"].string_value();
std::string recovery_hash = manifest["recovery_hash"].string_value();
int recovery_len = manifest["recovery_len"].int_value();
// std::string installer_url = manifest["installer_url"].string_value();
// std::string installer_hash = manifest["installer_hash"].string_value();
if (ota_url.empty() || ota_hash.empty()) {
set_error("invalid update manifest");
return;
}
// std::string installer_fn = stage_download(installer_url, installer_hash, "installer");
// if (installer_fn.empty()) {
// //error'd
// return;
// }
std::string recovery_fn;
if (recovery_url.empty() || recovery_hash.empty() || recovery_len == 0) {
set_progress("skipping recovery flash...");
} else {
// only download the recovery if it differs from what's flashed
set_progress("checking recovery...");
std::string existing_recovery_hash = sha256_file(RECOVERY_DEV, recovery_len);
printf("existing recovery hash: %s\n", existing_recovery_hash.c_str());
if (existing_recovery_hash != recovery_hash) {
recovery_fn = stage_download(recovery_url, recovery_hash, "recovery");
if (recovery_fn.empty()) {
// error'd
return;
}
}
}
std::string ota_fn = stage_download(ota_url, ota_hash, "update");
if (ota_fn.empty()) {
//error'd
return;
}
if (!check_battery()) {
set_error("must have at least 35% battery to update");
return;
}
if (!recovery_fn.empty()) {
// flash recovery
set_progress("flashing recovery...");
FILE *flash_file = fopen(recovery_fn.c_str(), "rb");
if (!flash_file) {
set_error("failed to flash recovery");
return;
}
FILE *recovery_dev = fopen(RECOVERY_DEV, "w+b");
if (!recovery_dev) {
fclose(flash_file);
set_error("failed to flash recovery");
return;
}
const size_t buf_size = 4096;
std::unique_ptr<char[]> buffer( new char[ buf_size ] );
while (true) {
size_t bytes_read = fread(buffer.get(), 1, buf_size, flash_file);
if (!bytes_read) break;
size_t bytes_written = fwrite(buffer.get(), 1, bytes_read, recovery_dev);
if (bytes_read != bytes_written) {
fclose(recovery_dev);
fclose(flash_file);
set_error("failed to flash recovery: write failed");
return;
}
}
fclose(recovery_dev);
fclose(flash_file);
set_progress("verifying flash...");
std::string new_recovery_hash = sha256_file(RECOVERY_DEV, recovery_len);
printf("new recovery hash: %s\n", new_recovery_hash.c_str());
if (new_recovery_hash != recovery_hash) {
set_error("recovery flash corrupted");
return;
}
}
// write arguments to recovery
FILE *cmd_file = fopen(RECOVERY_COMMAND, "wb");
if (!cmd_file) {
set_error("failed to reboot into recovery");
return;
}
fprintf(cmd_file, "--update_package=%s\n", ota_fn.c_str());
fclose(cmd_file);
set_progress("rebooting");
// remove the continue.sh so we come back into the setup.
// maybe we should go directly into the installer, but what if we don't come back with internet? :/
//unlink("/data/data/com.termux/files/continue.sh");
// TODO: this should be generic between android versions
// IPowerManager.reboot(confirm=false, reason="recovery", wait=true)
system("service call power 16 i32 0 s16 recovery i32 1");
while(1) pause();
// execl("/system/bin/reboot", "recovery");
// set_error("failed to reboot into recovery");
}
void draw_ack_screen(const char *message, const char *button, const char *altbutton) {
nvgFontSize(vg, 96.0f);
nvgFillColor(vg, nvgRGBA(255,255,255,255));
nvgTextAlign(vg, NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE);
nvgTextBox(vg, 50, 100, fb_w-100, message, NULL);
// draw button
if (button) {
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 255));
nvgRoundedRect(vg, b_x, b_y, b_w, b_h, 20);
nvgFill(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE);
nvgText(vg, b_x+b_w/2, b_y+b_h/2, button, NULL);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(255, 255, 255, 255));
nvgStrokeWidth(vg, 5);
nvgRoundedRect(vg, b_x, b_y, b_w, b_h, 20);
nvgStroke(vg);
}
// draw button
if (altbutton) {
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 255));
nvgRoundedRect(vg, balt_x, b_y, b_w, b_h, 20);
nvgFill(vg);
nvgFillColor(vg, nvgRGBA(255, 255, 255, 255));
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE);
nvgText(vg, balt_x+b_w/2, b_y+b_h/2, altbutton, NULL);
nvgBeginPath(vg);
nvgStrokeColor(vg, nvgRGBA(255, 255, 255, 255));
nvgStrokeWidth(vg, 5);
nvgRoundedRect(vg, balt_x, b_y, b_w, b_h, 20);
nvgStroke(vg);
}
}
void draw_progress_screen() {
// draw progress message
nvgFontSize(vg, 64.0f);
nvgFillColor(vg, nvgRGBA(255,255,255,255));
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_BASELINE);
nvgTextBox(vg, 0, 700, fb_w, progress_text.c_str(), NULL);
// draw progress bar
{
int progress_width = 800;
int progress_x = fb_w/2-progress_width/2;
int progress_y = 768;
int progress_height = 15;
int powerprompt_y = 512;
nvgText(vg, fb_w/2, powerprompt_y, "Ensure EON is connected to power", NULL);
NVGpaint paint = nvgBoxGradient(
vg, progress_x + 1, progress_y + 1,
progress_width - 2, progress_height, 3, 4, nvgRGB(0, 32, 0), nvgRGB(0, 92, 0));
nvgBeginPath(vg);
nvgRoundedRect(vg, progress_x, progress_y, progress_width, progress_height, 3);
nvgFillPaint(vg, paint);
nvgFill(vg);
float value = std::min(std::max(0.0f, progress_frac), 1.0f);
int bar_pos = ((progress_width - 2) * value);
paint = nvgBoxGradient(
vg, progress_x, progress_y,
bar_pos+1.5f, progress_height-1, 3, 4,
nvgRGB(220, 100, 0), nvgRGB(128, 100, 0));
nvgBeginPath(vg);
nvgRoundedRect(
vg, progress_x+1, progress_y+1,
bar_pos, progress_height-2, 3);
nvgFillPaint(vg, paint);
nvgFill(vg);
}
}
void ui_draw() {
std::lock_guard<std::mutex> guard(lock);
nvgBeginFrame(vg, fb_w, fb_h, 1.0f);
switch (state) {
case CONFIRMATION:
draw_ack_screen("An upgrade to NEOS is required.\n\n"
"Your device will now be reset and upgraded. You may want to connect to wifi as download is around 1 GB\nData on device shouldn't be lost.",
"continue",
"wifi");
break;
case RUNNING:
draw_progress_screen();
break;
case ERROR:
draw_ack_screen(("ERROR: " + error_text + "\n\nYou will need to retry").c_str(), NULL, "exit");
break;
}
nvgEndFrame(vg);
}
void ui_update() {
std::lock_guard<std::mutex> guard(lock);
switch (state) {
case ERROR:
case CONFIRMATION: {
int touch_x = -1, touch_y = -1;
int res = touch_poll(&touch, &touch_x, &touch_y, 0);
if (res == 1 && !is_settings_active()) {
if (touch_x >= b_x && touch_x < b_x+b_w && touch_y >= b_y && touch_y < b_y+b_h) {
if (state == CONFIRMATION) {
state = RUNNING;
update_thread_handle = std::thread(&Updater::run_stages, this);
}
}
if (touch_x >= balt_x && touch_x < balt_x+b_w && touch_y >= b_y && touch_y < b_y+b_h) {
if (state == CONFIRMATION) {
start_settings_activity("Settings$WifiSettingsActivity");
} else if (state == ERROR) {
do_exit = 1;
}
}
}
}
default:
break;
}
}
void go() {
while (!do_exit) {
ui_update();
glClearColor(0.19, 0.09, 0.2, 1.0);
glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
ui_draw();
glDisable(GL_BLEND);
eglSwapBuffers(display, surface);
assert(glGetError() == GL_NO_ERROR);
// no simple way to do 30fps vsync with surfaceflinger...
usleep(30000);
}
if (update_thread_handle.joinable()) {
update_thread_handle.join();
}
system("service call power 16 i32 0 i32 0 i32 1");
}
bool is_settings_active() {
FILE *fp;
char sys_output[4096];
fp = popen("/bin/dumpsys window windows", "r");
if (fp == NULL) {
return false;
}
bool active = false;
while (fgets(sys_output, sizeof(sys_output), fp) != NULL) {
if (strstr(sys_output, "mCurrentFocus=null") != NULL) {
break;
}
if (strstr(sys_output, "mCurrentFocus=Window") != NULL) {
active = true;
break;
}
}
pclose(fp);
return active;
}
};
}
int main(int argc, char *argv[]) {
if (argc > 1) {
if (strcmp(argv[1], "local") == 0) {
manifest_url = MANIFEST_URL_EON_LOCAL;
} else if (strcmp(argv[1], "staging") == 0) {
manifest_url = MANIFEST_URL_EON_STAGING;
} else {
manifest_url = argv[1];
}
}
printf("updating from %s\n", manifest_url);
Updater updater;
updater.go();
return 0;
}

View File

@ -1,5 +1,11 @@
#!/usr/bin/bash
export OMP_NUM_THREADS=1
export MKL_NUM_THREADS=1
export NUMEXPR_NUM_THREADS=1
export OPENBLAS_NUM_THREADS=1
export VECLIB_MAXIMUM_THREADS=1
if [ -z "$PASSIVE" ]; then
export PASSIVE="1"
fi

Binary file not shown.

View File

@ -0,0 +1,3 @@
git clone https://github.com/CyanogenMod/android_frameworks_native.git && cd android_frameworks_native
git reset --hard b22bca465e55618a949d9cbdea665a1a3a831241
cp -r include ~/one/phonelibs/android_frameworks_native/

View File

@ -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
/** @} */

View File

@ -0,0 +1,50 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @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
/** @} */

View File

@ -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
/** @} */

View File

@ -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

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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
/** @} */

View File

@ -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

View File

@ -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
/** @} */

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,124 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_BPBINDER_H
#define ANDROID_BPBINDER_H
#include <binder/IBinder.h>
#include <utils/KeyedVector.h>
#include <utils/threads.h>
// ---------------------------------------------------------------------------
namespace android {
class BpBinder : public IBinder
{
public:
BpBinder(int32_t handle);
inline int32_t handle() const { return mHandle; }
virtual const String16& getInterfaceDescriptor() const;
virtual bool isBinderAlive() const;
virtual status_t pingBinder();
virtual status_t dump(int fd, const Vector<String16>& args);
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
virtual status_t linkToDeath(const sp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0);
virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0,
wp<DeathRecipient>* outRecipient = NULL);
virtual void attachObject( const void* objectID,
void* object,
void* cleanupCookie,
object_cleanup_func func);
virtual void* findObject(const void* objectID) const;
virtual void detachObject(const void* objectID);
virtual BpBinder* remoteBinder();
status_t setConstantData(const void* data, size_t size);
void sendObituary();
class ObjectManager
{
public:
ObjectManager();
~ObjectManager();
void attach( const void* objectID,
void* object,
void* cleanupCookie,
IBinder::object_cleanup_func func);
void* find(const void* objectID) const;
void detach(const void* objectID);
void kill();
private:
ObjectManager(const ObjectManager&);
ObjectManager& operator=(const ObjectManager&);
struct entry_t
{
void* object;
void* cleanupCookie;
IBinder::object_cleanup_func func;
};
KeyedVector<const void*, entry_t> mObjects;
};
protected:
virtual ~BpBinder();
virtual void onFirstRef();
virtual void onLastStrongRef(const void* id);
virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
private:
const int32_t mHandle;
struct Obituary {
wp<DeathRecipient> recipient;
void* cookie;
uint32_t flags;
};
void reportOneDeath(const Obituary& obit);
bool isDescriptorCached() const;
mutable Mutex mLock;
volatile int32_t mAlive;
volatile int32_t mObitsSent;
Vector<Obituary>* mObituaries;
ObjectManager mObjects;
Parcel* mConstantData;
mutable String16 mDescriptorCache;
};
}; // namespace android
// ---------------------------------------------------------------------------
#endif // ANDROID_BPBINDER_H

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,150 @@
/*
* Copyright (C) 2005 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
#ifndef ANDROID_IINTERFACE_H
#define ANDROID_IINTERFACE_H
#include <binder/Binder.h>
namespace android {
// ----------------------------------------------------------------------
class IInterface : public virtual RefBase
{
public:
IInterface();
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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,51 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_MEMORY_BASE_H
#define ANDROID_MEMORY_BASE_H
#include <stdlib.h>
#include <stdint.h>
#include <binder/IMemory.h>
namespace android {
// ---------------------------------------------------------------------------
class MemoryBase : public BnMemory
{
public:
MemoryBase(const sp<IMemoryHeap>& heap, ssize_t offset, size_t size);
virtual ~MemoryBase();
virtual sp<IMemoryHeap> getMemory(ssize_t* offset, size_t* size) const;
protected:
size_t getSize() const { return mSize; }
ssize_t getOffset() const { return mOffset; }
const sp<IMemoryHeap>& getHeap() const { return mHeap; }
private:
size_t mSize;
ssize_t mOffset;
sp<IMemoryHeap> mHeap;
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_MEMORY_BASE_H

View File

@ -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

View File

@ -0,0 +1,103 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_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

View File

@ -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

View File

@ -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

View File

@ -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 */

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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 */

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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*/

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,60 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

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